hash
stringlengths
64
64
content
stringlengths
0
1.51M
906e064c11d4429811a4aaaa768d8a360454e88435a7641073325ded25f39f33
from datetime import datetime from functools import partialmethod from io import StringIO from unittest import mock, skipIf from django.core import serializers from django.core.serializers import SerializerDoesNotExist from django.core.serializers.base import ProgressBar from django.db import connection, transaction from django.http import HttpResponse from django.test import SimpleTestCase, override_settings, skipUnlessDBFeature from django.test.utils import Approximate from .models import ( Actor, Article, Author, AuthorProfile, BaseModel, Category, Child, ComplexModel, Movie, Player, ProxyBaseModel, ProxyProxyBaseModel, Score, Team, ) @override_settings( SERIALIZATION_MODULES={ "json2": "django.core.serializers.json", } ) class SerializerRegistrationTests(SimpleTestCase): def setUp(self): self.old_serializers = serializers._serializers serializers._serializers = {} def tearDown(self): serializers._serializers = self.old_serializers def test_register(self): "Registering a new serializer populates the full registry. Refs #14823" serializers.register_serializer('json3', 'django.core.serializers.json') public_formats = serializers.get_public_serializer_formats() self.assertIn('json3', public_formats) self.assertIn('json2', public_formats) self.assertIn('xml', public_formats) def test_unregister(self): "Unregistering a serializer doesn't cause the registry to be repopulated. Refs #14823" serializers.unregister_serializer('xml') serializers.register_serializer('json3', 'django.core.serializers.json') public_formats = serializers.get_public_serializer_formats() self.assertNotIn('xml', public_formats) self.assertIn('json3', public_formats) def test_unregister_unknown_serializer(self): with self.assertRaises(SerializerDoesNotExist): serializers.unregister_serializer("nonsense") def test_builtin_serializers(self): "Requesting a list of serializer formats populates the registry" all_formats = set(serializers.get_serializer_formats()) public_formats = set(serializers.get_public_serializer_formats()) self.assertIn('xml', all_formats), self.assertIn('xml', public_formats) self.assertIn('json2', all_formats) self.assertIn('json2', public_formats) self.assertIn('python', all_formats) self.assertNotIn('python', public_formats) def test_get_unknown_serializer(self): """ #15889: get_serializer('nonsense') raises a SerializerDoesNotExist """ with self.assertRaises(SerializerDoesNotExist): serializers.get_serializer("nonsense") with self.assertRaises(KeyError): serializers.get_serializer("nonsense") # SerializerDoesNotExist is instantiated with the nonexistent format with self.assertRaises(SerializerDoesNotExist) as cm: serializers.get_serializer("nonsense") self.assertEqual(cm.exception.args, ("nonsense",)) def test_get_unknown_deserializer(self): with self.assertRaises(SerializerDoesNotExist): serializers.get_deserializer("nonsense") class SerializersTestBase: serializer_name = None # Set by subclasses to the serialization format name def setUp(self): sports = Category.objects.create(name="Sports") music = Category.objects.create(name="Music") op_ed = Category.objects.create(name="Op-Ed") self.joe = Author.objects.create(name="Joe") self.jane = Author.objects.create(name="Jane") self.a1 = Article( author=self.jane, headline="Poker has no place on ESPN", pub_date=datetime(2006, 6, 16, 11, 00) ) self.a1.save() self.a1.categories.set([sports, op_ed]) self.a2 = Article( author=self.joe, headline="Time to reform copyright", pub_date=datetime(2006, 6, 16, 13, 00, 11, 345) ) self.a2.save() self.a2.categories.set([music, op_ed]) def test_serialize(self): """Basic serialization works.""" serial_str = serializers.serialize(self.serializer_name, Article.objects.all()) self.assertTrue(self._validate_output(serial_str)) def test_serializer_roundtrip(self): """Serialized content can be deserialized.""" serial_str = serializers.serialize(self.serializer_name, Article.objects.all()) models = list(serializers.deserialize(self.serializer_name, serial_str)) self.assertEqual(len(models), 2) def test_serialize_to_stream(self): obj = ComplexModel(field1='first', field2='second', field3='third') obj.save_base(raw=True) # Serialize the test database to a stream for stream in (StringIO(), HttpResponse()): serializers.serialize(self.serializer_name, [obj], indent=2, stream=stream) # Serialize normally for a comparison string_data = serializers.serialize(self.serializer_name, [obj], indent=2) # The two are the same if isinstance(stream, StringIO): self.assertEqual(string_data, stream.getvalue()) else: self.assertEqual(string_data, stream.content.decode()) def test_serialize_specific_fields(self): obj = ComplexModel(field1='first', field2='second', field3='third') obj.save_base(raw=True) # Serialize then deserialize the test database serialized_data = serializers.serialize( self.serializer_name, [obj], indent=2, fields=('field1', 'field3') ) result = next(serializers.deserialize(self.serializer_name, serialized_data)) # The deserialized object contains data in only the serialized fields. self.assertEqual(result.object.field1, 'first') self.assertEqual(result.object.field2, '') self.assertEqual(result.object.field3, 'third') def test_altering_serialized_output(self): """ The ability to create new objects by modifying serialized content. """ old_headline = "Poker has no place on ESPN" new_headline = "Poker has no place on television" serial_str = serializers.serialize(self.serializer_name, Article.objects.all()) serial_str = serial_str.replace(old_headline, new_headline) models = list(serializers.deserialize(self.serializer_name, serial_str)) # Prior to saving, old headline is in place self.assertTrue(Article.objects.filter(headline=old_headline)) self.assertFalse(Article.objects.filter(headline=new_headline)) for model in models: model.save() # After saving, new headline is in place self.assertTrue(Article.objects.filter(headline=new_headline)) self.assertFalse(Article.objects.filter(headline=old_headline)) def test_one_to_one_as_pk(self): """ If you use your own primary key field (such as a OneToOneField), it doesn't appear in the serialized field list - it replaces the pk identifier. """ AuthorProfile.objects.create(author=self.joe, date_of_birth=datetime(1970, 1, 1)) serial_str = serializers.serialize(self.serializer_name, AuthorProfile.objects.all()) self.assertFalse(self._get_field_values(serial_str, 'author')) for obj in serializers.deserialize(self.serializer_name, serial_str): self.assertEqual(obj.object.pk, self.joe.pk) def test_serialize_field_subset(self): """Output can be restricted to a subset of fields""" valid_fields = ('headline', 'pub_date') invalid_fields = ("author", "categories") serial_str = serializers.serialize(self.serializer_name, Article.objects.all(), fields=valid_fields) for field_name in invalid_fields: self.assertFalse(self._get_field_values(serial_str, field_name)) for field_name in valid_fields: self.assertTrue(self._get_field_values(serial_str, field_name)) def test_serialize_unicode(self): """Unicode makes the roundtrip intact""" actor_name = "Za\u017c\u00f3\u0142\u0107" movie_title = 'G\u0119\u015bl\u0105 ja\u017a\u0144' ac = Actor(name=actor_name) mv = Movie(title=movie_title, actor=ac) ac.save() mv.save() serial_str = serializers.serialize(self.serializer_name, [mv]) self.assertEqual(self._get_field_values(serial_str, "title")[0], movie_title) self.assertEqual(self._get_field_values(serial_str, "actor")[0], actor_name) obj_list = list(serializers.deserialize(self.serializer_name, serial_str)) mv_obj = obj_list[0].object self.assertEqual(mv_obj.title, movie_title) def test_serialize_progressbar(self): fake_stdout = StringIO() serializers.serialize( self.serializer_name, Article.objects.all(), progress_output=fake_stdout, object_count=Article.objects.count() ) self.assertTrue( fake_stdout.getvalue().endswith('[' + '.' * ProgressBar.progress_width + ']\n') ) def test_serialize_superfluous_queries(self): """Ensure no superfluous queries are made when serializing ForeignKeys #17602 """ ac = Actor(name='Actor name') ac.save() mv = Movie(title='Movie title', actor_id=ac.pk) mv.save() with self.assertNumQueries(0): serializers.serialize(self.serializer_name, [mv]) def test_serialize_with_null_pk(self): """ Serialized data with no primary key results in a model instance with no id """ category = Category(name="Reference") serial_str = serializers.serialize(self.serializer_name, [category]) pk_value = self._get_pk_values(serial_str)[0] self.assertFalse(pk_value) cat_obj = list(serializers.deserialize(self.serializer_name, serial_str))[0].object self.assertIsNone(cat_obj.id) def test_float_serialization(self): """Float values serialize and deserialize intact""" sc = Score(score=3.4) sc.save() serial_str = serializers.serialize(self.serializer_name, [sc]) deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str)) self.assertEqual(deserial_objs[0].object.score, Approximate(3.4, places=1)) def test_deferred_field_serialization(self): author = Author.objects.create(name='Victor Hugo') author = Author.objects.defer('name').get(pk=author.pk) serial_str = serializers.serialize(self.serializer_name, [author]) deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str)) self.assertIsInstance(deserial_objs[0].object, Author) def test_custom_field_serialization(self): """Custom fields serialize and deserialize intact""" team_str = "Spartak Moskva" player = Player() player.name = "Soslan Djanaev" player.rank = 1 player.team = Team(team_str) player.save() serial_str = serializers.serialize(self.serializer_name, Player.objects.all()) team = self._get_field_values(serial_str, "team") self.assertTrue(team) self.assertEqual(team[0], team_str) deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str)) self.assertEqual(deserial_objs[0].object.team.to_string(), player.team.to_string()) def test_pre_1000ad_date(self): """Year values before 1000AD are properly formatted""" # Regression for #12524 -- dates before 1000AD get prefixed # 0's on the year a = Article.objects.create( author=self.jane, headline="Nobody remembers the early years", pub_date=datetime(1, 2, 3, 4, 5, 6)) serial_str = serializers.serialize(self.serializer_name, [a]) date_values = self._get_field_values(serial_str, "pub_date") self.assertEqual(date_values[0].replace('T', ' '), "0001-02-03 04:05:06") def test_pkless_serialized_strings(self): """ Serialized strings without PKs can be turned into models """ deserial_objs = list(serializers.deserialize(self.serializer_name, self.pkless_str)) for obj in deserial_objs: self.assertFalse(obj.object.id) obj.save() self.assertEqual(Category.objects.all().count(), 5) def test_deterministic_mapping_ordering(self): """Mapping such as fields should be deterministically ordered. (#24558)""" output = serializers.serialize(self.serializer_name, [self.a1], indent=2) categories = self.a1.categories.values_list('pk', flat=True) self.assertEqual(output, self.mapping_ordering_str % { 'article_pk': self.a1.pk, 'author_pk': self.a1.author_id, 'first_category_pk': categories[0], 'second_category_pk': categories[1], }) def test_deserialize_force_insert(self): """Deserialized content can be saved with force_insert as a parameter.""" serial_str = serializers.serialize(self.serializer_name, [self.a1]) deserial_obj = list(serializers.deserialize(self.serializer_name, serial_str))[0] with mock.patch('django.db.models.Model') as mock_model: deserial_obj.save(force_insert=False) mock_model.save_base.assert_called_with(deserial_obj.object, raw=True, using=None, force_insert=False) @skipUnlessDBFeature('can_defer_constraint_checks') def test_serialize_proxy_model(self): BaseModel.objects.create(parent_data=1) base_objects = BaseModel.objects.all() proxy_objects = ProxyBaseModel.objects.all() proxy_proxy_objects = ProxyProxyBaseModel.objects.all() base_data = serializers.serialize("json", base_objects) proxy_data = serializers.serialize("json", proxy_objects) proxy_proxy_data = serializers.serialize("json", proxy_proxy_objects) self.assertEqual(base_data, proxy_data.replace('proxy', '')) self.assertEqual(base_data, proxy_proxy_data.replace('proxy', '')) def test_serialize_inherited_fields(self): child_1 = Child.objects.create(parent_data='a', child_data='b') child_2 = Child.objects.create(parent_data='c', child_data='d') child_1.parent_m2m.add(child_2) child_data = serializers.serialize(self.serializer_name, [child_1, child_2]) self.assertEqual(self._get_field_values(child_data, 'parent_m2m'), []) self.assertEqual(self._get_field_values(child_data, 'parent_data'), []) class SerializerAPITests(SimpleTestCase): def test_stream_class(self): class File: def __init__(self): self.lines = [] def write(self, line): self.lines.append(line) def getvalue(self): return ''.join(self.lines) class Serializer(serializers.json.Serializer): stream_class = File serializer = Serializer() data = serializer.serialize([Score(id=1, score=3.4)]) self.assertIs(serializer.stream_class, File) self.assertIsInstance(serializer.stream, File) self.assertEqual(data, '[{"model": "serializers.score", "pk": 1, "fields": {"score": 3.4}}]') class SerializersTransactionTestBase: available_apps = ['serializers'] @skipUnlessDBFeature('supports_forward_references') def test_forward_refs(self): """ Objects ids can be referenced before they are defined in the serialization data. """ # The deserialization process needs to run in a transaction in order # to test forward reference handling. with transaction.atomic(): objs = serializers.deserialize(self.serializer_name, self.fwd_ref_str) with connection.constraint_checks_disabled(): for obj in objs: obj.save() for model_cls in (Category, Author, Article): self.assertEqual(model_cls.objects.all().count(), 1) art_obj = Article.objects.all()[0] self.assertEqual(art_obj.categories.all().count(), 1) self.assertEqual(art_obj.author.name, "Agnes") def register_tests(test_class, method_name, test_func, exclude=()): """ Dynamically create serializer tests to ensure that all registered serializers are automatically tested. """ for format_ in serializers.get_serializer_formats(): if format_ == 'geojson' or format_ in exclude: continue decorated_func = skipIf( isinstance(serializers.get_serializer(format_), serializers.BadSerializer), 'The Python library for the %s serializer is not installed.' % format_, )(test_func) setattr(test_class, method_name % format_, partialmethod(decorated_func, format_))
5779be6cedc1f593f35d9dd6a507fd1e2367ee0d802e933afbd2bcd0932ddf9b
from django import forms from django.contrib.admin import BooleanFieldListFilter, SimpleListFilter from django.contrib.admin.options import VERTICAL, ModelAdmin, TabularInline from django.contrib.admin.sites import AdminSite from django.core.checks import Error from django.db.models import F, Field, Model from django.db.models.functions import Upper from django.forms.models import BaseModelFormSet from django.test import SimpleTestCase from .models import ( Band, Song, User, ValidationTestInlineModel, ValidationTestModel, ) class CheckTestCase(SimpleTestCase): def assertIsInvalid(self, model_admin, model, msg, id=None, hint=None, invalid_obj=None, admin_site=None): if admin_site is None: admin_site = AdminSite() invalid_obj = invalid_obj or model_admin admin_obj = model_admin(model, admin_site) self.assertEqual(admin_obj.check(), [Error(msg, hint=hint, obj=invalid_obj, id=id)]) def assertIsInvalidRegexp(self, model_admin, model, msg, id=None, hint=None, invalid_obj=None): """ Same as assertIsInvalid but treats the given msg as a regexp. """ invalid_obj = invalid_obj or model_admin admin_obj = model_admin(model, AdminSite()) errors = admin_obj.check() self.assertEqual(len(errors), 1) error = errors[0] self.assertEqual(error.hint, hint) self.assertEqual(error.obj, invalid_obj) self.assertEqual(error.id, id) self.assertRegex(error.msg, msg) def assertIsValid(self, model_admin, model, admin_site=None): if admin_site is None: admin_site = AdminSite() admin_obj = model_admin(model, admin_site) self.assertEqual(admin_obj.check(), []) class RawIdCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): raw_id_fields = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields' must be a list or tuple.", 'admin.E001' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ('non_existent_field',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields[0]' refers to 'non_existent_field', " "which is not an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E002' ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ('name',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields[0]' must be a foreign key or a " "many-to-many field.", 'admin.E003' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ('users',) self.assertIsValid(TestModelAdmin, ValidationTestModel) class FieldsetsCheckTests(CheckTestCase): def test_valid_case(self): class TestModelAdmin(ModelAdmin): fieldsets = (('General', {'fields': ('name',)}),) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_not_iterable(self): class TestModelAdmin(ModelAdmin): fieldsets = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets' must be a list or tuple.", 'admin.E007' ) def test_non_iterable_item(self): class TestModelAdmin(ModelAdmin): fieldsets = ({},) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0]' must be a list or tuple.", 'admin.E008' ) def test_item_not_a_pair(self): class TestModelAdmin(ModelAdmin): fieldsets = ((),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0]' must be of length 2.", 'admin.E009' ) def test_second_element_of_item_not_a_dict(self): class TestModelAdmin(ModelAdmin): fieldsets = (('General', ()),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0][1]' must be a dictionary.", 'admin.E010' ) def test_missing_fields_key(self): class TestModelAdmin(ModelAdmin): fieldsets = (('General', {}),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0][1]' must contain the key 'fields'.", 'admin.E011' ) class TestModelAdmin(ModelAdmin): fieldsets = (('General', {'fields': ('name',)}),) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_specified_both_fields_and_fieldsets(self): class TestModelAdmin(ModelAdmin): fieldsets = (('General', {'fields': ('name',)}),) fields = ['name'] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "Both 'fieldsets' and 'fields' are specified.", 'admin.E005' ) def test_duplicate_fields(self): class TestModelAdmin(ModelAdmin): fieldsets = [(None, {'fields': ['name', 'name']})] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "There are duplicate field(s) in 'fieldsets[0][1]'.", 'admin.E012' ) def test_duplicate_fields_in_fieldsets(self): class TestModelAdmin(ModelAdmin): fieldsets = [ (None, {'fields': ['name']}), (None, {'fields': ['name']}), ] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "There are duplicate field(s) in 'fieldsets[1][1]'.", 'admin.E012' ) def test_fieldsets_with_custom_form_validation(self): class BandAdmin(ModelAdmin): fieldsets = (('Band', {'fields': ('name',)}),) self.assertIsValid(BandAdmin, Band) class FieldsCheckTests(CheckTestCase): def test_duplicate_fields_in_fields(self): class TestModelAdmin(ModelAdmin): fields = ['name', 'name'] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fields' contains duplicate field(s).", 'admin.E006' ) def test_inline(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel fields = 10 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fields' must be a list or tuple.", 'admin.E004', invalid_obj=ValidationTestInline ) class FormCheckTests(CheckTestCase): def test_invalid_type(self): class FakeForm: pass class TestModelAdmin(ModelAdmin): form = FakeForm class TestModelAdminWithNoForm(ModelAdmin): form = 'not a form' for model_admin in (TestModelAdmin, TestModelAdminWithNoForm): with self.subTest(model_admin): self.assertIsInvalid( model_admin, ValidationTestModel, "The value of 'form' must inherit from 'BaseModelForm'.", 'admin.E016' ) def test_fieldsets_with_custom_form_validation(self): class BandAdmin(ModelAdmin): fieldsets = (('Band', {'fields': ('name',)}),) self.assertIsValid(BandAdmin, Band) def test_valid_case(self): class AdminBandForm(forms.ModelForm): delete = forms.BooleanField() class BandAdmin(ModelAdmin): form = AdminBandForm fieldsets = ( ('Band', { 'fields': ('name', 'bio', 'sign_date', 'delete') }), ) self.assertIsValid(BandAdmin, Band) class FilterVerticalCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): filter_vertical = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical' must be a list or tuple.", 'admin.E017' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): filter_vertical = ('non_existent_field',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical[0]' refers to 'non_existent_field', " "which is not an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E019' ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): filter_vertical = ('name',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical[0]' must be a many-to-many field.", 'admin.E020' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): filter_vertical = ('users',) self.assertIsValid(TestModelAdmin, ValidationTestModel) class FilterHorizontalCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): filter_horizontal = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_horizontal' must be a list or tuple.", 'admin.E018' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): filter_horizontal = ('non_existent_field',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_horizontal[0]' refers to 'non_existent_field', " "which is not an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E019' ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): filter_horizontal = ('name',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_horizontal[0]' must be a many-to-many field.", 'admin.E020' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): filter_horizontal = ('users',) self.assertIsValid(TestModelAdmin, ValidationTestModel) class RadioFieldsCheckTests(CheckTestCase): def test_not_dictionary(self): class TestModelAdmin(ModelAdmin): radio_fields = () self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields' must be a dictionary.", 'admin.E021' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): radio_fields = {'non_existent_field': VERTICAL} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields' refers to 'non_existent_field', " "which is not an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E022' ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): radio_fields = {'name': VERTICAL} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields' refers to 'name', which is not an instance " "of ForeignKey, and does not have a 'choices' definition.", 'admin.E023' ) def test_invalid_value(self): class TestModelAdmin(ModelAdmin): radio_fields = {'state': None} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields[\"state\"]' must be either admin.HORIZONTAL or admin.VERTICAL.", 'admin.E024' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): radio_fields = {'state': VERTICAL} self.assertIsValid(TestModelAdmin, ValidationTestModel) class PrepopulatedFieldsCheckTests(CheckTestCase): def test_not_list_or_tuple(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {'slug': 'test'} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, 'The value of \'prepopulated_fields["slug"]\' must be a list ' 'or tuple.', 'admin.E029' ) def test_not_dictionary(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = () self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' must be a dictionary.", 'admin.E026' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {'non_existent_field': ('slug',)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' refers to 'non_existent_field', " "which is not an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E027' ) def test_missing_field_again(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {'slug': ('non_existent_field',)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields[\"slug\"][0]' refers to 'non_existent_field', " "which is not an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E030' ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {'users': ('name',)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' refers to 'users', which must not be " "a DateTimeField, a ForeignKey, a OneToOneField, or a ManyToManyField.", 'admin.E028' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {'slug': ('name',)} self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_one_to_one_field(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {'best_friend': ('name',)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' refers to 'best_friend', which must not be " "a DateTimeField, a ForeignKey, a OneToOneField, or a ManyToManyField.", 'admin.E028' ) class ListDisplayTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): list_display = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display' must be a list or tuple.", 'admin.E107' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): list_display = ('non_existent_field',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display[0]' refers to 'non_existent_field', " "which is not a callable, an attribute of 'TestModelAdmin', " "or an attribute or method on 'modeladmin.ValidationTestModel'.", 'admin.E108' ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): list_display = ('users',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display[0]' must not be a ManyToManyField.", 'admin.E109' ) def test_valid_case(self): def a_callable(obj): pass class TestModelAdmin(ModelAdmin): def a_method(self, obj): pass list_display = ('name', 'decade_published_in', 'a_method', a_callable) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_valid_field_accessible_via_instance(self): class PositionField(Field): """Custom field accessible only via instance.""" def contribute_to_class(self, cls, name): super().contribute_to_class(cls, name) setattr(cls, self.name, self) def __get__(self, instance, owner): if instance is None: raise AttributeError() class TestModel(Model): field = PositionField() class TestModelAdmin(ModelAdmin): list_display = ('field',) self.assertIsValid(TestModelAdmin, TestModel) class ListDisplayLinksCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): list_display_links = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display_links' must be a list, a tuple, or None.", 'admin.E110' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): list_display_links = ('non_existent_field',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, ( "The value of 'list_display_links[0]' refers to " "'non_existent_field', which is not defined in 'list_display'." ), 'admin.E111' ) def test_missing_in_list_display(self): class TestModelAdmin(ModelAdmin): list_display_links = ('name',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display_links[0]' refers to 'name', which is not defined in 'list_display'.", 'admin.E111' ) def test_valid_case(self): def a_callable(obj): pass class TestModelAdmin(ModelAdmin): def a_method(self, obj): pass list_display = ('name', 'decade_published_in', 'a_method', a_callable) list_display_links = ('name', 'decade_published_in', 'a_method', a_callable) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_None_is_valid_case(self): class TestModelAdmin(ModelAdmin): list_display_links = None self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_list_display_links_check_skipped_if_get_list_display_overridden(self): """ list_display_links check is skipped if get_list_display() is overridden. """ class TestModelAdmin(ModelAdmin): list_display_links = ['name', 'subtitle'] def get_list_display(self, request): pass self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_list_display_link_checked_for_list_tuple_if_get_list_display_overridden(self): """ list_display_links is checked for list/tuple/None even if get_list_display() is overridden. """ class TestModelAdmin(ModelAdmin): list_display_links = 'non-list/tuple' def get_list_display(self, request): pass self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display_links' must be a list, a tuple, or None.", 'admin.E110' ) class ListFilterTests(CheckTestCase): def test_list_filter_validation(self): class TestModelAdmin(ModelAdmin): list_filter = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter' must be a list or tuple.", 'admin.E112' ) def test_not_list_filter_class(self): class TestModelAdmin(ModelAdmin): list_filter = ['RandomClass'] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' refers to 'RandomClass', which " "does not refer to a Field.", 'admin.E116' ) def test_callable(self): def random_callable(): pass class TestModelAdmin(ModelAdmin): list_filter = [random_callable] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must inherit from 'ListFilter'.", 'admin.E113' ) def test_not_callable(self): class TestModelAdmin(ModelAdmin): list_filter = [[42, 42]] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.", 'admin.E115' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): list_filter = ('non_existent_field',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' refers to 'non_existent_field', " "which does not refer to a Field.", 'admin.E116' ) def test_not_filter(self): class RandomClass: pass class TestModelAdmin(ModelAdmin): list_filter = (RandomClass,) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must inherit from 'ListFilter'.", 'admin.E113' ) def test_not_filter_again(self): class RandomClass: pass class TestModelAdmin(ModelAdmin): list_filter = (('is_active', RandomClass),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.", 'admin.E115' ) def test_not_filter_again_again(self): class AwesomeFilter(SimpleListFilter): def get_title(self): return 'awesomeness' def get_choices(self, request): return (('bit', 'A bit awesome'), ('very', 'Very awesome')) def get_queryset(self, cl, qs): return qs class TestModelAdmin(ModelAdmin): list_filter = (('is_active', AwesomeFilter),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.", 'admin.E115' ) def test_list_filter_is_func(self): def get_filter(): pass class TestModelAdmin(ModelAdmin): list_filter = [get_filter] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must inherit from 'ListFilter'.", 'admin.E113' ) def test_not_associated_with_field_name(self): class TestModelAdmin(ModelAdmin): list_filter = (BooleanFieldListFilter,) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must not inherit from 'FieldListFilter'.", 'admin.E114' ) def test_valid_case(self): class AwesomeFilter(SimpleListFilter): def get_title(self): return 'awesomeness' def get_choices(self, request): return (('bit', 'A bit awesome'), ('very', 'Very awesome')) def get_queryset(self, cl, qs): return qs class TestModelAdmin(ModelAdmin): list_filter = ('is_active', AwesomeFilter, ('is_active', BooleanFieldListFilter), 'no') self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListPerPageCheckTests(CheckTestCase): def test_not_integer(self): class TestModelAdmin(ModelAdmin): list_per_page = 'hello' self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_per_page' must be an integer.", 'admin.E118' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): list_per_page = 100 self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListMaxShowAllCheckTests(CheckTestCase): def test_not_integer(self): class TestModelAdmin(ModelAdmin): list_max_show_all = 'hello' self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_max_show_all' must be an integer.", 'admin.E119' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): list_max_show_all = 200 self.assertIsValid(TestModelAdmin, ValidationTestModel) class SearchFieldsCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): search_fields = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'search_fields' must be a list or tuple.", 'admin.E126' ) class DateHierarchyCheckTests(CheckTestCase): def test_missing_field(self): class TestModelAdmin(ModelAdmin): date_hierarchy = 'non_existent_field' self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'date_hierarchy' refers to 'non_existent_field', " "which does not refer to a Field.", 'admin.E127' ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): date_hierarchy = 'name' self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'date_hierarchy' must be a DateField or DateTimeField.", 'admin.E128' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): date_hierarchy = 'pub_date' self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_related_valid_case(self): class TestModelAdmin(ModelAdmin): date_hierarchy = 'band__sign_date' self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_related_invalid_field_type(self): class TestModelAdmin(ModelAdmin): date_hierarchy = 'band__name' self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'date_hierarchy' must be a DateField or DateTimeField.", 'admin.E128' ) class OrderingCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): ordering = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering' must be a list or tuple.", 'admin.E031' ) class TestModelAdmin(ModelAdmin): ordering = ('non_existent_field',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering[0]' refers to 'non_existent_field', " "which is not an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E033' ) def test_random_marker_not_alone(self): class TestModelAdmin(ModelAdmin): ordering = ('?', 'name') self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering' has the random ordering marker '?', but contains " "other fields as well.", 'admin.E032', hint='Either remove the "?", or remove the other fields.' ) def test_valid_random_marker_case(self): class TestModelAdmin(ModelAdmin): ordering = ('?',) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_valid_complex_case(self): class TestModelAdmin(ModelAdmin): ordering = ('band__name',) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_valid_case(self): class TestModelAdmin(ModelAdmin): ordering = ('name', 'pk') self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_invalid_expression(self): class TestModelAdmin(ModelAdmin): ordering = (F('nonexistent'), ) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering[0]' refers to 'nonexistent', which is not " "an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E033' ) def test_valid_expression(self): class TestModelAdmin(ModelAdmin): ordering = (Upper('name'), Upper('band__name').desc()) self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListSelectRelatedCheckTests(CheckTestCase): def test_invalid_type(self): class TestModelAdmin(ModelAdmin): list_select_related = 1 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_select_related' must be a boolean, tuple or list.", 'admin.E117' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): list_select_related = False self.assertIsValid(TestModelAdmin, ValidationTestModel) class SaveAsCheckTests(CheckTestCase): def test_not_boolean(self): class TestModelAdmin(ModelAdmin): save_as = 1 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'save_as' must be a boolean.", 'admin.E101' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): save_as = True self.assertIsValid(TestModelAdmin, ValidationTestModel) class SaveOnTopCheckTests(CheckTestCase): def test_not_boolean(self): class TestModelAdmin(ModelAdmin): save_on_top = 1 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'save_on_top' must be a boolean.", 'admin.E102' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): save_on_top = True self.assertIsValid(TestModelAdmin, ValidationTestModel) class InlinesCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): inlines = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'inlines' must be a list or tuple.", 'admin.E103' ) def test_not_correct_inline_field(self): class TestModelAdmin(ModelAdmin): inlines = [42] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"'.*\.TestModelAdmin' must inherit from 'InlineModelAdmin'\.", 'admin.E104' ) def test_not_model_admin(self): class ValidationTestInline: pass class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"'.*\.ValidationTestInline' must inherit from 'InlineModelAdmin'\.", 'admin.E104' ) def test_missing_model_field(self): class ValidationTestInline(TabularInline): pass class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"'.*\.ValidationTestInline' must have a 'model' attribute\.", 'admin.E105' ) def test_invalid_model_type(self): class SomethingBad: pass class ValidationTestInline(TabularInline): model = SomethingBad class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"The value of '.*\.ValidationTestInline.model' must be a Model\.", 'admin.E106' ) def test_invalid_model(self): class ValidationTestInline(TabularInline): model = 'Not a class' class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"The value of '.*\.ValidationTestInline.model' must be a Model\.", 'admin.E106' ) def test_invalid_callable(self): def random_obj(): pass class TestModelAdmin(ModelAdmin): inlines = [random_obj] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"'.*\.random_obj' must inherit from 'InlineModelAdmin'\.", 'admin.E104' ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class FkNameCheckTests(CheckTestCase): def test_missing_field(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel fk_name = 'non_existent_field' class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "'modeladmin.ValidationTestInlineModel' has no field named 'non_existent_field'.", 'admin.E202', invalid_obj=ValidationTestInline ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel fk_name = 'parent' class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class ExtraCheckTests(CheckTestCase): def test_not_integer(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel extra = 'hello' class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'extra' must be an integer.", 'admin.E203', invalid_obj=ValidationTestInline ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel extra = 2 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class MaxNumCheckTests(CheckTestCase): def test_not_integer(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel max_num = 'hello' class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'max_num' must be an integer.", 'admin.E204', invalid_obj=ValidationTestInline ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel max_num = 2 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class MinNumCheckTests(CheckTestCase): def test_not_integer(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel min_num = 'hello' class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'min_num' must be an integer.", 'admin.E205', invalid_obj=ValidationTestInline ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel min_num = 2 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class FormsetCheckTests(CheckTestCase): def test_invalid_type(self): class FakeFormSet: pass class ValidationTestInline(TabularInline): model = ValidationTestInlineModel formset = FakeFormSet class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'formset' must inherit from 'BaseModelFormSet'.", 'admin.E206', invalid_obj=ValidationTestInline ) def test_inline_without_formset_class(self): class ValidationTestInlineWithoutFormsetClass(TabularInline): model = ValidationTestInlineModel formset = 'Not a FormSet Class' class TestModelAdminWithoutFormsetClass(ModelAdmin): inlines = [ValidationTestInlineWithoutFormsetClass] self.assertIsInvalid( TestModelAdminWithoutFormsetClass, ValidationTestModel, "The value of 'formset' must inherit from 'BaseModelFormSet'.", 'admin.E206', invalid_obj=ValidationTestInlineWithoutFormsetClass ) def test_valid_case(self): class RealModelFormSet(BaseModelFormSet): pass class ValidationTestInline(TabularInline): model = ValidationTestInlineModel formset = RealModelFormSet class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListDisplayEditableTests(CheckTestCase): def test_list_display_links_is_none(self): """ list_display and list_editable can contain the same values when list_display_links is None """ class ProductAdmin(ModelAdmin): list_display = ['name', 'slug', 'pub_date'] list_editable = list_display list_display_links = None self.assertIsValid(ProductAdmin, ValidationTestModel) def test_list_display_first_item_same_as_list_editable_first_item(self): """ The first item in list_display can be the same as the first in list_editable. """ class ProductAdmin(ModelAdmin): list_display = ['name', 'slug', 'pub_date'] list_editable = ['name', 'slug'] list_display_links = ['pub_date'] self.assertIsValid(ProductAdmin, ValidationTestModel) def test_list_display_first_item_in_list_editable(self): """ The first item in list_display can be in list_editable as long as list_display_links is defined. """ class ProductAdmin(ModelAdmin): list_display = ['name', 'slug', 'pub_date'] list_editable = ['slug', 'name'] list_display_links = ['pub_date'] self.assertIsValid(ProductAdmin, ValidationTestModel) def test_list_display_first_item_same_as_list_editable_no_list_display_links(self): """ The first item in list_display cannot be the same as the first item in list_editable if list_display_links is not defined. """ class ProductAdmin(ModelAdmin): list_display = ['name'] list_editable = ['name'] self.assertIsInvalid( ProductAdmin, ValidationTestModel, "The value of 'list_editable[0]' refers to the first field " "in 'list_display' ('name'), which cannot be used unless " "'list_display_links' is set.", id='admin.E124', ) def test_list_display_first_item_in_list_editable_no_list_display_links(self): """ The first item in list_display cannot be in list_editable if list_display_links isn't defined. """ class ProductAdmin(ModelAdmin): list_display = ['name', 'slug', 'pub_date'] list_editable = ['slug', 'name'] self.assertIsInvalid( ProductAdmin, ValidationTestModel, "The value of 'list_editable[1]' refers to the first field " "in 'list_display' ('name'), which cannot be used unless " "'list_display_links' is set.", id='admin.E124', ) def test_both_list_editable_and_list_display_links(self): class ProductAdmin(ModelAdmin): list_editable = ('name',) list_display = ('name',) list_display_links = ('name',) self.assertIsInvalid( ProductAdmin, ValidationTestModel, "The value of 'name' cannot be in both 'list_editable' and " "'list_display_links'.", id='admin.E123', ) class AutocompleteFieldsTests(CheckTestCase): def test_autocomplete_e036(self): class Admin(ModelAdmin): autocomplete_fields = 'name' self.assertIsInvalid( Admin, Band, msg="The value of 'autocomplete_fields' must be a list or tuple.", id='admin.E036', invalid_obj=Admin, ) def test_autocomplete_e037(self): class Admin(ModelAdmin): autocomplete_fields = ('nonexistent',) self.assertIsInvalid( Admin, ValidationTestModel, msg=( "The value of 'autocomplete_fields[0]' refers to 'nonexistent', " "which is not an attribute of 'modeladmin.ValidationTestModel'." ), id='admin.E037', invalid_obj=Admin, ) def test_autocomplete_e38(self): class Admin(ModelAdmin): autocomplete_fields = ('name',) self.assertIsInvalid( Admin, ValidationTestModel, msg=( "The value of 'autocomplete_fields[0]' must be a foreign " "key or a many-to-many field." ), id='admin.E038', invalid_obj=Admin, ) def test_autocomplete_e039(self): class Admin(ModelAdmin): autocomplete_fields = ('band',) self.assertIsInvalid( Admin, Song, msg=( 'An admin for model "Band" has to be registered ' 'to be referenced by Admin.autocomplete_fields.' ), id='admin.E039', invalid_obj=Admin, ) def test_autocomplete_e040(self): class NoSearchFieldsAdmin(ModelAdmin): pass class AutocompleteAdmin(ModelAdmin): autocomplete_fields = ('featuring',) site = AdminSite() site.register(Band, NoSearchFieldsAdmin) self.assertIsInvalid( AutocompleteAdmin, Song, msg=( 'NoSearchFieldsAdmin must define "search_fields", because ' 'it\'s referenced by AutocompleteAdmin.autocomplete_fields.' ), id='admin.E040', invalid_obj=AutocompleteAdmin, admin_site=site, ) def test_autocomplete_is_valid(self): class SearchFieldsAdmin(ModelAdmin): search_fields = 'name' class AutocompleteAdmin(ModelAdmin): autocomplete_fields = ('featuring',) site = AdminSite() site.register(Band, SearchFieldsAdmin) self.assertIsValid(AutocompleteAdmin, Song, admin_site=site) def test_autocomplete_is_onetoone(self): class UserAdmin(ModelAdmin): search_fields = ('name',) class Admin(ModelAdmin): autocomplete_fields = ('best_friend',) site = AdminSite() site.register(User, UserAdmin) self.assertIsValid(Admin, ValidationTestModel, admin_site=site) class ActionsCheckTests(CheckTestCase): def test_custom_permissions_require_matching_has_method(self): def custom_permission_action(modeladmin, request, queryset): pass custom_permission_action.allowed_permissions = ('custom',) class BandAdmin(ModelAdmin): actions = (custom_permission_action,) self.assertIsInvalid( BandAdmin, Band, 'BandAdmin must define a has_custom_permission() method for the ' 'custom_permission_action action.', id='admin.E129', ) def test_actions_not_unique(self): def action(modeladmin, request, queryset): pass class BandAdmin(ModelAdmin): actions = (action, action) self.assertIsInvalid( BandAdmin, Band, "__name__ attributes of actions defined in " "<class 'modeladmin.test_checks.ActionsCheckTests." "test_actions_not_unique.<locals>.BandAdmin'> must be unique.", id='admin.E130', ) def test_actions_unique(self): def action1(modeladmin, request, queryset): pass def action2(modeladmin, request, queryset): pass class BandAdmin(ModelAdmin): actions = (action1, action2) self.assertIsValid(BandAdmin, Band)
168f97cdcb4495cabb37f970c191961d785450f0432acd46c6d9f87435421d78
""" Tests for django test runner """ import unittest from unittest import mock from admin_scripts.tests import AdminScriptTestCase from django import db from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.management import call_command from django.core.management.base import SystemCheckError from django.test import TransactionTestCase, skipUnlessDBFeature, testcases from django.test.runner import DiscoverRunner from django.test.testcases import connections_support_transactions from django.test.utils import dependency_ordered from .models import B, Person, Through class DependencyOrderingTests(unittest.TestCase): def test_simple_dependencies(self): raw = [ ('s1', ('s1_db', ['alpha'])), ('s2', ('s2_db', ['bravo'])), ('s3', ('s3_db', ['charlie'])), ] dependencies = { 'alpha': ['charlie'], 'bravo': ['charlie'], } ordered = dependency_ordered(raw, dependencies=dependencies) ordered_sigs = [sig for sig, value in ordered] self.assertIn('s1', ordered_sigs) self.assertIn('s2', ordered_sigs) self.assertIn('s3', ordered_sigs) self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s1')) self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s2')) def test_chained_dependencies(self): raw = [ ('s1', ('s1_db', ['alpha'])), ('s2', ('s2_db', ['bravo'])), ('s3', ('s3_db', ['charlie'])), ] dependencies = { 'alpha': ['bravo'], 'bravo': ['charlie'], } ordered = dependency_ordered(raw, dependencies=dependencies) ordered_sigs = [sig for sig, value in ordered] self.assertIn('s1', ordered_sigs) self.assertIn('s2', ordered_sigs) self.assertIn('s3', ordered_sigs) # Explicit dependencies self.assertLess(ordered_sigs.index('s2'), ordered_sigs.index('s1')) self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s2')) # Implied dependencies self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s1')) def test_multiple_dependencies(self): raw = [ ('s1', ('s1_db', ['alpha'])), ('s2', ('s2_db', ['bravo'])), ('s3', ('s3_db', ['charlie'])), ('s4', ('s4_db', ['delta'])), ] dependencies = { 'alpha': ['bravo', 'delta'], 'bravo': ['charlie'], 'delta': ['charlie'], } ordered = dependency_ordered(raw, dependencies=dependencies) ordered_sigs = [sig for sig, aliases in ordered] self.assertIn('s1', ordered_sigs) self.assertIn('s2', ordered_sigs) self.assertIn('s3', ordered_sigs) self.assertIn('s4', ordered_sigs) # Explicit dependencies self.assertLess(ordered_sigs.index('s2'), ordered_sigs.index('s1')) self.assertLess(ordered_sigs.index('s4'), ordered_sigs.index('s1')) self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s2')) self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s4')) # Implicit dependencies self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s1')) def test_circular_dependencies(self): raw = [ ('s1', ('s1_db', ['alpha'])), ('s2', ('s2_db', ['bravo'])), ] dependencies = { 'bravo': ['alpha'], 'alpha': ['bravo'], } with self.assertRaises(ImproperlyConfigured): dependency_ordered(raw, dependencies=dependencies) def test_own_alias_dependency(self): raw = [ ('s1', ('s1_db', ['alpha', 'bravo'])) ] dependencies = { 'alpha': ['bravo'] } with self.assertRaises(ImproperlyConfigured): dependency_ordered(raw, dependencies=dependencies) # reordering aliases shouldn't matter raw = [ ('s1', ('s1_db', ['bravo', 'alpha'])) ] with self.assertRaises(ImproperlyConfigured): dependency_ordered(raw, dependencies=dependencies) class MockTestRunner: def __init__(self, *args, **kwargs): pass MockTestRunner.run_tests = mock.Mock(return_value=[]) class ManageCommandTests(unittest.TestCase): def test_custom_test_runner(self): call_command('test', 'sites', testrunner='test_runner.tests.MockTestRunner') MockTestRunner.run_tests.assert_called_with(('sites',)) def test_bad_test_runner(self): with self.assertRaises(AttributeError): call_command('test', 'sites', testrunner='test_runner.NonexistentRunner') class CustomTestRunnerOptionsSettingsTests(AdminScriptTestCase): """ Custom runners can add command line arguments. The runner is specified through a settings file. """ def setUp(self): super().setUp() settings = { 'TEST_RUNNER': '\'test_runner.runner.CustomOptionsTestRunner\'', } self.write_settings('settings.py', sdict=settings) def test_default_options(self): args = ['test', '--settings=test_project.settings'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, '1:2:3') def test_default_and_given_options(self): args = ['test', '--settings=test_project.settings', '--option_b=foo'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, '1:foo:3') def test_option_name_and_value_separated(self): args = ['test', '--settings=test_project.settings', '--option_b', 'foo'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, '1:foo:3') def test_all_options_given(self): args = ['test', '--settings=test_project.settings', '--option_a=bar', '--option_b=foo', '--option_c=31337'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, 'bar:foo:31337') class CustomTestRunnerOptionsCmdlineTests(AdminScriptTestCase): """ Custom runners can add command line arguments when the runner is specified using --testrunner. """ def setUp(self): super().setUp() self.write_settings('settings.py') def test_testrunner_option(self): args = [ 'test', '--testrunner', 'test_runner.runner.CustomOptionsTestRunner', '--option_a=bar', '--option_b=foo', '--option_c=31337' ] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, 'bar:foo:31337') def test_testrunner_equals(self): args = [ 'test', '--testrunner=test_runner.runner.CustomOptionsTestRunner', '--option_a=bar', '--option_b=foo', '--option_c=31337' ] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, 'bar:foo:31337') def test_no_testrunner(self): args = ['test', '--testrunner'] out, err = self.run_django_admin(args, 'test_project.settings') self.assertIn('usage', err) self.assertNotIn('Traceback', err) self.assertNoOutput(out) class Ticket17477RegressionTests(AdminScriptTestCase): def setUp(self): super().setUp() self.write_settings('settings.py') def test_ticket_17477(self): """'manage.py help test' works after r16352.""" args = ['help', 'test'] out, err = self.run_manage(args) self.assertNoOutput(err) class SQLiteInMemoryTestDbs(TransactionTestCase): available_apps = ['test_runner'] databases = {'default', 'other'} @unittest.skipUnless(all(db.connections[conn].vendor == 'sqlite' for conn in db.connections), "This is an sqlite-specific issue") def test_transaction_support(self): # Assert connections mocking is appropriately applied by preventing # any attempts at calling create_test_db on the global connection # objects. for connection in db.connections.all(): create_test_db = mock.patch.object( connection.creation, 'create_test_db', side_effect=AssertionError("Global connection object shouldn't be manipulated.") ) create_test_db.start() self.addCleanup(create_test_db.stop) for option_key, option_value in ( ('NAME', ':memory:'), ('TEST', {'NAME': ':memory:'})): tested_connections = db.ConnectionHandler({ 'default': { 'ENGINE': 'django.db.backends.sqlite3', option_key: option_value, }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', option_key: option_value, }, }) with mock.patch('django.test.utils.connections', new=tested_connections): other = tested_connections['other'] DiscoverRunner(verbosity=0).setup_databases() msg = ( "DATABASES setting '%s' option set to sqlite3's ':memory:' value " "shouldn't interfere with transaction support detection." % option_key ) # Transaction support is properly initialized for the 'other' DB. self.assertTrue(other.features.supports_transactions, msg) # And all the DBs report that they support transactions. self.assertTrue(connections_support_transactions(), msg) class DummyBackendTest(unittest.TestCase): def test_setup_databases(self): """ setup_databases() doesn't fail with dummy database backend. """ tested_connections = db.ConnectionHandler({}) with mock.patch('django.test.utils.connections', new=tested_connections): runner_instance = DiscoverRunner(verbosity=0) old_config = runner_instance.setup_databases() runner_instance.teardown_databases(old_config) class AliasedDefaultTestSetupTest(unittest.TestCase): def test_setup_aliased_default_database(self): """ setup_databases() doesn't fail when 'default' is aliased """ tested_connections = db.ConnectionHandler({ 'default': { 'NAME': 'dummy' }, 'aliased': { 'NAME': 'dummy' } }) with mock.patch('django.test.utils.connections', new=tested_connections): runner_instance = DiscoverRunner(verbosity=0) old_config = runner_instance.setup_databases() runner_instance.teardown_databases(old_config) class SetupDatabasesTests(unittest.TestCase): def setUp(self): self.runner_instance = DiscoverRunner(verbosity=0) def test_setup_aliased_databases(self): tested_connections = db.ConnectionHandler({ 'default': { 'ENGINE': 'django.db.backends.dummy', 'NAME': 'dbname', }, 'other': { 'ENGINE': 'django.db.backends.dummy', 'NAME': 'dbname', } }) with mock.patch('django.db.backends.dummy.base.DatabaseWrapper.creation_class') as mocked_db_creation: with mock.patch('django.test.utils.connections', new=tested_connections): old_config = self.runner_instance.setup_databases() self.runner_instance.teardown_databases(old_config) mocked_db_creation.return_value.destroy_test_db.assert_called_once_with('dbname', 0, False) def test_destroy_test_db_restores_db_name(self): tested_connections = db.ConnectionHandler({ 'default': { 'ENGINE': settings.DATABASES[db.DEFAULT_DB_ALIAS]["ENGINE"], 'NAME': 'xxx_test_database', }, }) # Using the real current name as old_name to not mess with the test suite. old_name = settings.DATABASES[db.DEFAULT_DB_ALIAS]["NAME"] with mock.patch('django.db.connections', new=tested_connections): tested_connections['default'].creation.destroy_test_db(old_name, verbosity=0, keepdb=True) self.assertEqual(tested_connections['default'].settings_dict["NAME"], old_name) def test_serialization(self): tested_connections = db.ConnectionHandler({ 'default': { 'ENGINE': 'django.db.backends.dummy', }, }) with mock.patch('django.db.backends.dummy.base.DatabaseWrapper.creation_class') as mocked_db_creation: with mock.patch('django.test.utils.connections', new=tested_connections): self.runner_instance.setup_databases() mocked_db_creation.return_value.create_test_db.assert_called_once_with( verbosity=0, autoclobber=False, serialize=True, keepdb=False ) def test_serialized_off(self): tested_connections = db.ConnectionHandler({ 'default': { 'ENGINE': 'django.db.backends.dummy', 'TEST': {'SERIALIZE': False}, }, }) with mock.patch('django.db.backends.dummy.base.DatabaseWrapper.creation_class') as mocked_db_creation: with mock.patch('django.test.utils.connections', new=tested_connections): self.runner_instance.setup_databases() mocked_db_creation.return_value.create_test_db.assert_called_once_with( verbosity=0, autoclobber=False, serialize=False, keepdb=False ) @skipUnlessDBFeature('supports_sequence_reset') class AutoIncrementResetTest(TransactionTestCase): """ Creating the same models in different test methods receive the same PK values since the sequences are reset before each test method. """ available_apps = ['test_runner'] reset_sequences = True def _test(self): # Regular model p = Person.objects.create(first_name='Jack', last_name='Smith') self.assertEqual(p.pk, 1) # Auto-created many-to-many through model p.friends.add(Person.objects.create(first_name='Jacky', last_name='Smith')) self.assertEqual(p.friends.through.objects.first().pk, 1) # Many-to-many through model b = B.objects.create() t = Through.objects.create(person=p, b=b) self.assertEqual(t.pk, 1) def test_autoincrement_reset1(self): self._test() def test_autoincrement_reset2(self): self._test() class EmptyDefaultDatabaseTest(unittest.TestCase): def test_empty_default_database(self): """ An empty default database in settings does not raise an ImproperlyConfigured error when running a unit test that does not use a database. """ testcases.connections = db.ConnectionHandler({'default': {}}) connection = testcases.connections[db.utils.DEFAULT_DB_ALIAS] self.assertEqual(connection.settings_dict['ENGINE'], 'django.db.backends.dummy') connections_support_transactions() class RunTestsExceptionHandlingTests(unittest.TestCase): def test_run_checks_raises(self): """ Teardown functions are run when run_checks() raises SystemCheckError. """ with mock.patch('django.test.runner.DiscoverRunner.setup_test_environment'), \ mock.patch('django.test.runner.DiscoverRunner.setup_databases'), \ mock.patch('django.test.runner.DiscoverRunner.build_suite'), \ mock.patch('django.test.runner.DiscoverRunner.run_checks', side_effect=SystemCheckError), \ mock.patch('django.test.runner.DiscoverRunner.teardown_databases') as teardown_databases, \ mock.patch('django.test.runner.DiscoverRunner.teardown_test_environment') as teardown_test_environment: runner = DiscoverRunner(verbosity=0, interactive=False) with self.assertRaises(SystemCheckError): runner.run_tests(['test_runner_apps.sample.tests_sample.TestDjangoTestCase']) self.assertTrue(teardown_databases.called) self.assertTrue(teardown_test_environment.called) def test_run_checks_raises_and_teardown_raises(self): """ SystemCheckError is surfaced when run_checks() raises SystemCheckError and teardown databases() raises ValueError. """ with mock.patch('django.test.runner.DiscoverRunner.setup_test_environment'), \ mock.patch('django.test.runner.DiscoverRunner.setup_databases'), \ mock.patch('django.test.runner.DiscoverRunner.build_suite'), \ mock.patch('django.test.runner.DiscoverRunner.run_checks', side_effect=SystemCheckError), \ mock.patch('django.test.runner.DiscoverRunner.teardown_databases', side_effect=ValueError) \ as teardown_databases, \ mock.patch('django.test.runner.DiscoverRunner.teardown_test_environment') as teardown_test_environment: runner = DiscoverRunner(verbosity=0, interactive=False) with self.assertRaises(SystemCheckError): runner.run_tests(['test_runner_apps.sample.tests_sample.TestDjangoTestCase']) self.assertTrue(teardown_databases.called) self.assertFalse(teardown_test_environment.called) def test_run_checks_passes_and_teardown_raises(self): """ Exceptions on teardown are surfaced if no exceptions happen during run_checks(). """ with mock.patch('django.test.runner.DiscoverRunner.setup_test_environment'), \ mock.patch('django.test.runner.DiscoverRunner.setup_databases'), \ mock.patch('django.test.runner.DiscoverRunner.build_suite'), \ mock.patch('django.test.runner.DiscoverRunner.run_checks'), \ mock.patch('django.test.runner.DiscoverRunner.teardown_databases', side_effect=ValueError) \ as teardown_databases, \ mock.patch('django.test.runner.DiscoverRunner.teardown_test_environment') as teardown_test_environment: runner = DiscoverRunner(verbosity=0, interactive=False) with self.assertRaises(ValueError): # Suppress the output when running TestDjangoTestCase. with mock.patch('sys.stderr'): runner.run_tests(['test_runner_apps.sample.tests_sample.TestDjangoTestCase']) self.assertTrue(teardown_databases.called) self.assertFalse(teardown_test_environment.called)
0ebba818dfec8a88cbe05d28efd0fb56c0b984fa66388525f7b5896d0cb35f1e
import json from datetime import datetime from django.contrib.admin.models import ADDITION, CHANGE, DELETION, LogEntry from django.contrib.admin.utils import quote from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.test import TestCase, override_settings from django.urls import reverse from django.utils import translation from django.utils.html import escape from .models import Article, ArticleProxy, Site @override_settings(ROOT_URLCONF='admin_utils.urls') class LogEntryTests(TestCase): def setUp(self): self.user = User.objects.create_superuser(username='super', password='secret', email='[email protected]') self.site = Site.objects.create(domain='example.org') self.a1 = Article.objects.create( site=self.site, title="Title", created=datetime(2008, 3, 12, 11, 54), ) content_type_pk = ContentType.objects.get_for_model(Article).pk LogEntry.objects.log_action( self.user.pk, content_type_pk, self.a1.pk, repr(self.a1), CHANGE, change_message='Changed something' ) self.client.force_login(self.user) def test_logentry_save(self): """ LogEntry.action_time is a timestamp of the date when the entry was created. It shouldn't be updated on a subsequent save(). """ logentry = LogEntry.objects.get(content_type__model__iexact="article") action_time = logentry.action_time logentry.save() self.assertEqual(logentry.action_time, action_time) def test_logentry_change_message(self): """ LogEntry.change_message is stored as a dumped JSON structure to be able to get the message dynamically translated at display time. """ post_data = { 'site': self.site.pk, 'title': 'Changed', 'hist': 'Some content', 'created_0': '2008-03-12', 'created_1': '11:54', } change_url = reverse('admin:admin_utils_article_change', args=[quote(self.a1.pk)]) response = self.client.post(change_url, post_data) self.assertRedirects(response, reverse('admin:admin_utils_article_changelist')) logentry = LogEntry.objects.filter(content_type__model__iexact='article').latest('id') self.assertEqual(logentry.get_change_message(), 'Changed Title and History.') with translation.override('fr'): self.assertEqual(logentry.get_change_message(), 'Modification de Title et Historique.') add_url = reverse('admin:admin_utils_article_add') post_data['title'] = 'New' response = self.client.post(add_url, post_data) self.assertRedirects(response, reverse('admin:admin_utils_article_changelist')) logentry = LogEntry.objects.filter(content_type__model__iexact='article').latest('id') self.assertEqual(logentry.get_change_message(), 'Added.') with translation.override('fr'): self.assertEqual(logentry.get_change_message(), 'Ajout.') def test_logentry_change_message_not_json(self): """LogEntry.change_message was a string before Django 1.10.""" logentry = LogEntry(change_message='non-JSON string') self.assertEqual(logentry.get_change_message(), logentry.change_message) @override_settings(USE_L10N=True) def test_logentry_change_message_localized_datetime_input(self): """ Localized date/time inputs shouldn't affect changed form data detection. """ post_data = { 'site': self.site.pk, 'title': 'Changed', 'hist': 'Some content', 'created_0': '12/03/2008', 'created_1': '11:54', } with translation.override('fr'): change_url = reverse('admin:admin_utils_article_change', args=[quote(self.a1.pk)]) response = self.client.post(change_url, post_data) self.assertRedirects(response, reverse('admin:admin_utils_article_changelist')) logentry = LogEntry.objects.filter(content_type__model__iexact='article').latest('id') self.assertEqual(logentry.get_change_message(), 'Changed Title and History.') def test_logentry_change_message_formsets(self): """ All messages for changed formsets are logged in a change message. """ a2 = Article.objects.create( site=self.site, title="Title second article", created=datetime(2012, 3, 18, 11, 54), ) post_data = { 'domain': 'example.com', # domain changed 'admin_articles-TOTAL_FORMS': '5', 'admin_articles-INITIAL_FORMS': '2', 'admin_articles-MIN_NUM_FORMS': '0', 'admin_articles-MAX_NUM_FORMS': '1000', # Changed title for 1st article 'admin_articles-0-id': str(self.a1.pk), 'admin_articles-0-site': str(self.site.pk), 'admin_articles-0-title': 'Changed Title', # Second article is deleted 'admin_articles-1-id': str(a2.pk), 'admin_articles-1-site': str(self.site.pk), 'admin_articles-1-title': 'Title second article', 'admin_articles-1-DELETE': 'on', # A new article is added 'admin_articles-2-site': str(self.site.pk), 'admin_articles-2-title': 'Added article', } change_url = reverse('admin:admin_utils_site_change', args=[quote(self.site.pk)]) response = self.client.post(change_url, post_data) self.assertRedirects(response, reverse('admin:admin_utils_site_changelist')) self.assertQuerysetEqual(Article.objects.filter(pk=a2.pk), []) logentry = LogEntry.objects.filter(content_type__model__iexact='site').latest('action_time') self.assertEqual( json.loads(logentry.change_message), [ {"changed": {"fields": ["Domain"]}}, {"added": {"object": "Added article", "name": "article"}}, {"changed": {"fields": ["Title", "not_a_form_field"], "object": "Changed Title", "name": "article"}}, {"deleted": {"object": "Title second article", "name": "article"}}, ] ) self.assertEqual( logentry.get_change_message(), 'Changed Domain. Added article “Added article”. ' 'Changed Title and not_a_form_field for article “Changed Title”. ' 'Deleted article “Title second article”.' ) with translation.override('fr'): self.assertEqual( logentry.get_change_message(), "Modification de Domain. Ajout de article « Added article ». " "Modification de Title et not_a_form_field pour l'objet " "article « Changed Title ». " "Suppression de article « Title second article »." ) def test_logentry_get_edited_object(self): """ LogEntry.get_edited_object() returns the edited object of a LogEntry object. """ logentry = LogEntry.objects.get(content_type__model__iexact="article") edited_obj = logentry.get_edited_object() self.assertEqual(logentry.object_id, str(edited_obj.pk)) def test_logentry_get_admin_url(self): """ LogEntry.get_admin_url returns a URL to edit the entry's object or None for nonexistent (possibly deleted) models. """ logentry = LogEntry.objects.get(content_type__model__iexact='article') expected_url = reverse('admin:admin_utils_article_change', args=(quote(self.a1.pk),)) self.assertEqual(logentry.get_admin_url(), expected_url) self.assertIn('article/%d/change/' % self.a1.pk, logentry.get_admin_url()) logentry.content_type.model = "nonexistent" self.assertIsNone(logentry.get_admin_url()) def test_logentry_unicode(self): log_entry = LogEntry() log_entry.action_flag = ADDITION self.assertTrue(str(log_entry).startswith('Added ')) log_entry.action_flag = CHANGE self.assertTrue(str(log_entry).startswith('Changed ')) log_entry.action_flag = DELETION self.assertTrue(str(log_entry).startswith('Deleted ')) # Make sure custom action_flags works log_entry.action_flag = 4 self.assertEqual(str(log_entry), 'LogEntry Object') def test_logentry_repr(self): logentry = LogEntry.objects.first() self.assertEqual(repr(logentry), str(logentry.action_time)) def test_log_action(self): content_type_pk = ContentType.objects.get_for_model(Article).pk log_entry = LogEntry.objects.log_action( self.user.pk, content_type_pk, self.a1.pk, repr(self.a1), CHANGE, change_message='Changed something else', ) self.assertEqual(log_entry, LogEntry.objects.latest('id')) def test_recentactions_without_content_type(self): """ If a LogEntry is missing content_type it will not display it in span tag under the hyperlink. """ response = self.client.get(reverse('admin:index')) link = reverse('admin:admin_utils_article_change', args=(quote(self.a1.pk),)) should_contain = """<a href="%s">%s</a>""" % (escape(link), escape(repr(self.a1))) self.assertContains(response, should_contain) should_contain = "Article" self.assertContains(response, should_contain) logentry = LogEntry.objects.get(content_type__model__iexact='article') # If the log entry doesn't have a content type it should still be # possible to view the Recent Actions part (#10275). logentry.content_type = None logentry.save() should_contain = should_contain.encode() counted_presence_before = response.content.count(should_contain) response = self.client.get(reverse('admin:index')) counted_presence_after = response.content.count(should_contain) self.assertEqual(counted_presence_before - 1, counted_presence_after) def test_proxy_model_content_type_is_used_for_log_entries(self): """ Log entries for proxy models should have the proxy model's contenttype (#21084). """ proxy_content_type = ContentType.objects.get_for_model(ArticleProxy, for_concrete_model=False) post_data = { 'site': self.site.pk, 'title': "Foo", 'hist': "Bar", 'created_0': '2015-12-25', 'created_1': '00:00', } changelist_url = reverse('admin:admin_utils_articleproxy_changelist') # add proxy_add_url = reverse('admin:admin_utils_articleproxy_add') response = self.client.post(proxy_add_url, post_data) self.assertRedirects(response, changelist_url) proxy_addition_log = LogEntry.objects.latest('id') self.assertEqual(proxy_addition_log.action_flag, ADDITION) self.assertEqual(proxy_addition_log.content_type, proxy_content_type) # change article_id = proxy_addition_log.object_id proxy_change_url = reverse('admin:admin_utils_articleproxy_change', args=(article_id,)) post_data['title'] = 'New' response = self.client.post(proxy_change_url, post_data) self.assertRedirects(response, changelist_url) proxy_change_log = LogEntry.objects.latest('id') self.assertEqual(proxy_change_log.action_flag, CHANGE) self.assertEqual(proxy_change_log.content_type, proxy_content_type) # delete proxy_delete_url = reverse('admin:admin_utils_articleproxy_delete', args=(article_id,)) response = self.client.post(proxy_delete_url, {'post': 'yes'}) self.assertRedirects(response, changelist_url) proxy_delete_log = LogEntry.objects.latest('id') self.assertEqual(proxy_delete_log.action_flag, DELETION) self.assertEqual(proxy_delete_log.content_type, proxy_content_type) def test_action_flag_choices(self): tests = ((1, 'Addition'), (2, 'Change'), (3, 'Deletion')) for action_flag, display_name in tests: with self.subTest(action_flag=action_flag): log = LogEntry(action_flag=action_flag) self.assertEqual(log.get_action_flag_display(), display_name)
8ab0ec548806b3544099230fc7196fccd90b1c1214032a0638b096eac217c0c1
from io import BytesIO from itertools import chain from urllib.parse import urlencode from django.core.exceptions import DisallowedHost from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.http import HttpRequest, RawPostDataException, UnreadablePostError from django.http.multipartparser import MultiPartParserError from django.http.request import HttpHeaders, split_domain_port from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.client import FakePayload class RequestsTests(SimpleTestCase): def test_httprequest(self): request = HttpRequest() self.assertEqual(list(request.GET), []) self.assertEqual(list(request.POST), []) self.assertEqual(list(request.COOKIES), []) self.assertEqual(list(request.META), []) # .GET and .POST should be QueryDicts self.assertEqual(request.GET.urlencode(), '') self.assertEqual(request.POST.urlencode(), '') # and FILES should be MultiValueDict self.assertEqual(request.FILES.getlist('foo'), []) self.assertIsNone(request.content_type) self.assertIsNone(request.content_params) def test_httprequest_full_path(self): request = HttpRequest() request.path = '/;some/?awful/=path/foo:bar/' request.path_info = '/prefix' + request.path request.META['QUERY_STRING'] = ';some=query&+query=string' expected = '/%3Bsome/%3Fawful/%3Dpath/foo:bar/?;some=query&+query=string' self.assertEqual(request.get_full_path(), expected) self.assertEqual(request.get_full_path_info(), '/prefix' + expected) def test_httprequest_full_path_with_query_string_and_fragment(self): request = HttpRequest() request.path = '/foo#bar' request.path_info = '/prefix' + request.path request.META['QUERY_STRING'] = 'baz#quux' self.assertEqual(request.get_full_path(), '/foo%23bar?baz#quux') self.assertEqual(request.get_full_path_info(), '/prefix/foo%23bar?baz#quux') def test_httprequest_repr(self): request = HttpRequest() request.path = '/somepath/' request.method = 'GET' request.GET = {'get-key': 'get-value'} request.POST = {'post-key': 'post-value'} request.COOKIES = {'post-key': 'post-value'} request.META = {'post-key': 'post-value'} self.assertEqual(repr(request), "<HttpRequest: GET '/somepath/'>") def test_httprequest_repr_invalid_method_and_path(self): request = HttpRequest() self.assertEqual(repr(request), "<HttpRequest>") request = HttpRequest() request.method = "GET" self.assertEqual(repr(request), "<HttpRequest>") request = HttpRequest() request.path = "" self.assertEqual(repr(request), "<HttpRequest>") def test_wsgirequest(self): request = WSGIRequest({ 'PATH_INFO': 'bogus', 'REQUEST_METHOD': 'bogus', 'CONTENT_TYPE': 'text/html; charset=utf8', 'wsgi.input': BytesIO(b''), }) self.assertEqual(list(request.GET), []) self.assertEqual(list(request.POST), []) self.assertEqual(list(request.COOKIES), []) self.assertEqual( set(request.META), {'PATH_INFO', 'REQUEST_METHOD', 'SCRIPT_NAME', 'CONTENT_TYPE', 'wsgi.input'} ) self.assertEqual(request.META['PATH_INFO'], 'bogus') self.assertEqual(request.META['REQUEST_METHOD'], 'bogus') self.assertEqual(request.META['SCRIPT_NAME'], '') self.assertEqual(request.content_type, 'text/html') self.assertEqual(request.content_params, {'charset': 'utf8'}) def test_wsgirequest_with_script_name(self): """ The request's path is correctly assembled, regardless of whether or not the SCRIPT_NAME has a trailing slash (#20169). """ # With trailing slash request = WSGIRequest({ 'PATH_INFO': '/somepath/', 'SCRIPT_NAME': '/PREFIX/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), }) self.assertEqual(request.path, '/PREFIX/somepath/') # Without trailing slash request = WSGIRequest({ 'PATH_INFO': '/somepath/', 'SCRIPT_NAME': '/PREFIX', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), }) self.assertEqual(request.path, '/PREFIX/somepath/') def test_wsgirequest_script_url_double_slashes(self): """ WSGI squashes multiple successive slashes in PATH_INFO, WSGIRequest should take that into account when populating request.path and request.META['SCRIPT_NAME'] (#17133). """ request = WSGIRequest({ 'SCRIPT_URL': '/mst/milestones//accounts/login//help', 'PATH_INFO': '/milestones/accounts/login/help', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), }) self.assertEqual(request.path, '/mst/milestones/accounts/login/help') self.assertEqual(request.META['SCRIPT_NAME'], '/mst') def test_wsgirequest_with_force_script_name(self): """ The FORCE_SCRIPT_NAME setting takes precedence over the request's SCRIPT_NAME environment parameter (#20169). """ with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'): request = WSGIRequest({ 'PATH_INFO': '/somepath/', 'SCRIPT_NAME': '/PREFIX/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), }) self.assertEqual(request.path, '/FORCED_PREFIX/somepath/') def test_wsgirequest_path_with_force_script_name_trailing_slash(self): """ The request's path is correctly assembled, regardless of whether or not the FORCE_SCRIPT_NAME setting has a trailing slash (#20169). """ # With trailing slash with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'): request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, '/FORCED_PREFIX/somepath/') # Without trailing slash with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX'): request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, '/FORCED_PREFIX/somepath/') def test_wsgirequest_repr(self): request = WSGIRequest({'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(repr(request), "<WSGIRequest: GET '/'>") request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) request.GET = {'get-key': 'get-value'} request.POST = {'post-key': 'post-value'} request.COOKIES = {'post-key': 'post-value'} request.META = {'post-key': 'post-value'} self.assertEqual(repr(request), "<WSGIRequest: GET '/somepath/'>") def test_wsgirequest_path_info(self): def wsgi_str(path_info, encoding='utf-8'): path_info = path_info.encode(encoding) # Actual URL sent by the browser (bytestring) path_info = path_info.decode('iso-8859-1') # Value in the WSGI environ dict (native string) return path_info # Regression for #19468 request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, "/سلام/") # The URL may be incorrectly encoded in a non-UTF-8 encoding (#26971) request = WSGIRequest({ 'PATH_INFO': wsgi_str("/café/", encoding='iso-8859-1'), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), }) # Since it's impossible to decide the (wrong) encoding of the URL, it's # left percent-encoded in the path. self.assertEqual(request.path, "/caf%E9/") def test_limited_stream(self): # Read all of a limited stream stream = LimitedStream(BytesIO(b'test'), 2) self.assertEqual(stream.read(), b'te') # Reading again returns nothing. self.assertEqual(stream.read(), b'') # Read a number of characters greater than the stream has to offer stream = LimitedStream(BytesIO(b'test'), 2) self.assertEqual(stream.read(5), b'te') # Reading again returns nothing. self.assertEqual(stream.readline(5), b'') # Read sequentially from a stream stream = LimitedStream(BytesIO(b'12345678'), 8) self.assertEqual(stream.read(5), b'12345') self.assertEqual(stream.read(5), b'678') # Reading again returns nothing. self.assertEqual(stream.readline(5), b'') # Read lines from a stream stream = LimitedStream(BytesIO(b'1234\n5678\nabcd\nefgh\nijkl'), 24) # Read a full line, unconditionally self.assertEqual(stream.readline(), b'1234\n') # Read a number of characters less than a line self.assertEqual(stream.readline(2), b'56') # Read the rest of the partial line self.assertEqual(stream.readline(), b'78\n') # Read a full line, with a character limit greater than the line length self.assertEqual(stream.readline(6), b'abcd\n') # Read the next line, deliberately terminated at the line end self.assertEqual(stream.readline(4), b'efgh') # Read the next line... just the line end self.assertEqual(stream.readline(), b'\n') # Read everything else. self.assertEqual(stream.readline(), b'ijkl') # Regression for #15018 # If a stream contains a newline, but the provided length # is less than the number of provided characters, the newline # doesn't reset the available character count stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9) self.assertEqual(stream.readline(10), b'1234\n') self.assertEqual(stream.readline(3), b'abc') # Now expire the available characters self.assertEqual(stream.readline(3), b'd') # Reading again returns nothing. self.assertEqual(stream.readline(2), b'') # Same test, but with read, not readline. stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9) self.assertEqual(stream.read(6), b'1234\na') self.assertEqual(stream.read(2), b'bc') self.assertEqual(stream.read(2), b'd') self.assertEqual(stream.read(2), b'') self.assertEqual(stream.read(), b'') def test_stream(self): payload = FakePayload('name=value') request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload}, ) self.assertEqual(request.read(), b'name=value') def test_read_after_value(self): """ Reading from request is allowed after accessing request contents as POST or body. """ payload = FakePayload('name=value') request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertEqual(request.POST, {'name': ['value']}) self.assertEqual(request.body, b'name=value') self.assertEqual(request.read(), b'name=value') def test_value_after_read(self): """ Construction of POST or body is not allowed after reading from request. """ payload = FakePayload('name=value') request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertEqual(request.read(2), b'na') with self.assertRaises(RawPostDataException): request.body self.assertEqual(request.POST, {}) def test_non_ascii_POST(self): payload = FakePayload(urlencode({'key': 'España'})) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'wsgi.input': payload, }) self.assertEqual(request.POST, {'key': ['España']}) def test_alternate_charset_POST(self): """ Test a POST with non-utf-8 payload encoding. """ payload = FakePayload(urlencode({'key': 'España'.encode('latin-1')})) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': 'application/x-www-form-urlencoded; charset=iso-8859-1', 'wsgi.input': payload, }) self.assertEqual(request.POST, {'key': ['España']}) def test_body_after_POST_multipart_form_data(self): """ Reading body after parsing multipart/form-data is not allowed """ # Because multipart is used for large amounts of data i.e. file uploads, # we don't want the data held in memory twice, and we don't want to # silence the error by setting body = '' either. payload = FakePayload("\r\n".join([ '--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--' ''])) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertEqual(request.POST, {'name': ['value']}) with self.assertRaises(RawPostDataException): request.body def test_body_after_POST_multipart_related(self): """ Reading body after parsing multipart that isn't form-data is allowed """ # Ticket #9054 # There are cases in which the multipart data is related instead of # being a binary upload, in which case it should still be accessible # via body. payload_data = b"\r\n".join([ b'--boundary', b'Content-ID: id; name="name"', b'', b'value', b'--boundary--' b'']) payload = FakePayload(payload_data) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/related; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertEqual(request.POST, {}) self.assertEqual(request.body, payload_data) def test_POST_multipart_with_content_length_zero(self): """ Multipart POST requests with Content-Length >= 0 are valid and need to be handled. """ # According to: # https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13 # Every request.POST with Content-Length >= 0 is a valid request, # this test ensures that we handle Content-Length == 0. payload = FakePayload("\r\n".join([ '--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--' ''])) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': 0, 'wsgi.input': payload, }) self.assertEqual(request.POST, {}) def test_POST_binary_only(self): payload = b'\r\n\x01\x00\x00\x00ab\x00\x00\xcd\xcc,@' environ = { 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/octet-stream', 'CONTENT_LENGTH': len(payload), 'wsgi.input': BytesIO(payload), } request = WSGIRequest(environ) self.assertEqual(request.POST, {}) self.assertEqual(request.FILES, {}) self.assertEqual(request.body, payload) # Same test without specifying content-type environ.update({'CONTENT_TYPE': '', 'wsgi.input': BytesIO(payload)}) request = WSGIRequest(environ) self.assertEqual(request.POST, {}) self.assertEqual(request.FILES, {}) self.assertEqual(request.body, payload) def test_read_by_lines(self): payload = FakePayload('name=value') request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertEqual(list(request), [b'name=value']) def test_POST_after_body_read(self): """ POST should be populated even if body is read first """ payload = FakePayload('name=value') request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) request.body # evaluate self.assertEqual(request.POST, {'name': ['value']}) def test_POST_after_body_read_and_stream_read(self): """ POST should be populated even if body is read first, and then the stream is read second. """ payload = FakePayload('name=value') request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) request.body # evaluate self.assertEqual(request.read(1), b'n') self.assertEqual(request.POST, {'name': ['value']}) def test_POST_after_body_read_and_stream_read_multipart(self): """ POST should be populated even if body is read first, and then the stream is read second. Using multipart/form-data instead of urlencoded. """ payload = FakePayload("\r\n".join([ '--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--' ''])) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) request.body # evaluate # Consume enough data to mess up the parsing: self.assertEqual(request.read(13), b'--boundary\r\nC') self.assertEqual(request.POST, {'name': ['value']}) def test_POST_immutable_for_multipart(self): """ MultiPartParser.parse() leaves request.POST immutable. """ payload = FakePayload("\r\n".join([ '--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--', ])) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertFalse(request.POST._mutable) def test_multipart_without_boundary(self): request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data;', 'CONTENT_LENGTH': 0, 'wsgi.input': FakePayload(), }) with self.assertRaisesMessage(MultiPartParserError, 'Invalid boundary in multipart: None'): request.POST def test_multipart_non_ascii_content_type(self): request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary = \xe0', 'CONTENT_LENGTH': 0, 'wsgi.input': FakePayload(), }) msg = 'Invalid non-ASCII Content-Type in multipart: multipart/form-data; boundary = à' with self.assertRaisesMessage(MultiPartParserError, msg): request.POST def test_POST_connection_error(self): """ If wsgi.input.read() raises an exception while trying to read() the POST, the exception is identifiable (not a generic OSError). """ class ExplodingBytesIO(BytesIO): def read(self, len=0): raise OSError('kaboom!') payload = b'name=value' request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': ExplodingBytesIO(payload), }) with self.assertRaises(UnreadablePostError): request.body def test_set_encoding_clears_POST(self): payload = FakePayload('name=Hello Günter') request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertEqual(request.POST, {'name': ['Hello Günter']}) request.encoding = 'iso-8859-16' self.assertEqual(request.POST, {'name': ['Hello GĂŒnter']}) def test_set_encoding_clears_GET(self): request = WSGIRequest({ 'REQUEST_METHOD': 'GET', 'wsgi.input': '', 'QUERY_STRING': 'name=Hello%20G%C3%BCnter', }) self.assertEqual(request.GET, {'name': ['Hello Günter']}) request.encoding = 'iso-8859-16' self.assertEqual(request.GET, {'name': ['Hello G\u0102\u0152nter']}) def test_FILES_connection_error(self): """ If wsgi.input.read() raises an exception while trying to read() the FILES, the exception is identifiable (not a generic OSError). """ class ExplodingBytesIO(BytesIO): def read(self, len=0): raise OSError('kaboom!') payload = b'x' request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=foo_', 'CONTENT_LENGTH': len(payload), 'wsgi.input': ExplodingBytesIO(payload), }) with self.assertRaises(UnreadablePostError): request.FILES @override_settings(ALLOWED_HOSTS=['example.com']) def test_get_raw_uri(self): factory = RequestFactory(HTTP_HOST='evil.com') request = factory.get('////absolute-uri') self.assertEqual(request.get_raw_uri(), 'http://evil.com//absolute-uri') request = factory.get('/?foo=bar') self.assertEqual(request.get_raw_uri(), 'http://evil.com/?foo=bar') request = factory.get('/path/with:colons') self.assertEqual(request.get_raw_uri(), 'http://evil.com/path/with:colons') class HostValidationTests(SimpleTestCase): poisoned_hosts = [ '[email protected]', 'example.com:[email protected]', 'example.com:[email protected]:80', 'example.com:80/badpath', 'example.com: recovermypassword.com', ] @override_settings( USE_X_FORWARDED_HOST=False, ALLOWED_HOSTS=[ 'forward.com', 'example.com', 'internal.com', '12.34.56.78', '[2001:19f0:feee::dead:beef:cafe]', 'xn--4ca9at.com', '.multitenant.com', 'INSENSITIVE.com', '[::ffff:169.254.169.254]', ]) def test_http_get_host(self): # Check if X_FORWARDED_HOST is provided. request = HttpRequest() request.META = { 'HTTP_X_FORWARDED_HOST': 'forward.com', 'HTTP_HOST': 'example.com', 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } # X_FORWARDED_HOST is ignored. self.assertEqual(request.get_host(), 'example.com') # Check if X_FORWARDED_HOST isn't provided. request = HttpRequest() request.META = { 'HTTP_HOST': 'example.com', 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } self.assertEqual(request.get_host(), 'example.com') # Check if HTTP_HOST isn't provided. request = HttpRequest() request.META = { 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } self.assertEqual(request.get_host(), 'internal.com') # Check if HTTP_HOST isn't provided, and we're on a nonstandard port request = HttpRequest() request.META = { 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 8042, } self.assertEqual(request.get_host(), 'internal.com:8042') legit_hosts = [ 'example.com', 'example.com:80', '12.34.56.78', '12.34.56.78:443', '[2001:19f0:feee::dead:beef:cafe]', '[2001:19f0:feee::dead:beef:cafe]:8080', 'xn--4ca9at.com', # Punycode for öäü.com 'anything.multitenant.com', 'multitenant.com', 'insensitive.com', 'example.com.', 'example.com.:80', '[::ffff:169.254.169.254]', ] for host in legit_hosts: request = HttpRequest() request.META = { 'HTTP_HOST': host, } request.get_host() # Poisoned host headers are rejected as suspicious for host in chain(self.poisoned_hosts, ['other.com', 'example.com..']): with self.assertRaises(DisallowedHost): request = HttpRequest() request.META = { 'HTTP_HOST': host, } request.get_host() @override_settings(USE_X_FORWARDED_HOST=True, ALLOWED_HOSTS=['*']) def test_http_get_host_with_x_forwarded_host(self): # Check if X_FORWARDED_HOST is provided. request = HttpRequest() request.META = { 'HTTP_X_FORWARDED_HOST': 'forward.com', 'HTTP_HOST': 'example.com', 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } # X_FORWARDED_HOST is obeyed. self.assertEqual(request.get_host(), 'forward.com') # Check if X_FORWARDED_HOST isn't provided. request = HttpRequest() request.META = { 'HTTP_HOST': 'example.com', 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } self.assertEqual(request.get_host(), 'example.com') # Check if HTTP_HOST isn't provided. request = HttpRequest() request.META = { 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } self.assertEqual(request.get_host(), 'internal.com') # Check if HTTP_HOST isn't provided, and we're on a nonstandard port request = HttpRequest() request.META = { 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 8042, } self.assertEqual(request.get_host(), 'internal.com:8042') # Poisoned host headers are rejected as suspicious legit_hosts = [ 'example.com', 'example.com:80', '12.34.56.78', '12.34.56.78:443', '[2001:19f0:feee::dead:beef:cafe]', '[2001:19f0:feee::dead:beef:cafe]:8080', 'xn--4ca9at.com', # Punycode for öäü.com ] for host in legit_hosts: request = HttpRequest() request.META = { 'HTTP_HOST': host, } request.get_host() for host in self.poisoned_hosts: with self.assertRaises(DisallowedHost): request = HttpRequest() request.META = { 'HTTP_HOST': host, } request.get_host() @override_settings(USE_X_FORWARDED_PORT=False) def test_get_port(self): request = HttpRequest() request.META = { 'SERVER_PORT': '8080', 'HTTP_X_FORWARDED_PORT': '80', } # Shouldn't use the X-Forwarded-Port header self.assertEqual(request.get_port(), '8080') request = HttpRequest() request.META = { 'SERVER_PORT': '8080', } self.assertEqual(request.get_port(), '8080') @override_settings(USE_X_FORWARDED_PORT=True) def test_get_port_with_x_forwarded_port(self): request = HttpRequest() request.META = { 'SERVER_PORT': '8080', 'HTTP_X_FORWARDED_PORT': '80', } # Should use the X-Forwarded-Port header self.assertEqual(request.get_port(), '80') request = HttpRequest() request.META = { 'SERVER_PORT': '8080', } self.assertEqual(request.get_port(), '8080') @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_in_debug_mode(self): """ If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are allowed. """ valid_hosts = ['localhost', '127.0.0.1', '[::1]'] for host in valid_hosts: request = HttpRequest() request.META = {'HTTP_HOST': host} self.assertEqual(request.get_host(), host) # Other hostnames raise a DisallowedHost. with self.assertRaises(DisallowedHost): request = HttpRequest() request.META = {'HTTP_HOST': 'example.com'} request.get_host() @override_settings(ALLOWED_HOSTS=[]) def test_get_host_suggestion_of_allowed_host(self): """get_host() makes helpful suggestions if a valid-looking host is not in ALLOWED_HOSTS.""" msg_invalid_host = "Invalid HTTP_HOST header: %r." msg_suggestion = msg_invalid_host + " You may need to add %r to ALLOWED_HOSTS." msg_suggestion2 = msg_invalid_host + " The domain name provided is not valid according to RFC 1034/1035" for host in [ # Valid-looking hosts 'example.com', '12.34.56.78', '[2001:19f0:feee::dead:beef:cafe]', 'xn--4ca9at.com', # Punycode for öäü.com ]: request = HttpRequest() request.META = {'HTTP_HOST': host} with self.assertRaisesMessage(DisallowedHost, msg_suggestion % (host, host)): request.get_host() for domain, port in [ # Valid-looking hosts with a port number ('example.com', 80), ('12.34.56.78', 443), ('[2001:19f0:feee::dead:beef:cafe]', 8080), ]: host = '%s:%s' % (domain, port) request = HttpRequest() request.META = {'HTTP_HOST': host} with self.assertRaisesMessage(DisallowedHost, msg_suggestion % (host, domain)): request.get_host() for host in self.poisoned_hosts: request = HttpRequest() request.META = {'HTTP_HOST': host} with self.assertRaisesMessage(DisallowedHost, msg_invalid_host % host): request.get_host() request = HttpRequest() request.META = {'HTTP_HOST': "invalid_hostname.com"} with self.assertRaisesMessage(DisallowedHost, msg_suggestion2 % "invalid_hostname.com"): request.get_host() def test_split_domain_port_removes_trailing_dot(self): domain, port = split_domain_port('example.com.:8080') self.assertEqual(domain, 'example.com') self.assertEqual(port, '8080') class BuildAbsoluteURITests(SimpleTestCase): factory = RequestFactory() def test_absolute_url(self): request = HttpRequest() url = 'https://www.example.com/asdf' self.assertEqual(request.build_absolute_uri(location=url), url) def test_host_retrieval(self): request = HttpRequest() request.get_host = lambda: 'www.example.com' request.path = '' self.assertEqual( request.build_absolute_uri(location='/path/with:colons'), 'http://www.example.com/path/with:colons' ) def test_request_path_begins_with_two_slashes(self): # //// creates a request with a path beginning with // request = self.factory.get('////absolute-uri') tests = ( # location isn't provided (None, 'http://testserver//absolute-uri'), # An absolute URL ('http://example.com/?foo=bar', 'http://example.com/?foo=bar'), # A schema-relative URL ('//example.com/?foo=bar', 'http://example.com/?foo=bar'), # Relative URLs ('/foo/bar/', 'http://testserver/foo/bar/'), ('/foo/./bar/', 'http://testserver/foo/bar/'), ('/foo/../bar/', 'http://testserver/bar/'), ('///foo/bar/', 'http://testserver/foo/bar/'), ) for location, expected_url in tests: with self.subTest(location=location): self.assertEqual(request.build_absolute_uri(location=location), expected_url) class RequestHeadersTests(SimpleTestCase): ENVIRON = { # Non-headers are ignored. 'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, # These non-HTTP prefixed headers are included. 'CONTENT_TYPE': 'text/html', 'CONTENT_LENGTH': '100', # All HTTP-prefixed headers are included. 'HTTP_ACCEPT': '*', 'HTTP_HOST': 'example.com', 'HTTP_USER_AGENT': 'python-requests/1.2.0', } def test_base_request_headers(self): request = HttpRequest() request.META = self.ENVIRON self.assertEqual(dict(request.headers), { 'Content-Type': 'text/html', 'Content-Length': '100', 'Accept': '*', 'Host': 'example.com', 'User-Agent': 'python-requests/1.2.0', }) def test_wsgi_request_headers(self): request = WSGIRequest(self.ENVIRON) self.assertEqual(dict(request.headers), { 'Content-Type': 'text/html', 'Content-Length': '100', 'Accept': '*', 'Host': 'example.com', 'User-Agent': 'python-requests/1.2.0', }) def test_wsgi_request_headers_getitem(self): request = WSGIRequest(self.ENVIRON) self.assertEqual(request.headers['User-Agent'], 'python-requests/1.2.0') self.assertEqual(request.headers['user-agent'], 'python-requests/1.2.0') self.assertEqual(request.headers['user_agent'], 'python-requests/1.2.0') self.assertEqual(request.headers['Content-Type'], 'text/html') self.assertEqual(request.headers['Content-Length'], '100') def test_wsgi_request_headers_get(self): request = WSGIRequest(self.ENVIRON) self.assertEqual(request.headers.get('User-Agent'), 'python-requests/1.2.0') self.assertEqual(request.headers.get('user-agent'), 'python-requests/1.2.0') self.assertEqual(request.headers.get('Content-Type'), 'text/html') self.assertEqual(request.headers.get('Content-Length'), '100') class HttpHeadersTests(SimpleTestCase): def test_basic(self): environ = { 'CONTENT_TYPE': 'text/html', 'CONTENT_LENGTH': '100', 'HTTP_HOST': 'example.com', } headers = HttpHeaders(environ) self.assertEqual(sorted(headers), ['Content-Length', 'Content-Type', 'Host']) self.assertEqual(headers, { 'Content-Type': 'text/html', 'Content-Length': '100', 'Host': 'example.com', }) def test_parse_header_name(self): tests = ( ('PATH_INFO', None), ('HTTP_ACCEPT', 'Accept'), ('HTTP_USER_AGENT', 'User-Agent'), ('HTTP_X_FORWARDED_PROTO', 'X-Forwarded-Proto'), ('CONTENT_TYPE', 'Content-Type'), ('CONTENT_LENGTH', 'Content-Length'), ) for header, expected in tests: with self.subTest(header=header): self.assertEqual(HttpHeaders.parse_header_name(header), expected)
a47ad75f093a7688ce2c0fd6431e4e49533982d51b164374f67cb75d5b44f090
import datetime import pickle import sys import unittest from operator import attrgetter from django.core.exceptions import EmptyResultSet, FieldError from django.db import DEFAULT_DB_ALIAS, connection from django.db.models import Count, Exists, F, OuterRef, Q from django.db.models.sql.constants import LOUTER from django.db.models.sql.where import NothingNode, WhereNode from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from .models import ( FK1, Annotation, Article, Author, BaseA, Book, CategoryItem, CategoryRelationship, Celebrity, Channel, Chapter, Child, ChildObjectA, Classroom, CommonMixedCaseForeignKeys, Company, Cover, CustomPk, CustomPkTag, DateTimePK, Detail, DumbCategory, Eaten, Employment, ExtraInfo, Fan, Food, Identifier, Individual, Item, Job, JobResponsibilities, Join, LeafA, LeafB, LoopX, LoopZ, ManagedModel, Member, MixedCaseDbColumnCategoryItem, MixedCaseFieldCategoryItem, ModelA, ModelB, ModelC, ModelD, MyObject, NamedCategory, Node, Note, NullableName, Number, ObjectA, ObjectB, ObjectC, OneToOneCategory, Order, OrderItem, Page, Paragraph, Person, Plaything, PointerA, Program, ProxyCategory, ProxyObjectA, ProxyObjectB, Ranking, Related, RelatedIndividual, RelatedObject, Report, ReportComment, ReservedName, Responsibility, School, SharedConnection, SimpleCategory, SingleObject, SpecialCategory, Staff, StaffUser, Student, Tag, Task, Teacher, Ticket21203Child, Ticket21203Parent, Ticket23605A, Ticket23605B, Ticket23605C, TvChef, Valid, X, ) class Queries1Tests(TestCase): @classmethod def setUpTestData(cls): generic = NamedCategory.objects.create(name="Generic") cls.t1 = Tag.objects.create(name='t1', category=generic) cls.t2 = Tag.objects.create(name='t2', parent=cls.t1, category=generic) cls.t3 = Tag.objects.create(name='t3', parent=cls.t1) t4 = Tag.objects.create(name='t4', parent=cls.t3) cls.t5 = Tag.objects.create(name='t5', parent=cls.t3) cls.n1 = Note.objects.create(note='n1', misc='foo', id=1) cls.n2 = Note.objects.create(note='n2', misc='bar', id=2) cls.n3 = Note.objects.create(note='n3', misc='foo', id=3) ann1 = Annotation.objects.create(name='a1', tag=cls.t1) ann1.notes.add(cls.n1) ann2 = Annotation.objects.create(name='a2', tag=t4) ann2.notes.add(cls.n2, cls.n3) # Create these out of order so that sorting by 'id' will be different to sorting # by 'info'. Helps detect some problems later. cls.e2 = ExtraInfo.objects.create(info='e2', note=cls.n2, value=41) e1 = ExtraInfo.objects.create(info='e1', note=cls.n1, value=42) cls.a1 = Author.objects.create(name='a1', num=1001, extra=e1) cls.a2 = Author.objects.create(name='a2', num=2002, extra=e1) a3 = Author.objects.create(name='a3', num=3003, extra=cls.e2) cls.a4 = Author.objects.create(name='a4', num=4004, extra=cls.e2) cls.time1 = datetime.datetime(2007, 12, 19, 22, 25, 0) cls.time2 = datetime.datetime(2007, 12, 19, 21, 0, 0) time3 = datetime.datetime(2007, 12, 20, 22, 25, 0) time4 = datetime.datetime(2007, 12, 20, 21, 0, 0) cls.i1 = Item.objects.create(name='one', created=cls.time1, modified=cls.time1, creator=cls.a1, note=cls.n3) cls.i1.tags.set([cls.t1, cls.t2]) cls.i2 = Item.objects.create(name='two', created=cls.time2, creator=cls.a2, note=cls.n2) cls.i2.tags.set([cls.t1, cls.t3]) cls.i3 = Item.objects.create(name='three', created=time3, creator=cls.a2, note=cls.n3) i4 = Item.objects.create(name='four', created=time4, creator=cls.a4, note=cls.n3) i4.tags.set([t4]) cls.r1 = Report.objects.create(name='r1', creator=cls.a1) Report.objects.create(name='r2', creator=a3) Report.objects.create(name='r3') # Ordering by 'rank' gives us rank2, rank1, rank3. Ordering by the Meta.ordering # will be rank3, rank2, rank1. cls.rank1 = Ranking.objects.create(rank=2, author=cls.a2) Cover.objects.create(title="first", item=i4) Cover.objects.create(title="second", item=cls.i2) def test_subquery_condition(self): qs1 = Tag.objects.filter(pk__lte=0) qs2 = Tag.objects.filter(parent__in=qs1) qs3 = Tag.objects.filter(parent__in=qs2) self.assertEqual(qs3.query.subq_aliases, {'T', 'U', 'V'}) self.assertIn('v0', str(qs3.query).lower()) qs4 = qs3.filter(parent__in=qs1) self.assertEqual(qs4.query.subq_aliases, {'T', 'U', 'V'}) # It is possible to reuse U for the second subquery, no need to use W. self.assertNotIn('w0', str(qs4.query).lower()) # So, 'U0."id"' is referenced in SELECT and WHERE twice. self.assertEqual(str(qs4.query).lower().count('u0.'), 4) def test_ticket1050(self): self.assertQuerysetEqual( Item.objects.filter(tags__isnull=True), ['<Item: three>'] ) self.assertQuerysetEqual( Item.objects.filter(tags__id__isnull=True), ['<Item: three>'] ) def test_ticket1801(self): self.assertQuerysetEqual( Author.objects.filter(item=self.i2), ['<Author: a2>'] ) self.assertQuerysetEqual( Author.objects.filter(item=self.i3), ['<Author: a2>'] ) self.assertQuerysetEqual( Author.objects.filter(item=self.i2) & Author.objects.filter(item=self.i3), ['<Author: a2>'] ) def test_ticket2306(self): # Checking that no join types are "left outer" joins. query = Item.objects.filter(tags=self.t2).query self.assertNotIn(LOUTER, [x.join_type for x in query.alias_map.values()]) self.assertQuerysetEqual( Item.objects.filter(Q(tags=self.t1)).order_by('name'), ['<Item: one>', '<Item: two>'] ) self.assertQuerysetEqual( Item.objects.filter(Q(tags=self.t1)).filter(Q(tags=self.t2)), ['<Item: one>'] ) self.assertQuerysetEqual( Item.objects.filter(Q(tags=self.t1)).filter(Q(creator__name='fred') | Q(tags=self.t2)), ['<Item: one>'] ) # Each filter call is processed "at once" against a single table, so this is # different from the previous example as it tries to find tags that are two # things at once (rather than two tags). self.assertQuerysetEqual( Item.objects.filter(Q(tags=self.t1) & Q(tags=self.t2)), [] ) self.assertQuerysetEqual( Item.objects.filter(Q(tags=self.t1), Q(creator__name='fred') | Q(tags=self.t2)), [] ) qs = Author.objects.filter(ranking__rank=2, ranking__id=self.rank1.id) self.assertQuerysetEqual(list(qs), ['<Author: a2>']) self.assertEqual(2, qs.query.count_active_tables(), 2) qs = Author.objects.filter(ranking__rank=2).filter(ranking__id=self.rank1.id) self.assertEqual(qs.query.count_active_tables(), 3) def test_ticket4464(self): self.assertQuerysetEqual( Item.objects.filter(tags=self.t1).filter(tags=self.t2), ['<Item: one>'] ) self.assertQuerysetEqual( Item.objects.filter(tags__in=[self.t1, self.t2]).distinct().order_by('name'), ['<Item: one>', '<Item: two>'] ) self.assertQuerysetEqual( Item.objects.filter(tags__in=[self.t1, self.t2]).filter(tags=self.t3), ['<Item: two>'] ) # Make sure .distinct() works with slicing (this was broken in Oracle). self.assertQuerysetEqual( Item.objects.filter(tags__in=[self.t1, self.t2]).order_by('name')[:3], ['<Item: one>', '<Item: one>', '<Item: two>'] ) self.assertQuerysetEqual( Item.objects.filter(tags__in=[self.t1, self.t2]).distinct().order_by('name')[:3], ['<Item: one>', '<Item: two>'] ) def test_tickets_2080_3592(self): self.assertQuerysetEqual( Author.objects.filter(item__name='one') | Author.objects.filter(name='a3'), ['<Author: a1>', '<Author: a3>'] ) self.assertQuerysetEqual( Author.objects.filter(Q(item__name='one') | Q(name='a3')), ['<Author: a1>', '<Author: a3>'] ) self.assertQuerysetEqual( Author.objects.filter(Q(name='a3') | Q(item__name='one')), ['<Author: a1>', '<Author: a3>'] ) self.assertQuerysetEqual( Author.objects.filter(Q(item__name='three') | Q(report__name='r3')), ['<Author: a2>'] ) def test_ticket6074(self): # Merging two empty result sets shouldn't leave a queryset with no constraints # (which would match everything). self.assertQuerysetEqual(Author.objects.filter(Q(id__in=[])), []) self.assertQuerysetEqual( Author.objects.filter(Q(id__in=[]) | Q(id__in=[])), [] ) def test_tickets_1878_2939(self): self.assertEqual(Item.objects.values('creator').distinct().count(), 3) # Create something with a duplicate 'name' so that we can test multi-column # cases (which require some tricky SQL transformations under the covers). xx = Item(name='four', created=self.time1, creator=self.a2, note=self.n1) xx.save() self.assertEqual( Item.objects.exclude(name='two').values('creator', 'name').distinct().count(), 4 ) self.assertEqual( ( Item.objects .exclude(name='two') .extra(select={'foo': '%s'}, select_params=(1,)) .values('creator', 'name', 'foo') .distinct() .count() ), 4 ) self.assertEqual( ( Item.objects .exclude(name='two') .extra(select={'foo': '%s'}, select_params=(1,)) .values('creator', 'name') .distinct() .count() ), 4 ) xx.delete() def test_ticket7323(self): self.assertEqual(Item.objects.values('creator', 'name').count(), 4) def test_ticket2253(self): q1 = Item.objects.order_by('name') q2 = Item.objects.filter(id=self.i1.id) self.assertQuerysetEqual( q1, ['<Item: four>', '<Item: one>', '<Item: three>', '<Item: two>'] ) self.assertQuerysetEqual(q2, ['<Item: one>']) self.assertQuerysetEqual( (q1 | q2).order_by('name'), ['<Item: four>', '<Item: one>', '<Item: three>', '<Item: two>'] ) self.assertQuerysetEqual((q1 & q2).order_by('name'), ['<Item: one>']) q1 = Item.objects.filter(tags=self.t1) q2 = Item.objects.filter(note=self.n3, tags=self.t2) q3 = Item.objects.filter(creator=self.a4) self.assertQuerysetEqual( ((q1 & q2) | q3).order_by('name'), ['<Item: four>', '<Item: one>'] ) def test_order_by_tables(self): q1 = Item.objects.order_by('name') q2 = Item.objects.filter(id=self.i1.id) list(q2) combined_query = (q1 & q2).order_by('name').query self.assertEqual(len([ t for t in combined_query.alias_map if combined_query.alias_refcount[t] ]), 1) def test_order_by_join_unref(self): """ This test is related to the above one, testing that there aren't old JOINs in the query. """ qs = Celebrity.objects.order_by('greatest_fan__fan_of') self.assertIn('OUTER JOIN', str(qs.query)) qs = qs.order_by('id') self.assertNotIn('OUTER JOIN', str(qs.query)) def test_get_clears_ordering(self): """ get() should clear ordering for optimization purposes. """ with CaptureQueriesContext(connection) as captured_queries: Author.objects.order_by('name').get(pk=self.a1.pk) self.assertNotIn('order by', captured_queries[0]['sql'].lower()) def test_tickets_4088_4306(self): self.assertQuerysetEqual( Report.objects.filter(creator=1001), ['<Report: r1>'] ) self.assertQuerysetEqual( Report.objects.filter(creator__num=1001), ['<Report: r1>'] ) self.assertQuerysetEqual(Report.objects.filter(creator__id=1001), []) self.assertQuerysetEqual( Report.objects.filter(creator__id=self.a1.id), ['<Report: r1>'] ) self.assertQuerysetEqual( Report.objects.filter(creator__name='a1'), ['<Report: r1>'] ) def test_ticket4510(self): self.assertQuerysetEqual( Author.objects.filter(report__name='r1'), ['<Author: a1>'] ) def test_ticket7378(self): self.assertQuerysetEqual(self.a1.report_set.all(), ['<Report: r1>']) def test_tickets_5324_6704(self): self.assertQuerysetEqual( Item.objects.filter(tags__name='t4'), ['<Item: four>'] ) self.assertQuerysetEqual( Item.objects.exclude(tags__name='t4').order_by('name').distinct(), ['<Item: one>', '<Item: three>', '<Item: two>'] ) self.assertQuerysetEqual( Item.objects.exclude(tags__name='t4').order_by('name').distinct().reverse(), ['<Item: two>', '<Item: three>', '<Item: one>'] ) self.assertQuerysetEqual( Author.objects.exclude(item__name='one').distinct().order_by('name'), ['<Author: a2>', '<Author: a3>', '<Author: a4>'] ) # Excluding across a m2m relation when there is more than one related # object associated was problematic. self.assertQuerysetEqual( Item.objects.exclude(tags__name='t1').order_by('name'), ['<Item: four>', '<Item: three>'] ) self.assertQuerysetEqual( Item.objects.exclude(tags__name='t1').exclude(tags__name='t4'), ['<Item: three>'] ) # Excluding from a relation that cannot be NULL should not use outer joins. query = Item.objects.exclude(creator__in=[self.a1, self.a2]).query self.assertNotIn(LOUTER, [x.join_type for x in query.alias_map.values()]) # Similarly, when one of the joins cannot possibly, ever, involve NULL # values (Author -> ExtraInfo, in the following), it should never be # promoted to a left outer join. So the following query should only # involve one "left outer" join (Author -> Item is 0-to-many). qs = Author.objects.filter(id=self.a1.id).filter(Q(extra__note=self.n1) | Q(item__note=self.n3)) self.assertEqual( len([ x for x in qs.query.alias_map.values() if x.join_type == LOUTER and qs.query.alias_refcount[x.table_alias] ]), 1 ) # The previous changes shouldn't affect nullable foreign key joins. self.assertQuerysetEqual( Tag.objects.filter(parent__isnull=True).order_by('name'), ['<Tag: t1>'] ) self.assertQuerysetEqual( Tag.objects.exclude(parent__isnull=True).order_by('name'), ['<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Tag.objects.exclude(Q(parent__name='t1') | Q(parent__isnull=True)).order_by('name'), ['<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Tag.objects.exclude(Q(parent__isnull=True) | Q(parent__name='t1')).order_by('name'), ['<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Tag.objects.exclude(Q(parent__parent__isnull=True)).order_by('name'), ['<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Tag.objects.filter(~Q(parent__parent__isnull=True)).order_by('name'), ['<Tag: t4>', '<Tag: t5>'] ) def test_ticket2091(self): t = Tag.objects.get(name='t4') self.assertQuerysetEqual( Item.objects.filter(tags__in=[t]), ['<Item: four>'] ) def test_avoid_infinite_loop_on_too_many_subqueries(self): x = Tag.objects.filter(pk=1) local_recursion_limit = sys.getrecursionlimit() // 16 msg = 'Maximum recursion depth exceeded: too many subqueries.' with self.assertRaisesMessage(RecursionError, msg): for i in range(local_recursion_limit + 2): x = Tag.objects.filter(pk__in=x) def test_reasonable_number_of_subq_aliases(self): x = Tag.objects.filter(pk=1) for _ in range(20): x = Tag.objects.filter(pk__in=x) self.assertEqual( x.query.subq_aliases, { 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', } ) def test_heterogeneous_qs_combination(self): # Combining querysets built on different models should behave in a well-defined # fashion. We raise an error. with self.assertRaisesMessage(AssertionError, 'Cannot combine queries on two different base models.'): Author.objects.all() & Tag.objects.all() with self.assertRaisesMessage(AssertionError, 'Cannot combine queries on two different base models.'): Author.objects.all() | Tag.objects.all() def test_ticket3141(self): self.assertEqual(Author.objects.extra(select={'foo': '1'}).count(), 4) self.assertEqual( Author.objects.extra(select={'foo': '%s'}, select_params=(1,)).count(), 4 ) def test_ticket2400(self): self.assertQuerysetEqual( Author.objects.filter(item__isnull=True), ['<Author: a3>'] ) self.assertQuerysetEqual( Tag.objects.filter(item__isnull=True), ['<Tag: t5>'] ) def test_ticket2496(self): self.assertQuerysetEqual( Item.objects.extra(tables=['queries_author']).select_related().order_by('name')[:1], ['<Item: four>'] ) def test_error_raised_on_filter_with_dictionary(self): with self.assertRaisesMessage(FieldError, 'Cannot parse keyword query as dict'): Note.objects.filter({'note': 'n1', 'misc': 'foo'}) def test_tickets_2076_7256(self): # Ordering on related tables should be possible, even if the table is # not otherwise involved. self.assertQuerysetEqual( Item.objects.order_by('note__note', 'name'), ['<Item: two>', '<Item: four>', '<Item: one>', '<Item: three>'] ) # Ordering on a related field should use the remote model's default # ordering as a final step. self.assertQuerysetEqual( Author.objects.order_by('extra', '-name'), ['<Author: a2>', '<Author: a1>', '<Author: a4>', '<Author: a3>'] ) # Using remote model default ordering can span multiple models (in this # case, Cover is ordered by Item's default, which uses Note's default). self.assertQuerysetEqual( Cover.objects.all(), ['<Cover: first>', '<Cover: second>'] ) # If the remote model does not have a default ordering, we order by its 'id' # field. self.assertQuerysetEqual( Item.objects.order_by('creator', 'name'), ['<Item: one>', '<Item: three>', '<Item: two>', '<Item: four>'] ) # Ordering by a many-valued attribute (e.g. a many-to-many or reverse # ForeignKey) is legal, but the results might not make sense. That # isn't Django's problem. Garbage in, garbage out. self.assertQuerysetEqual( Item.objects.filter(tags__isnull=False).order_by('tags', 'id'), ['<Item: one>', '<Item: two>', '<Item: one>', '<Item: two>', '<Item: four>'] ) # If we replace the default ordering, Django adjusts the required # tables automatically. Item normally requires a join with Note to do # the default ordering, but that isn't needed here. qs = Item.objects.order_by('name') self.assertQuerysetEqual( qs, ['<Item: four>', '<Item: one>', '<Item: three>', '<Item: two>'] ) self.assertEqual(len(qs.query.alias_map), 1) def test_tickets_2874_3002(self): qs = Item.objects.select_related().order_by('note__note', 'name') self.assertQuerysetEqual( qs, ['<Item: two>', '<Item: four>', '<Item: one>', '<Item: three>'] ) # This is also a good select_related() test because there are multiple # Note entries in the SQL. The two Note items should be different. self.assertEqual(repr(qs[0].note), '<Note: n2>') self.assertEqual(repr(qs[0].creator.extra.note), '<Note: n1>') def test_ticket3037(self): self.assertQuerysetEqual( Item.objects.filter(Q(creator__name='a3', name='two') | Q(creator__name='a4', name='four')), ['<Item: four>'] ) def test_tickets_5321_7070(self): # Ordering columns must be included in the output columns. Note that # this means results that might otherwise be distinct are not (if there # are multiple values in the ordering cols), as in this example. This # isn't a bug; it's a warning to be careful with the selection of # ordering columns. self.assertSequenceEqual( Note.objects.values('misc').distinct().order_by('note', '-misc'), [{'misc': 'foo'}, {'misc': 'bar'}, {'misc': 'foo'}] ) def test_ticket4358(self): # If you don't pass any fields to values(), relation fields are # returned as "foo_id" keys, not "foo". For consistency, you should be # able to pass "foo_id" in the fields list and have it work, too. We # actually allow both "foo" and "foo_id". # The *_id version is returned by default. self.assertIn('note_id', ExtraInfo.objects.values()[0]) # You can also pass it in explicitly. self.assertSequenceEqual(ExtraInfo.objects.values('note_id'), [{'note_id': 1}, {'note_id': 2}]) # ...or use the field name. self.assertSequenceEqual(ExtraInfo.objects.values('note'), [{'note': 1}, {'note': 2}]) def test_ticket6154(self): # Multiple filter statements are joined using "AND" all the time. self.assertQuerysetEqual( Author.objects.filter(id=self.a1.id).filter(Q(extra__note=self.n1) | Q(item__note=self.n3)), ['<Author: a1>'] ) self.assertQuerysetEqual( Author.objects.filter(Q(extra__note=self.n1) | Q(item__note=self.n3)).filter(id=self.a1.id), ['<Author: a1>'] ) def test_ticket6981(self): self.assertQuerysetEqual( Tag.objects.select_related('parent').order_by('name'), ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'] ) def test_ticket9926(self): self.assertQuerysetEqual( Tag.objects.select_related("parent", "category").order_by('name'), ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Tag.objects.select_related('parent', "parent__category").order_by('name'), ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'] ) def test_tickets_6180_6203(self): # Dates with limits and/or counts self.assertEqual(Item.objects.count(), 4) self.assertEqual(Item.objects.datetimes('created', 'month').count(), 1) self.assertEqual(Item.objects.datetimes('created', 'day').count(), 2) self.assertEqual(len(Item.objects.datetimes('created', 'day')), 2) self.assertEqual(Item.objects.datetimes('created', 'day')[0], datetime.datetime(2007, 12, 19, 0, 0)) def test_tickets_7087_12242(self): # Dates with extra select columns self.assertQuerysetEqual( Item.objects.datetimes('created', 'day').extra(select={'a': 1}), ['datetime.datetime(2007, 12, 19, 0, 0)', 'datetime.datetime(2007, 12, 20, 0, 0)'] ) self.assertQuerysetEqual( Item.objects.extra(select={'a': 1}).datetimes('created', 'day'), ['datetime.datetime(2007, 12, 19, 0, 0)', 'datetime.datetime(2007, 12, 20, 0, 0)'] ) name = "one" self.assertQuerysetEqual( Item.objects.datetimes('created', 'day').extra(where=['name=%s'], params=[name]), ['datetime.datetime(2007, 12, 19, 0, 0)'] ) self.assertQuerysetEqual( Item.objects.extra(where=['name=%s'], params=[name]).datetimes('created', 'day'), ['datetime.datetime(2007, 12, 19, 0, 0)'] ) def test_ticket7155(self): # Nullable dates self.assertQuerysetEqual( Item.objects.datetimes('modified', 'day'), ['datetime.datetime(2007, 12, 19, 0, 0)'] ) def test_ticket7098(self): # Make sure semi-deprecated ordering by related models syntax still # works. self.assertSequenceEqual( Item.objects.values('note__note').order_by('queries_note.note', 'id'), [{'note__note': 'n2'}, {'note__note': 'n3'}, {'note__note': 'n3'}, {'note__note': 'n3'}] ) def test_ticket7096(self): # Make sure exclude() with multiple conditions continues to work. self.assertQuerysetEqual( Tag.objects.filter(parent=self.t1, name='t3').order_by('name'), ['<Tag: t3>'] ) self.assertQuerysetEqual( Tag.objects.exclude(parent=self.t1, name='t3').order_by('name'), ['<Tag: t1>', '<Tag: t2>', '<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Item.objects.exclude(tags__name='t1', name='one').order_by('name').distinct(), ['<Item: four>', '<Item: three>', '<Item: two>'] ) self.assertQuerysetEqual( Item.objects.filter(name__in=['three', 'four']).exclude(tags__name='t1').order_by('name'), ['<Item: four>', '<Item: three>'] ) # More twisted cases, involving nested negations. self.assertQuerysetEqual( Item.objects.exclude(~Q(tags__name='t1', name='one')), ['<Item: one>'] ) self.assertQuerysetEqual( Item.objects.filter(~Q(tags__name='t1', name='one'), name='two'), ['<Item: two>'] ) self.assertQuerysetEqual( Item.objects.exclude(~Q(tags__name='t1', name='one'), name='two'), ['<Item: four>', '<Item: one>', '<Item: three>'] ) def test_tickets_7204_7506(self): # Make sure querysets with related fields can be pickled. If this # doesn't crash, it's a Good Thing. pickle.dumps(Item.objects.all()) def test_ticket7813(self): # We should also be able to pickle things that use select_related(). # The only tricky thing here is to ensure that we do the related # selections properly after unpickling. qs = Item.objects.select_related() query = qs.query.get_compiler(qs.db).as_sql()[0] query2 = pickle.loads(pickle.dumps(qs.query)) self.assertEqual( query2.get_compiler(qs.db).as_sql()[0], query ) def test_deferred_load_qs_pickling(self): # Check pickling of deferred-loading querysets qs = Item.objects.defer('name', 'creator') q2 = pickle.loads(pickle.dumps(qs)) self.assertEqual(list(qs), list(q2)) q3 = pickle.loads(pickle.dumps(qs, pickle.HIGHEST_PROTOCOL)) self.assertEqual(list(qs), list(q3)) def test_ticket7277(self): self.assertQuerysetEqual( self.n1.annotation_set.filter( Q(tag=self.t5) | Q(tag__children=self.t5) | Q(tag__children__children=self.t5) ), ['<Annotation: a1>'] ) def test_tickets_7448_7707(self): # Complex objects should be converted to strings before being used in # lookups. self.assertQuerysetEqual( Item.objects.filter(created__in=[self.time1, self.time2]), ['<Item: one>', '<Item: two>'] ) def test_ticket7235(self): # An EmptyQuerySet should not raise exceptions if it is filtered. Eaten.objects.create(meal='m') q = Eaten.objects.none() with self.assertNumQueries(0): self.assertQuerysetEqual(q.all(), []) self.assertQuerysetEqual(q.filter(meal='m'), []) self.assertQuerysetEqual(q.exclude(meal='m'), []) self.assertQuerysetEqual(q.complex_filter({'pk': 1}), []) self.assertQuerysetEqual(q.select_related('food'), []) self.assertQuerysetEqual(q.annotate(Count('food')), []) self.assertQuerysetEqual(q.order_by('meal', 'food'), []) self.assertQuerysetEqual(q.distinct(), []) self.assertQuerysetEqual( q.extra(select={'foo': "1"}), [] ) self.assertQuerysetEqual(q.reverse(), []) q.query.low_mark = 1 with self.assertRaisesMessage(AssertionError, 'Cannot change a query once a slice has been taken'): q.extra(select={'foo': "1"}) self.assertQuerysetEqual(q.defer('meal'), []) self.assertQuerysetEqual(q.only('meal'), []) def test_ticket7791(self): # There were "issues" when ordering and distinct-ing on fields related # via ForeignKeys. self.assertEqual( len(Note.objects.order_by('extrainfo__info').distinct()), 3 ) # Pickling of QuerySets using datetimes() should work. qs = Item.objects.datetimes('created', 'month') pickle.loads(pickle.dumps(qs)) def test_ticket9997(self): # If a ValuesList or Values queryset is passed as an inner query, we # make sure it's only requesting a single value and use that as the # thing to select. self.assertQuerysetEqual( Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values('name')), ['<Tag: t2>', '<Tag: t3>'] ) # Multi-valued values() and values_list() querysets should raise errors. with self.assertRaisesMessage(TypeError, 'Cannot use multi-field values as a filter value.'): Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values('name', 'id')) with self.assertRaisesMessage(TypeError, 'Cannot use multi-field values as a filter value.'): Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values_list('name', 'id')) def test_ticket9985(self): # qs.values_list(...).values(...) combinations should work. self.assertSequenceEqual( Note.objects.values_list("note", flat=True).values("id").order_by("id"), [{'id': 1}, {'id': 2}, {'id': 3}] ) self.assertQuerysetEqual( Annotation.objects.filter(notes__in=Note.objects.filter(note="n1").values_list('note').values('id')), ['<Annotation: a1>'] ) def test_ticket10205(self): # When bailing out early because of an empty "__in" filter, we need # to set things up correctly internally so that subqueries can continue properly. self.assertEqual(Tag.objects.filter(name__in=()).update(name="foo"), 0) def test_ticket10432(self): # Testing an empty "__in" filter with a generator as the value. def f(): return iter([]) n_obj = Note.objects.all()[0] def g(): yield n_obj.pk self.assertQuerysetEqual(Note.objects.filter(pk__in=f()), []) self.assertEqual(list(Note.objects.filter(pk__in=g())), [n_obj]) def test_ticket10742(self): # Queries used in an __in clause don't execute subqueries subq = Author.objects.filter(num__lt=3000) qs = Author.objects.filter(pk__in=subq) self.assertQuerysetEqual(qs, ['<Author: a1>', '<Author: a2>']) # The subquery result cache should not be populated self.assertIsNone(subq._result_cache) subq = Author.objects.filter(num__lt=3000) qs = Author.objects.exclude(pk__in=subq) self.assertQuerysetEqual(qs, ['<Author: a3>', '<Author: a4>']) # The subquery result cache should not be populated self.assertIsNone(subq._result_cache) subq = Author.objects.filter(num__lt=3000) self.assertQuerysetEqual( Author.objects.filter(Q(pk__in=subq) & Q(name='a1')), ['<Author: a1>'] ) # The subquery result cache should not be populated self.assertIsNone(subq._result_cache) def test_ticket7076(self): # Excluding shouldn't eliminate NULL entries. self.assertQuerysetEqual( Item.objects.exclude(modified=self.time1).order_by('name'), ['<Item: four>', '<Item: three>', '<Item: two>'] ) self.assertQuerysetEqual( Tag.objects.exclude(parent__name=self.t1.name), ['<Tag: t1>', '<Tag: t4>', '<Tag: t5>'] ) def test_ticket7181(self): # Ordering by related tables should accommodate nullable fields (this # test is a little tricky, since NULL ordering is database dependent. # Instead, we just count the number of results). self.assertEqual(len(Tag.objects.order_by('parent__name')), 5) # Empty querysets can be merged with others. self.assertQuerysetEqual( Note.objects.none() | Note.objects.all(), ['<Note: n1>', '<Note: n2>', '<Note: n3>'] ) self.assertQuerysetEqual( Note.objects.all() | Note.objects.none(), ['<Note: n1>', '<Note: n2>', '<Note: n3>'] ) self.assertQuerysetEqual(Note.objects.none() & Note.objects.all(), []) self.assertQuerysetEqual(Note.objects.all() & Note.objects.none(), []) def test_ticket9411(self): # Make sure bump_prefix() (an internal Query method) doesn't (re-)break. It's # sufficient that this query runs without error. qs = Tag.objects.values_list('id', flat=True).order_by('id') qs.query.bump_prefix(qs.query) first = qs[0] self.assertEqual(list(qs), list(range(first, first + 5))) def test_ticket8439(self): # Complex combinations of conjunctions, disjunctions and nullable # relations. self.assertQuerysetEqual( Author.objects.filter(Q(item__note__extrainfo=self.e2) | Q(report=self.r1, name='xyz')), ['<Author: a2>'] ) self.assertQuerysetEqual( Author.objects.filter(Q(report=self.r1, name='xyz') | Q(item__note__extrainfo=self.e2)), ['<Author: a2>'] ) self.assertQuerysetEqual( Annotation.objects.filter(Q(tag__parent=self.t1) | Q(notes__note='n1', name='a1')), ['<Annotation: a1>'] ) xx = ExtraInfo.objects.create(info='xx', note=self.n3) self.assertQuerysetEqual( Note.objects.filter(Q(extrainfo__author=self.a1) | Q(extrainfo=xx)), ['<Note: n1>', '<Note: n3>'] ) q = Note.objects.filter(Q(extrainfo__author=self.a1) | Q(extrainfo=xx)).query self.assertEqual( len([x for x in q.alias_map.values() if x.join_type == LOUTER and q.alias_refcount[x.table_alias]]), 1 ) def test_ticket17429(self): """ Meta.ordering=None works the same as Meta.ordering=[] """ original_ordering = Tag._meta.ordering Tag._meta.ordering = None try: self.assertQuerysetEqual( Tag.objects.all(), ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'], ordered=False ) finally: Tag._meta.ordering = original_ordering def test_exclude(self): self.assertQuerysetEqual( Item.objects.exclude(tags__name='t4'), [repr(i) for i in Item.objects.filter(~Q(tags__name='t4'))]) self.assertQuerysetEqual( Item.objects.exclude(Q(tags__name='t4') | Q(tags__name='t3')), [repr(i) for i in Item.objects.filter(~(Q(tags__name='t4') | Q(tags__name='t3')))]) self.assertQuerysetEqual( Item.objects.exclude(Q(tags__name='t4') | ~Q(tags__name='t3')), [repr(i) for i in Item.objects.filter(~(Q(tags__name='t4') | ~Q(tags__name='t3')))]) def test_nested_exclude(self): self.assertQuerysetEqual( Item.objects.exclude(~Q(tags__name='t4')), [repr(i) for i in Item.objects.filter(~~Q(tags__name='t4'))]) def test_double_exclude(self): self.assertQuerysetEqual( Item.objects.filter(Q(tags__name='t4')), [repr(i) for i in Item.objects.filter(~~Q(tags__name='t4'))]) self.assertQuerysetEqual( Item.objects.filter(Q(tags__name='t4')), [repr(i) for i in Item.objects.filter(~Q(~Q(tags__name='t4')))]) def test_exclude_in(self): self.assertQuerysetEqual( Item.objects.exclude(Q(tags__name__in=['t4', 't3'])), [repr(i) for i in Item.objects.filter(~Q(tags__name__in=['t4', 't3']))]) self.assertQuerysetEqual( Item.objects.filter(Q(tags__name__in=['t4', 't3'])), [repr(i) for i in Item.objects.filter(~~Q(tags__name__in=['t4', 't3']))]) def test_ticket_10790_1(self): # Querying direct fields with isnull should trim the left outer join. # It also should not create INNER JOIN. q = Tag.objects.filter(parent__isnull=True) self.assertQuerysetEqual(q, ['<Tag: t1>']) self.assertNotIn('JOIN', str(q.query)) q = Tag.objects.filter(parent__isnull=False) self.assertQuerysetEqual( q, ['<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'], ) self.assertNotIn('JOIN', str(q.query)) q = Tag.objects.exclude(parent__isnull=True) self.assertQuerysetEqual( q, ['<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'], ) self.assertNotIn('JOIN', str(q.query)) q = Tag.objects.exclude(parent__isnull=False) self.assertQuerysetEqual(q, ['<Tag: t1>']) self.assertNotIn('JOIN', str(q.query)) q = Tag.objects.exclude(parent__parent__isnull=False) self.assertQuerysetEqual( q, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'], ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1) self.assertNotIn('INNER JOIN', str(q.query)) def test_ticket_10790_2(self): # Querying across several tables should strip only the last outer join, # while preserving the preceding inner joins. q = Tag.objects.filter(parent__parent__isnull=False) self.assertQuerysetEqual( q, ['<Tag: t4>', '<Tag: t5>'], ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 1) # Querying without isnull should not convert anything to left outer join. q = Tag.objects.filter(parent__parent=self.t1) self.assertQuerysetEqual( q, ['<Tag: t4>', '<Tag: t5>'], ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 1) def test_ticket_10790_3(self): # Querying via indirect fields should populate the left outer join q = NamedCategory.objects.filter(tag__isnull=True) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1) # join to dumbcategory ptr_id self.assertEqual(str(q.query).count('INNER JOIN'), 1) self.assertQuerysetEqual(q, []) # Querying across several tables should strip only the last join, while # preserving the preceding left outer joins. q = NamedCategory.objects.filter(tag__parent__isnull=True) self.assertEqual(str(q.query).count('INNER JOIN'), 1) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1) self.assertQuerysetEqual(q, ['<NamedCategory: Generic>']) def test_ticket_10790_4(self): # Querying across m2m field should not strip the m2m table from join. q = Author.objects.filter(item__tags__isnull=True) self.assertQuerysetEqual( q, ['<Author: a2>', '<Author: a3>'], ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 2) self.assertNotIn('INNER JOIN', str(q.query)) q = Author.objects.filter(item__tags__parent__isnull=True) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a3>'], ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 3) self.assertNotIn('INNER JOIN', str(q.query)) def test_ticket_10790_5(self): # Querying with isnull=False across m2m field should not create outer joins q = Author.objects.filter(item__tags__isnull=False) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a4>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 2) q = Author.objects.filter(item__tags__parent__isnull=False) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a2>', '<Author: a4>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 3) q = Author.objects.filter(item__tags__parent__parent__isnull=False) self.assertQuerysetEqual( q, ['<Author: a4>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 4) def test_ticket_10790_6(self): # Querying with isnull=True across m2m field should not create inner joins # and strip last outer join q = Author.objects.filter(item__tags__parent__parent__isnull=True) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a2>', '<Author: a3>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 4) self.assertEqual(str(q.query).count('INNER JOIN'), 0) q = Author.objects.filter(item__tags__parent__isnull=True) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a3>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 3) self.assertEqual(str(q.query).count('INNER JOIN'), 0) def test_ticket_10790_7(self): # Reverse querying with isnull should not strip the join q = Author.objects.filter(item__isnull=True) self.assertQuerysetEqual( q, ['<Author: a3>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1) self.assertEqual(str(q.query).count('INNER JOIN'), 0) q = Author.objects.filter(item__isnull=False) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a4>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 1) def test_ticket_10790_8(self): # Querying with combined q-objects should also strip the left outer join q = Tag.objects.filter(Q(parent__isnull=True) | Q(parent=self.t1)) self.assertQuerysetEqual( q, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 0) def test_ticket_10790_combine(self): # Combining queries should not re-populate the left outer join q1 = Tag.objects.filter(parent__isnull=True) q2 = Tag.objects.filter(parent__isnull=False) q3 = q1 | q2 self.assertQuerysetEqual( q3, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'], ) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) q3 = q1 & q2 self.assertQuerysetEqual(q3, []) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) q2 = Tag.objects.filter(parent=self.t1) q3 = q1 | q2 self.assertQuerysetEqual( q3, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'] ) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) q3 = q2 | q1 self.assertQuerysetEqual( q3, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'] ) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) q1 = Tag.objects.filter(parent__isnull=True) q2 = Tag.objects.filter(parent__parent__isnull=True) q3 = q1 | q2 self.assertQuerysetEqual( q3, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'] ) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 1) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) q3 = q2 | q1 self.assertQuerysetEqual( q3, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'] ) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 1) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) def test_ticket19672(self): self.assertQuerysetEqual( Report.objects.filter(Q(creator__isnull=False) & ~Q(creator__extra__value=41)), ['<Report: r1>'] ) def test_ticket_20250(self): # A negated Q along with an annotated queryset failed in Django 1.4 qs = Author.objects.annotate(Count('item')) qs = qs.filter(~Q(extra__value=0)).order_by('name') self.assertIn('SELECT', str(qs.query)) self.assertQuerysetEqual( qs, ['<Author: a1>', '<Author: a2>', '<Author: a3>', '<Author: a4>'] ) def test_lookup_constraint_fielderror(self): msg = ( "Cannot resolve keyword 'unknown_field' into field. Choices are: " "annotation, category, category_id, children, id, item, " "managedmodel, name, note, parent, parent_id" ) with self.assertRaisesMessage(FieldError, msg): Tag.objects.filter(unknown_field__name='generic') def test_common_mixed_case_foreign_keys(self): """ Valid query should be generated when fields fetched from joined tables include FKs whose names only differ by case. """ c1 = SimpleCategory.objects.create(name='c1') c2 = SimpleCategory.objects.create(name='c2') c3 = SimpleCategory.objects.create(name='c3') category = CategoryItem.objects.create(category=c1) mixed_case_field_category = MixedCaseFieldCategoryItem.objects.create(CaTeGoRy=c2) mixed_case_db_column_category = MixedCaseDbColumnCategoryItem.objects.create(category=c3) CommonMixedCaseForeignKeys.objects.create( category=category, mixed_case_field_category=mixed_case_field_category, mixed_case_db_column_category=mixed_case_db_column_category, ) qs = CommonMixedCaseForeignKeys.objects.values( 'category', 'mixed_case_field_category', 'mixed_case_db_column_category', 'category__category', 'mixed_case_field_category__CaTeGoRy', 'mixed_case_db_column_category__category', ) self.assertTrue(qs.first()) def test_excluded_intermediary_m2m_table_joined(self): self.assertSequenceEqual( Note.objects.filter(~Q(tag__annotation__name=F('note'))), [self.n1, self.n2, self.n3], ) self.assertSequenceEqual( Note.objects.filter(tag__annotation__name='a1').filter(~Q(tag__annotation__name=F('note'))), [], ) class Queries2Tests(TestCase): @classmethod def setUpTestData(cls): Number.objects.create(num=4) Number.objects.create(num=8) Number.objects.create(num=12) def test_ticket4289(self): # A slight variation on the restricting the filtering choices by the # lookup constraints. self.assertQuerysetEqual(Number.objects.filter(num__lt=4), []) self.assertQuerysetEqual(Number.objects.filter(num__gt=8, num__lt=12), []) self.assertQuerysetEqual( Number.objects.filter(num__gt=8, num__lt=13), ['<Number: 12>'] ) self.assertQuerysetEqual( Number.objects.filter(Q(num__lt=4) | Q(num__gt=8, num__lt=12)), [] ) self.assertQuerysetEqual( Number.objects.filter(Q(num__gt=8, num__lt=12) | Q(num__lt=4)), [] ) self.assertQuerysetEqual( Number.objects.filter(Q(num__gt=8) & Q(num__lt=12) | Q(num__lt=4)), [] ) self.assertQuerysetEqual( Number.objects.filter(Q(num__gt=7) & Q(num__lt=12) | Q(num__lt=4)), ['<Number: 8>'] ) def test_ticket12239(self): # Custom lookups are registered to round float values correctly on gte # and lt IntegerField queries. self.assertQuerysetEqual( Number.objects.filter(num__gt=11.9), ['<Number: 12>'] ) self.assertQuerysetEqual(Number.objects.filter(num__gt=12), []) self.assertQuerysetEqual(Number.objects.filter(num__gt=12.0), []) self.assertQuerysetEqual(Number.objects.filter(num__gt=12.1), []) self.assertQuerysetEqual( Number.objects.filter(num__lt=12), ['<Number: 4>', '<Number: 8>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lt=12.0), ['<Number: 4>', '<Number: 8>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lt=12.1), ['<Number: 4>', '<Number: 8>', '<Number: 12>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__gte=11.9), ['<Number: 12>'] ) self.assertQuerysetEqual( Number.objects.filter(num__gte=12), ['<Number: 12>'] ) self.assertQuerysetEqual( Number.objects.filter(num__gte=12.0), ['<Number: 12>'] ) self.assertQuerysetEqual(Number.objects.filter(num__gte=12.1), []) self.assertQuerysetEqual(Number.objects.filter(num__gte=12.9), []) self.assertQuerysetEqual( Number.objects.filter(num__lte=11.9), ['<Number: 4>', '<Number: 8>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lte=12), ['<Number: 4>', '<Number: 8>', '<Number: 12>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lte=12.0), ['<Number: 4>', '<Number: 8>', '<Number: 12>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lte=12.1), ['<Number: 4>', '<Number: 8>', '<Number: 12>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lte=12.9), ['<Number: 4>', '<Number: 8>', '<Number: 12>'], ordered=False ) def test_ticket7759(self): # Count should work with a partially read result set. count = Number.objects.count() qs = Number.objects.all() def run(): for obj in qs: return qs.count() == count self.assertTrue(run()) class Queries3Tests(TestCase): def test_ticket7107(self): # This shouldn't create an infinite loop. self.assertQuerysetEqual(Valid.objects.all(), []) def test_ticket8683(self): # An error should be raised when QuerySet.datetimes() is passed the # wrong type of field. with self.assertRaisesMessage(AssertionError, "'name' isn't a DateField, TimeField, or DateTimeField."): Item.objects.datetimes('name', 'month') def test_ticket22023(self): with self.assertRaisesMessage(TypeError, "Cannot call only() after .values() or .values_list()"): Valid.objects.values().only() with self.assertRaisesMessage(TypeError, "Cannot call defer() after .values() or .values_list()"): Valid.objects.values().defer() class Queries4Tests(TestCase): @classmethod def setUpTestData(cls): generic = NamedCategory.objects.create(name="Generic") cls.t1 = Tag.objects.create(name='t1', category=generic) n1 = Note.objects.create(note='n1', misc='foo') n2 = Note.objects.create(note='n2', misc='bar') e1 = ExtraInfo.objects.create(info='e1', note=n1) e2 = ExtraInfo.objects.create(info='e2', note=n2) cls.a1 = Author.objects.create(name='a1', num=1001, extra=e1) cls.a3 = Author.objects.create(name='a3', num=3003, extra=e2) cls.r1 = Report.objects.create(name='r1', creator=cls.a1) cls.r2 = Report.objects.create(name='r2', creator=cls.a3) cls.r3 = Report.objects.create(name='r3') Item.objects.create(name='i1', created=datetime.datetime.now(), note=n1, creator=cls.a1) Item.objects.create(name='i2', created=datetime.datetime.now(), note=n1, creator=cls.a3) def test_ticket24525(self): tag = Tag.objects.create() anth100 = tag.note_set.create(note='ANTH', misc='100') math101 = tag.note_set.create(note='MATH', misc='101') s1 = tag.annotation_set.create(name='1') s2 = tag.annotation_set.create(name='2') s1.notes.set([math101, anth100]) s2.notes.set([math101]) result = math101.annotation_set.all() & tag.annotation_set.exclude(notes__in=[anth100]) self.assertEqual(list(result), [s2]) def test_ticket11811(self): unsaved_category = NamedCategory(name="Other") msg = 'Unsaved model instance <NamedCategory: Other> cannot be used in an ORM query.' with self.assertRaisesMessage(ValueError, msg): Tag.objects.filter(pk=self.t1.pk).update(category=unsaved_category) def test_ticket14876(self): # Note: when combining the query we need to have information available # about the join type of the trimmed "creator__isnull" join. If we # don't have that information, then the join is created as INNER JOIN # and results will be incorrect. q1 = Report.objects.filter(Q(creator__isnull=True) | Q(creator__extra__info='e1')) q2 = Report.objects.filter(Q(creator__isnull=True)) | Report.objects.filter(Q(creator__extra__info='e1')) self.assertQuerysetEqual(q1, ["<Report: r1>", "<Report: r3>"], ordered=False) self.assertEqual(str(q1.query), str(q2.query)) q1 = Report.objects.filter(Q(creator__extra__info='e1') | Q(creator__isnull=True)) q2 = Report.objects.filter(Q(creator__extra__info='e1')) | Report.objects.filter(Q(creator__isnull=True)) self.assertQuerysetEqual(q1, ["<Report: r1>", "<Report: r3>"], ordered=False) self.assertEqual(str(q1.query), str(q2.query)) q1 = Item.objects.filter(Q(creator=self.a1) | Q(creator__report__name='r1')).order_by() q2 = ( Item.objects .filter(Q(creator=self.a1)).order_by() | Item.objects.filter(Q(creator__report__name='r1')) .order_by() ) self.assertQuerysetEqual(q1, ["<Item: i1>"]) self.assertEqual(str(q1.query), str(q2.query)) q1 = Item.objects.filter(Q(creator__report__name='e1') | Q(creator=self.a1)).order_by() q2 = ( Item.objects.filter(Q(creator__report__name='e1')).order_by() | Item.objects.filter(Q(creator=self.a1)).order_by() ) self.assertQuerysetEqual(q1, ["<Item: i1>"]) self.assertEqual(str(q1.query), str(q2.query)) def test_combine_join_reuse(self): # Joins having identical connections are correctly recreated in the # rhs query, in case the query is ORed together (#18748). Report.objects.create(name='r4', creator=self.a1) q1 = Author.objects.filter(report__name='r5') q2 = Author.objects.filter(report__name='r4').filter(report__name='r1') combined = q1 | q2 self.assertEqual(str(combined.query).count('JOIN'), 2) self.assertEqual(len(combined), 1) self.assertEqual(combined[0].name, 'a1') def test_join_reuse_order(self): # Join aliases are reused in order. This shouldn't raise AssertionError # because change_map contains a circular reference (#26522). s1 = School.objects.create() s2 = School.objects.create() s3 = School.objects.create() t1 = Teacher.objects.create() otherteachers = Teacher.objects.exclude(pk=t1.pk).exclude(friends=t1) qs1 = otherteachers.filter(schools=s1).filter(schools=s2) qs2 = otherteachers.filter(schools=s1).filter(schools=s3) self.assertQuerysetEqual(qs1 | qs2, []) def test_ticket7095(self): # Updates that are filtered on the model being updated are somewhat # tricky in MySQL. ManagedModel.objects.create(data='mm1', tag=self.t1, public=True) self.assertEqual(ManagedModel.objects.update(data='mm'), 1) # A values() or values_list() query across joined models must use outer # joins appropriately. # Note: In Oracle, we expect a null CharField to return '' instead of # None. if connection.features.interprets_empty_strings_as_nulls: expected_null_charfield_repr = '' else: expected_null_charfield_repr = None self.assertSequenceEqual( Report.objects.values_list("creator__extra__info", flat=True).order_by("name"), ['e1', 'e2', expected_null_charfield_repr], ) # Similarly for select_related(), joins beyond an initial nullable join # must use outer joins so that all results are included. self.assertQuerysetEqual( Report.objects.select_related("creator", "creator__extra").order_by("name"), ['<Report: r1>', '<Report: r2>', '<Report: r3>'] ) # When there are multiple paths to a table from another table, we have # to be careful not to accidentally reuse an inappropriate join when # using select_related(). We used to return the parent's Detail record # here by mistake. d1 = Detail.objects.create(data="d1") d2 = Detail.objects.create(data="d2") m1 = Member.objects.create(name="m1", details=d1) m2 = Member.objects.create(name="m2", details=d2) Child.objects.create(person=m2, parent=m1) obj = m1.children.select_related("person__details")[0] self.assertEqual(obj.person.details.data, 'd2') def test_order_by_resetting(self): # Calling order_by() with no parameters removes any existing ordering on the # model. But it should still be possible to add new ordering after that. qs = Author.objects.order_by().order_by('name') self.assertIn('ORDER BY', qs.query.get_compiler(qs.db).as_sql()[0]) def test_order_by_reverse_fk(self): # It is possible to order by reverse of foreign key, although that can lead # to duplicate results. c1 = SimpleCategory.objects.create(name="category1") c2 = SimpleCategory.objects.create(name="category2") CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c2) CategoryItem.objects.create(category=c1) self.assertSequenceEqual(SimpleCategory.objects.order_by('categoryitem', 'pk'), [c1, c2, c1]) def test_filter_reverse_non_integer_pk(self): date_obj = DateTimePK.objects.create() extra_obj = ExtraInfo.objects.create(info='extra', date=date_obj) self.assertEqual( DateTimePK.objects.filter(extrainfo=extra_obj).get(), date_obj, ) def test_ticket10181(self): # Avoid raising an EmptyResultSet if an inner query is probably # empty (and hence, not executed). self.assertQuerysetEqual( Tag.objects.filter(id__in=Tag.objects.filter(id__in=[])), [] ) def test_ticket15316_filter_false(self): c1 = SimpleCategory.objects.create(name="category1") c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") CategoryItem.objects.create(category=c1) ci2 = CategoryItem.objects.create(category=c2) ci3 = CategoryItem.objects.create(category=c3) qs = CategoryItem.objects.filter(category__specialcategory__isnull=False) self.assertEqual(qs.count(), 2) self.assertSequenceEqual(qs, [ci2, ci3]) def test_ticket15316_exclude_false(self): c1 = SimpleCategory.objects.create(name="category1") c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") ci1 = CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c2) CategoryItem.objects.create(category=c3) qs = CategoryItem.objects.exclude(category__specialcategory__isnull=False) self.assertEqual(qs.count(), 1) self.assertSequenceEqual(qs, [ci1]) def test_ticket15316_filter_true(self): c1 = SimpleCategory.objects.create(name="category1") c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") ci1 = CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c2) CategoryItem.objects.create(category=c3) qs = CategoryItem.objects.filter(category__specialcategory__isnull=True) self.assertEqual(qs.count(), 1) self.assertSequenceEqual(qs, [ci1]) def test_ticket15316_exclude_true(self): c1 = SimpleCategory.objects.create(name="category1") c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") CategoryItem.objects.create(category=c1) ci2 = CategoryItem.objects.create(category=c2) ci3 = CategoryItem.objects.create(category=c3) qs = CategoryItem.objects.exclude(category__specialcategory__isnull=True) self.assertEqual(qs.count(), 2) self.assertSequenceEqual(qs, [ci2, ci3]) def test_ticket15316_one2one_filter_false(self): c = SimpleCategory.objects.create(name="cat") c0 = SimpleCategory.objects.create(name="cat0") c1 = SimpleCategory.objects.create(name="category1") OneToOneCategory.objects.create(category=c1, new_name="new1") OneToOneCategory.objects.create(category=c0, new_name="new2") CategoryItem.objects.create(category=c) ci2 = CategoryItem.objects.create(category=c0) ci3 = CategoryItem.objects.create(category=c1) qs = CategoryItem.objects.filter(category__onetoonecategory__isnull=False).order_by('pk') self.assertEqual(qs.count(), 2) self.assertSequenceEqual(qs, [ci2, ci3]) def test_ticket15316_one2one_exclude_false(self): c = SimpleCategory.objects.create(name="cat") c0 = SimpleCategory.objects.create(name="cat0") c1 = SimpleCategory.objects.create(name="category1") OneToOneCategory.objects.create(category=c1, new_name="new1") OneToOneCategory.objects.create(category=c0, new_name="new2") ci1 = CategoryItem.objects.create(category=c) CategoryItem.objects.create(category=c0) CategoryItem.objects.create(category=c1) qs = CategoryItem.objects.exclude(category__onetoonecategory__isnull=False) self.assertEqual(qs.count(), 1) self.assertSequenceEqual(qs, [ci1]) def test_ticket15316_one2one_filter_true(self): c = SimpleCategory.objects.create(name="cat") c0 = SimpleCategory.objects.create(name="cat0") c1 = SimpleCategory.objects.create(name="category1") OneToOneCategory.objects.create(category=c1, new_name="new1") OneToOneCategory.objects.create(category=c0, new_name="new2") ci1 = CategoryItem.objects.create(category=c) CategoryItem.objects.create(category=c0) CategoryItem.objects.create(category=c1) qs = CategoryItem.objects.filter(category__onetoonecategory__isnull=True) self.assertEqual(qs.count(), 1) self.assertSequenceEqual(qs, [ci1]) def test_ticket15316_one2one_exclude_true(self): c = SimpleCategory.objects.create(name="cat") c0 = SimpleCategory.objects.create(name="cat0") c1 = SimpleCategory.objects.create(name="category1") OneToOneCategory.objects.create(category=c1, new_name="new1") OneToOneCategory.objects.create(category=c0, new_name="new2") CategoryItem.objects.create(category=c) ci2 = CategoryItem.objects.create(category=c0) ci3 = CategoryItem.objects.create(category=c1) qs = CategoryItem.objects.exclude(category__onetoonecategory__isnull=True).order_by('pk') self.assertEqual(qs.count(), 2) self.assertSequenceEqual(qs, [ci2, ci3]) class Queries5Tests(TestCase): @classmethod def setUpTestData(cls): # Ordering by 'rank' gives us rank2, rank1, rank3. Ordering by the # Meta.ordering will be rank3, rank2, rank1. n1 = Note.objects.create(note='n1', misc='foo', id=1) n2 = Note.objects.create(note='n2', misc='bar', id=2) e1 = ExtraInfo.objects.create(info='e1', note=n1) e2 = ExtraInfo.objects.create(info='e2', note=n2) a1 = Author.objects.create(name='a1', num=1001, extra=e1) a2 = Author.objects.create(name='a2', num=2002, extra=e1) a3 = Author.objects.create(name='a3', num=3003, extra=e2) cls.rank1 = Ranking.objects.create(rank=2, author=a2) Ranking.objects.create(rank=1, author=a3) Ranking.objects.create(rank=3, author=a1) def test_ordering(self): # Cross model ordering is possible in Meta, too. self.assertQuerysetEqual( Ranking.objects.all(), ['<Ranking: 3: a1>', '<Ranking: 2: a2>', '<Ranking: 1: a3>'] ) self.assertQuerysetEqual( Ranking.objects.all().order_by('rank'), ['<Ranking: 1: a3>', '<Ranking: 2: a2>', '<Ranking: 3: a1>'] ) # Ordering of extra() pieces is possible, too and you can mix extra # fields and model fields in the ordering. self.assertQuerysetEqual( Ranking.objects.extra(tables=['django_site'], order_by=['-django_site.id', 'rank']), ['<Ranking: 1: a3>', '<Ranking: 2: a2>', '<Ranking: 3: a1>'] ) sql = 'case when %s > 2 then 1 else 0 end' % connection.ops.quote_name('rank') qs = Ranking.objects.extra(select={'good': sql}) self.assertEqual( [o.good for o in qs.extra(order_by=('-good',))], [True, False, False] ) self.assertQuerysetEqual( qs.extra(order_by=('-good', 'id')), ['<Ranking: 3: a1>', '<Ranking: 2: a2>', '<Ranking: 1: a3>'] ) # Despite having some extra aliases in the query, we can still omit # them in a values() query. dicts = qs.values('id', 'rank').order_by('id') self.assertEqual( [d['rank'] for d in dicts], [2, 1, 3] ) def test_ticket7256(self): # An empty values() call includes all aliases, including those from an # extra() sql = 'case when %s > 2 then 1 else 0 end' % connection.ops.quote_name('rank') qs = Ranking.objects.extra(select={'good': sql}) dicts = qs.values().order_by('id') for d in dicts: del d['id'] del d['author_id'] self.assertEqual( [sorted(d.items()) for d in dicts], [[('good', 0), ('rank', 2)], [('good', 0), ('rank', 1)], [('good', 1), ('rank', 3)]] ) def test_ticket7045(self): # Extra tables used to crash SQL construction on the second use. qs = Ranking.objects.extra(tables=['django_site']) qs.query.get_compiler(qs.db).as_sql() # test passes if this doesn't raise an exception. qs.query.get_compiler(qs.db).as_sql() def test_ticket9848(self): # Make sure that updates which only filter on sub-tables don't # inadvertently update the wrong records (bug #9848). author_start = Author.objects.get(name='a1') ranking_start = Ranking.objects.get(author__name='a1') # Make sure that the IDs from different tables don't happen to match. self.assertQuerysetEqual( Ranking.objects.filter(author__name='a1'), ['<Ranking: 3: a1>'] ) self.assertEqual( Ranking.objects.filter(author__name='a1').update(rank=4636), 1 ) r = Ranking.objects.get(author__name='a1') self.assertEqual(r.id, ranking_start.id) self.assertEqual(r.author.id, author_start.id) self.assertEqual(r.rank, 4636) r.rank = 3 r.save() self.assertQuerysetEqual( Ranking.objects.all(), ['<Ranking: 3: a1>', '<Ranking: 2: a2>', '<Ranking: 1: a3>'] ) def test_ticket5261(self): # Test different empty excludes. self.assertQuerysetEqual( Note.objects.exclude(Q()), ['<Note: n1>', '<Note: n2>'] ) self.assertQuerysetEqual( Note.objects.filter(~Q()), ['<Note: n1>', '<Note: n2>'] ) self.assertQuerysetEqual( Note.objects.filter(~Q() | ~Q()), ['<Note: n1>', '<Note: n2>'] ) self.assertQuerysetEqual( Note.objects.exclude(~Q() & ~Q()), ['<Note: n1>', '<Note: n2>'] ) def test_extra_select_literal_percent_s(self): # Allow %%s to escape select clauses self.assertEqual( Note.objects.extra(select={'foo': "'%%s'"})[0].foo, '%s' ) self.assertEqual( Note.objects.extra(select={'foo': "'%%s bar %%s'"})[0].foo, '%s bar %s' ) self.assertEqual( Note.objects.extra(select={'foo': "'bar %%s'"})[0].foo, 'bar %s' ) class SelectRelatedTests(TestCase): def test_tickets_3045_3288(self): # Once upon a time, select_related() with circular relations would loop # infinitely if you forgot to specify "depth". Now we set an arbitrary # default upper bound. self.assertQuerysetEqual(X.objects.all(), []) self.assertQuerysetEqual(X.objects.select_related(), []) class SubclassFKTests(TestCase): def test_ticket7778(self): # Model subclasses could not be deleted if a nullable foreign key # relates to a model that relates back. num_celebs = Celebrity.objects.count() tvc = TvChef.objects.create(name="Huey") self.assertEqual(Celebrity.objects.count(), num_celebs + 1) Fan.objects.create(fan_of=tvc) Fan.objects.create(fan_of=tvc) tvc.delete() # The parent object should have been deleted as well. self.assertEqual(Celebrity.objects.count(), num_celebs) class CustomPkTests(TestCase): def test_ticket7371(self): self.assertQuerysetEqual(Related.objects.order_by('custom'), []) class NullableRelOrderingTests(TestCase): def test_ticket10028(self): # Ordering by model related to nullable relations(!) should use outer # joins, so that all results are included. Plaything.objects.create(name="p1") self.assertQuerysetEqual( Plaything.objects.all(), ['<Plaything: p1>'] ) def test_join_already_in_query(self): # Ordering by model related to nullable relations should not change # the join type of already existing joins. Plaything.objects.create(name="p1") s = SingleObject.objects.create(name='s') r = RelatedObject.objects.create(single=s, f=1) Plaything.objects.create(name="p2", others=r) qs = Plaything.objects.all().filter(others__isnull=False).order_by('pk') self.assertNotIn('JOIN', str(qs.query)) qs = Plaything.objects.all().filter(others__f__isnull=False).order_by('pk') self.assertIn('INNER', str(qs.query)) qs = qs.order_by('others__single__name') # The ordering by others__single__pk will add one new join (to single) # and that join must be LEFT join. The already existing join to related # objects must be kept INNER. So, we have both an INNER and a LEFT join # in the query. self.assertEqual(str(qs.query).count('LEFT'), 1) self.assertEqual(str(qs.query).count('INNER'), 1) self.assertQuerysetEqual( qs, ['<Plaything: p2>'] ) class DisjunctiveFilterTests(TestCase): @classmethod def setUpTestData(cls): cls.n1 = Note.objects.create(note='n1', misc='foo', id=1) ExtraInfo.objects.create(info='e1', note=cls.n1) def test_ticket7872(self): # Another variation on the disjunctive filtering theme. # For the purposes of this regression test, it's important that there is no # Join object related to the LeafA we create. LeafA.objects.create(data='first') self.assertQuerysetEqual(LeafA.objects.all(), ['<LeafA: first>']) self.assertQuerysetEqual( LeafA.objects.filter(Q(data='first') | Q(join__b__data='second')), ['<LeafA: first>'] ) def test_ticket8283(self): # Checking that applying filters after a disjunction works correctly. self.assertQuerysetEqual( (ExtraInfo.objects.filter(note=self.n1) | ExtraInfo.objects.filter(info='e2')).filter(note=self.n1), ['<ExtraInfo: e1>'] ) self.assertQuerysetEqual( (ExtraInfo.objects.filter(info='e2') | ExtraInfo.objects.filter(note=self.n1)).filter(note=self.n1), ['<ExtraInfo: e1>'] ) class Queries6Tests(TestCase): @classmethod def setUpTestData(cls): generic = NamedCategory.objects.create(name="Generic") cls.t1 = Tag.objects.create(name='t1', category=generic) cls.t2 = Tag.objects.create(name='t2', parent=cls.t1, category=generic) cls.t3 = Tag.objects.create(name='t3', parent=cls.t1) cls.t4 = Tag.objects.create(name='t4', parent=cls.t3) cls.t5 = Tag.objects.create(name='t5', parent=cls.t3) n1 = Note.objects.create(note='n1', misc='foo', id=1) ann1 = Annotation.objects.create(name='a1', tag=cls.t1) ann1.notes.add(n1) Annotation.objects.create(name='a2', tag=cls.t4) def test_parallel_iterators(self): # Parallel iterators work. qs = Tag.objects.all() i1, i2 = iter(qs), iter(qs) self.assertEqual(repr(next(i1)), '<Tag: t1>') self.assertEqual(repr(next(i1)), '<Tag: t2>') self.assertEqual(repr(next(i2)), '<Tag: t1>') self.assertEqual(repr(next(i2)), '<Tag: t2>') self.assertEqual(repr(next(i2)), '<Tag: t3>') self.assertEqual(repr(next(i1)), '<Tag: t3>') qs = X.objects.all() self.assertFalse(qs) self.assertFalse(qs) def test_nested_queries_sql(self): # Nested queries should not evaluate the inner query as part of constructing the # SQL (so we should see a nested query here, indicated by two "SELECT" calls). qs = Annotation.objects.filter(notes__in=Note.objects.filter(note="xyzzy")) self.assertEqual( qs.query.get_compiler(qs.db).as_sql()[0].count('SELECT'), 2 ) def test_tickets_8921_9188(self): # Incorrect SQL was being generated for certain types of exclude() # queries that crossed multi-valued relations (#8921, #9188 and some # preemptively discovered cases). self.assertQuerysetEqual( PointerA.objects.filter(connection__pointerb__id=1), [] ) self.assertQuerysetEqual( PointerA.objects.exclude(connection__pointerb__id=1), [] ) self.assertQuerysetEqual( Tag.objects.exclude(children=None), ['<Tag: t1>', '<Tag: t3>'] ) # This example is tricky because the parent could be NULL, so only checking # parents with annotations omits some results (tag t1, in this case). self.assertQuerysetEqual( Tag.objects.exclude(parent__annotation__name="a1"), ['<Tag: t1>', '<Tag: t4>', '<Tag: t5>'] ) # The annotation->tag link is single values and tag->children links is # multi-valued. So we have to split the exclude filter in the middle # and then optimize the inner query without losing results. self.assertQuerysetEqual( Annotation.objects.exclude(tag__children__name="t2"), ['<Annotation: a2>'] ) # Nested queries are possible (although should be used with care, since # they have performance problems on backends like MySQL. self.assertQuerysetEqual( Annotation.objects.filter(notes__in=Note.objects.filter(note="n1")), ['<Annotation: a1>'] ) def test_ticket3739(self): # The all() method on querysets returns a copy of the queryset. q1 = Tag.objects.order_by('name') self.assertIsNot(q1, q1.all()) def test_ticket_11320(self): qs = Tag.objects.exclude(category=None).exclude(category__name='foo') self.assertEqual(str(qs.query).count(' INNER JOIN '), 1) def test_distinct_ordered_sliced_subquery_aggregation(self): self.assertEqual(Tag.objects.distinct().order_by('category__name')[:3].count(), 3) def test_multiple_columns_with_the_same_name_slice(self): self.assertEqual( list(Tag.objects.order_by('name').values_list('name', 'category__name')[:2]), [('t1', 'Generic'), ('t2', 'Generic')], ) self.assertSequenceEqual( Tag.objects.order_by('name').select_related('category')[:2], [self.t1, self.t2], ) self.assertEqual( list(Tag.objects.order_by('-name').values_list('name', 'parent__name')[:2]), [('t5', 't3'), ('t4', 't3')], ) self.assertSequenceEqual( Tag.objects.order_by('-name').select_related('parent')[:2], [self.t5, self.t4], ) class RawQueriesTests(TestCase): def setUp(self): Note.objects.create(note='n1', misc='foo', id=1) def test_ticket14729(self): # Test representation of raw query with one or few parameters passed as list query = "SELECT * FROM queries_note WHERE note = %s" params = ['n1'] qs = Note.objects.raw(query, params=params) self.assertEqual(repr(qs), "<RawQuerySet: SELECT * FROM queries_note WHERE note = n1>") query = "SELECT * FROM queries_note WHERE note = %s and misc = %s" params = ['n1', 'foo'] qs = Note.objects.raw(query, params=params) self.assertEqual(repr(qs), "<RawQuerySet: SELECT * FROM queries_note WHERE note = n1 and misc = foo>") class GeneratorExpressionTests(SimpleTestCase): def test_ticket10432(self): # Using an empty iterator as the rvalue for an "__in" # lookup is legal. self.assertCountEqual(Note.objects.filter(pk__in=iter(())), []) class ComparisonTests(TestCase): def setUp(self): self.n1 = Note.objects.create(note='n1', misc='foo', id=1) e1 = ExtraInfo.objects.create(info='e1', note=self.n1) self.a2 = Author.objects.create(name='a2', num=2002, extra=e1) def test_ticket8597(self): # Regression tests for case-insensitive comparisons Item.objects.create(name="a_b", created=datetime.datetime.now(), creator=self.a2, note=self.n1) Item.objects.create(name="x%y", created=datetime.datetime.now(), creator=self.a2, note=self.n1) self.assertQuerysetEqual( Item.objects.filter(name__iexact="A_b"), ['<Item: a_b>'] ) self.assertQuerysetEqual( Item.objects.filter(name__iexact="x%Y"), ['<Item: x%y>'] ) self.assertQuerysetEqual( Item.objects.filter(name__istartswith="A_b"), ['<Item: a_b>'] ) self.assertQuerysetEqual( Item.objects.filter(name__iendswith="A_b"), ['<Item: a_b>'] ) class ExistsSql(TestCase): def test_exists(self): with CaptureQueriesContext(connection) as captured_queries: self.assertFalse(Tag.objects.exists()) # Ok - so the exist query worked - but did it include too many columns? self.assertEqual(len(captured_queries), 1) qstr = captured_queries[0]['sql'] id, name = connection.ops.quote_name('id'), connection.ops.quote_name('name') self.assertNotIn(id, qstr) self.assertNotIn(name, qstr) def test_ticket_18414(self): Article.objects.create(name='one', created=datetime.datetime.now()) Article.objects.create(name='one', created=datetime.datetime.now()) Article.objects.create(name='two', created=datetime.datetime.now()) self.assertTrue(Article.objects.exists()) self.assertTrue(Article.objects.distinct().exists()) self.assertTrue(Article.objects.distinct()[1:3].exists()) self.assertFalse(Article.objects.distinct()[1:1].exists()) @skipUnlessDBFeature('can_distinct_on_fields') def test_ticket_18414_distinct_on(self): Article.objects.create(name='one', created=datetime.datetime.now()) Article.objects.create(name='one', created=datetime.datetime.now()) Article.objects.create(name='two', created=datetime.datetime.now()) self.assertTrue(Article.objects.distinct('name').exists()) self.assertTrue(Article.objects.distinct('name')[1:2].exists()) self.assertFalse(Article.objects.distinct('name')[2:3].exists()) class QuerysetOrderedTests(unittest.TestCase): """ Tests for the Queryset.ordered attribute. """ def test_no_default_or_explicit_ordering(self): self.assertIs(Annotation.objects.all().ordered, False) def test_cleared_default_ordering(self): self.assertIs(Tag.objects.all().ordered, True) self.assertIs(Tag.objects.all().order_by().ordered, False) def test_explicit_ordering(self): self.assertIs(Annotation.objects.all().order_by('id').ordered, True) def test_empty_queryset(self): self.assertIs(Annotation.objects.none().ordered, True) def test_order_by_extra(self): self.assertIs(Annotation.objects.all().extra(order_by=['id']).ordered, True) def test_annotated_ordering(self): qs = Annotation.objects.annotate(num_notes=Count('notes')) self.assertIs(qs.ordered, False) self.assertIs(qs.order_by('num_notes').ordered, True) @skipUnlessDBFeature('allow_sliced_subqueries_with_in') class SubqueryTests(TestCase): @classmethod def setUpTestData(cls): NamedCategory.objects.create(id=1, name='first') NamedCategory.objects.create(id=2, name='second') NamedCategory.objects.create(id=3, name='third') NamedCategory.objects.create(id=4, name='fourth') def test_ordered_subselect(self): "Subselects honor any manual ordering" query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:2]) self.assertEqual(set(query.values_list('id', flat=True)), {3, 4}) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[:2]) self.assertEqual(set(query.values_list('id', flat=True)), {3, 4}) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:2]) self.assertEqual(set(query.values_list('id', flat=True)), {3}) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[2:]) self.assertEqual(set(query.values_list('id', flat=True)), {1, 2}) def test_slice_subquery_and_query(self): """ Slice a query that has a sliced subquery """ query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:2])[0:2] self.assertEqual({x.id for x in query}, {3, 4}) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:3])[1:3] self.assertEqual({x.id for x in query}, {3}) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[2:])[1:] self.assertEqual({x.id for x in query}, {2}) def test_related_sliced_subquery(self): """ Related objects constraints can safely contain sliced subqueries. refs #22434 """ generic = NamedCategory.objects.create(id=5, name="Generic") t1 = Tag.objects.create(name='t1', category=generic) t2 = Tag.objects.create(name='t2', category=generic) ManagedModel.objects.create(data='mm1', tag=t1, public=True) mm2 = ManagedModel.objects.create(data='mm2', tag=t2, public=True) query = ManagedModel.normal_manager.filter( tag__in=Tag.objects.order_by('-id')[:1] ) self.assertEqual({x.id for x in query}, {mm2.id}) def test_sliced_delete(self): "Delete queries can safely contain sliced subqueries" DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:1]).delete() self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), {1, 2, 3}) DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:2]).delete() self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), {1, 3}) DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:]).delete() self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), {3}) def test_distinct_ordered_sliced_subquery(self): # Implicit values('id'). self.assertSequenceEqual( NamedCategory.objects.filter( id__in=NamedCategory.objects.distinct().order_by('name')[0:2], ).order_by('name').values_list('name', flat=True), ['first', 'fourth'] ) # Explicit values('id'). self.assertSequenceEqual( NamedCategory.objects.filter( id__in=NamedCategory.objects.distinct().order_by('-name').values('id')[0:2], ).order_by('name').values_list('name', flat=True), ['second', 'third'] ) # Annotated value. self.assertSequenceEqual( DumbCategory.objects.filter( id__in=DumbCategory.objects.annotate( double_id=F('id') * 2 ).order_by('id').distinct().values('double_id')[0:2], ).order_by('id').values_list('id', flat=True), [2, 4] ) @skipUnlessDBFeature('allow_sliced_subqueries_with_in') class QuerySetBitwiseOperationTests(TestCase): @classmethod def setUpTestData(cls): school = School.objects.create() cls.room_1 = Classroom.objects.create(school=school, has_blackboard=False, name='Room 1') cls.room_2 = Classroom.objects.create(school=school, has_blackboard=True, name='Room 2') cls.room_3 = Classroom.objects.create(school=school, has_blackboard=True, name='Room 3') cls.room_4 = Classroom.objects.create(school=school, has_blackboard=False, name='Room 4') def test_or_with_rhs_slice(self): qs1 = Classroom.objects.filter(has_blackboard=True) qs2 = Classroom.objects.filter(has_blackboard=False)[:1] self.assertCountEqual(qs1 | qs2, [self.room_1, self.room_2, self.room_3]) def test_or_with_lhs_slice(self): qs1 = Classroom.objects.filter(has_blackboard=True)[:1] qs2 = Classroom.objects.filter(has_blackboard=False) self.assertCountEqual(qs1 | qs2, [self.room_1, self.room_2, self.room_4]) def test_or_with_both_slice(self): qs1 = Classroom.objects.filter(has_blackboard=False)[:1] qs2 = Classroom.objects.filter(has_blackboard=True)[:1] self.assertCountEqual(qs1 | qs2, [self.room_1, self.room_2]) def test_or_with_both_slice_and_ordering(self): qs1 = Classroom.objects.filter(has_blackboard=False).order_by('-pk')[:1] qs2 = Classroom.objects.filter(has_blackboard=True).order_by('-name')[:1] self.assertCountEqual(qs1 | qs2, [self.room_3, self.room_4]) class CloneTests(TestCase): def test_evaluated_queryset_as_argument(self): "#13227 -- If a queryset is already evaluated, it can still be used as a query arg" n = Note(note='Test1', misc='misc') n.save() e = ExtraInfo(info='good', note=n) e.save() n_list = Note.objects.all() # Evaluate the Note queryset, populating the query cache list(n_list) # Use the note queryset in a query, and evaluate # that query in a way that involves cloning. self.assertEqual(ExtraInfo.objects.filter(note__in=n_list)[0].info, 'good') def test_no_model_options_cloning(self): """ Cloning a queryset does not get out of hand. While complete testing is impossible, this is a sanity check against invalid use of deepcopy. refs #16759. """ opts_class = type(Note._meta) note_deepcopy = getattr(opts_class, "__deepcopy__", None) opts_class.__deepcopy__ = lambda obj, memo: self.fail("Model options shouldn't be cloned.") try: Note.objects.filter(pk__lte=F('pk') + 1).all() finally: if note_deepcopy is None: delattr(opts_class, "__deepcopy__") else: opts_class.__deepcopy__ = note_deepcopy def test_no_fields_cloning(self): """ Cloning a queryset does not get out of hand. While complete testing is impossible, this is a sanity check against invalid use of deepcopy. refs #16759. """ opts_class = type(Note._meta.get_field("misc")) note_deepcopy = getattr(opts_class, "__deepcopy__", None) opts_class.__deepcopy__ = lambda obj, memo: self.fail("Model fields shouldn't be cloned") try: Note.objects.filter(note=F('misc')).all() finally: if note_deepcopy is None: delattr(opts_class, "__deepcopy__") else: opts_class.__deepcopy__ = note_deepcopy class EmptyQuerySetTests(SimpleTestCase): def test_emptyqueryset_values(self): # #14366 -- Calling .values() on an empty QuerySet and then cloning # that should not cause an error self.assertCountEqual(Number.objects.none().values('num').order_by('num'), []) def test_values_subquery(self): self.assertCountEqual(Number.objects.filter(pk__in=Number.objects.none().values('pk')), []) self.assertCountEqual(Number.objects.filter(pk__in=Number.objects.none().values_list('pk')), []) def test_ticket_19151(self): # #19151 -- Calling .values() or .values_list() on an empty QuerySet # should return an empty QuerySet and not cause an error. q = Author.objects.none() self.assertCountEqual(q.values(), []) self.assertCountEqual(q.values_list(), []) class ValuesQuerysetTests(TestCase): @classmethod def setUpTestData(cls): Number.objects.create(num=72) def test_flat_values_list(self): qs = Number.objects.values_list("num") qs = qs.values_list("num", flat=True) self.assertSequenceEqual(qs, [72]) def test_extra_values(self): # testing for ticket 14930 issues qs = Number.objects.extra(select={'value_plus_x': 'num+%s', 'value_minus_x': 'num-%s'}, select_params=(1, 2)) qs = qs.order_by('value_minus_x') qs = qs.values('num') self.assertSequenceEqual(qs, [{'num': 72}]) def test_extra_values_order_twice(self): # testing for ticket 14930 issues qs = Number.objects.extra(select={'value_plus_one': 'num+1', 'value_minus_one': 'num-1'}) qs = qs.order_by('value_minus_one').order_by('value_plus_one') qs = qs.values('num') self.assertSequenceEqual(qs, [{'num': 72}]) def test_extra_values_order_multiple(self): # Postgres doesn't allow constants in order by, so check for that. qs = Number.objects.extra(select={ 'value_plus_one': 'num+1', 'value_minus_one': 'num-1', 'constant_value': '1' }) qs = qs.order_by('value_plus_one', 'value_minus_one', 'constant_value') qs = qs.values('num') self.assertSequenceEqual(qs, [{'num': 72}]) def test_extra_values_order_in_extra(self): # testing for ticket 14930 issues qs = Number.objects.extra( select={'value_plus_one': 'num+1', 'value_minus_one': 'num-1'}, order_by=['value_minus_one'], ) qs = qs.values('num') def test_extra_select_params_values_order_in_extra(self): # testing for 23259 issue qs = Number.objects.extra( select={'value_plus_x': 'num+%s'}, select_params=[1], order_by=['value_plus_x'], ) qs = qs.filter(num=72) qs = qs.values('num') self.assertSequenceEqual(qs, [{'num': 72}]) def test_extra_multiple_select_params_values_order_by(self): # testing for 23259 issue qs = Number.objects.extra(select={'value_plus_x': 'num+%s', 'value_minus_x': 'num-%s'}, select_params=(72, 72)) qs = qs.order_by('value_minus_x') qs = qs.filter(num=1) qs = qs.values('num') self.assertSequenceEqual(qs, []) def test_extra_values_list(self): # testing for ticket 14930 issues qs = Number.objects.extra(select={'value_plus_one': 'num+1'}) qs = qs.order_by('value_plus_one') qs = qs.values_list('num') self.assertSequenceEqual(qs, [(72,)]) def test_flat_extra_values_list(self): # testing for ticket 14930 issues qs = Number.objects.extra(select={'value_plus_one': 'num+1'}) qs = qs.order_by('value_plus_one') qs = qs.values_list('num', flat=True) self.assertSequenceEqual(qs, [72]) def test_field_error_values_list(self): # see #23443 msg = "Cannot resolve keyword %r into field. Join on 'name' not permitted." % 'foo' with self.assertRaisesMessage(FieldError, msg): Tag.objects.values_list('name__foo') def test_named_values_list_flat(self): msg = "'flat' and 'named' can't be used together." with self.assertRaisesMessage(TypeError, msg): Number.objects.values_list('num', flat=True, named=True) def test_named_values_list_bad_field_name(self): msg = "Type names and field names must be valid identifiers: '1'" with self.assertRaisesMessage(ValueError, msg): Number.objects.extra(select={'1': 'num+1'}).values_list('1', named=True).first() def test_named_values_list_with_fields(self): qs = Number.objects.extra(select={'num2': 'num+1'}).annotate(Count('id')) values = qs.values_list('num', 'num2', named=True).first() self.assertEqual(type(values).__name__, 'Row') self.assertEqual(values._fields, ('num', 'num2')) self.assertEqual(values.num, 72) self.assertEqual(values.num2, 73) def test_named_values_list_without_fields(self): qs = Number.objects.extra(select={'num2': 'num+1'}).annotate(Count('id')) values = qs.values_list(named=True).first() self.assertEqual(type(values).__name__, 'Row') self.assertEqual(values._fields, ('num2', 'id', 'num', 'other_num', 'id__count')) self.assertEqual(values.num, 72) self.assertEqual(values.num2, 73) self.assertEqual(values.id__count, 1) def test_named_values_list_expression_with_default_alias(self): expr = Count('id') values = Number.objects.annotate(id__count1=expr).values_list(expr, 'id__count1', named=True).first() self.assertEqual(values._fields, ('id__count2', 'id__count1')) def test_named_values_list_expression(self): expr = F('num') + 1 qs = Number.objects.annotate(combinedexpression1=expr).values_list(expr, 'combinedexpression1', named=True) values = qs.first() self.assertEqual(values._fields, ('combinedexpression2', 'combinedexpression1')) class QuerySetSupportsPythonIdioms(TestCase): @classmethod def setUpTestData(cls): some_date = datetime.datetime(2014, 5, 16, 12, 1) for i in range(1, 8): Article.objects.create( name="Article {}".format(i), created=some_date) def get_ordered_articles(self): return Article.objects.all().order_by('name') def test_can_get_items_using_index_and_slice_notation(self): self.assertEqual(self.get_ordered_articles()[0].name, 'Article 1') self.assertQuerysetEqual( self.get_ordered_articles()[1:3], ["<Article: Article 2>", "<Article: Article 3>"] ) def test_slicing_with_steps_can_be_used(self): self.assertQuerysetEqual( self.get_ordered_articles()[::2], [ "<Article: Article 1>", "<Article: Article 3>", "<Article: Article 5>", "<Article: Article 7>" ] ) def test_slicing_without_step_is_lazy(self): with self.assertNumQueries(0): self.get_ordered_articles()[0:5] def test_slicing_with_tests_is_not_lazy(self): with self.assertNumQueries(1): self.get_ordered_articles()[0:5:3] def test_slicing_can_slice_again_after_slicing(self): self.assertQuerysetEqual( self.get_ordered_articles()[0:5][0:2], ["<Article: Article 1>", "<Article: Article 2>"] ) self.assertQuerysetEqual(self.get_ordered_articles()[0:5][4:], ["<Article: Article 5>"]) self.assertQuerysetEqual(self.get_ordered_articles()[0:5][5:], []) # Some more tests! self.assertQuerysetEqual( self.get_ordered_articles()[2:][0:2], ["<Article: Article 3>", "<Article: Article 4>"] ) self.assertQuerysetEqual( self.get_ordered_articles()[2:][:2], ["<Article: Article 3>", "<Article: Article 4>"] ) self.assertQuerysetEqual(self.get_ordered_articles()[2:][2:3], ["<Article: Article 5>"]) # Using an offset without a limit is also possible. self.assertQuerysetEqual( self.get_ordered_articles()[5:], ["<Article: Article 6>", "<Article: Article 7>"] ) def test_slicing_cannot_filter_queryset_once_sliced(self): with self.assertRaisesMessage(AssertionError, "Cannot filter a query once a slice has been taken."): Article.objects.all()[0:5].filter(id=1) def test_slicing_cannot_reorder_queryset_once_sliced(self): with self.assertRaisesMessage(AssertionError, "Cannot reorder a query once a slice has been taken."): Article.objects.all()[0:5].order_by('id') def test_slicing_cannot_combine_queries_once_sliced(self): with self.assertRaisesMessage(AssertionError, "Cannot combine queries once a slice has been taken."): Article.objects.all()[0:1] & Article.objects.all()[4:5] def test_slicing_negative_indexing_not_supported_for_single_element(self): """hint: inverting your ordering might do what you need""" with self.assertRaisesMessage(AssertionError, "Negative indexing is not supported."): Article.objects.all()[-1] def test_slicing_negative_indexing_not_supported_for_range(self): """hint: inverting your ordering might do what you need""" with self.assertRaisesMessage(AssertionError, "Negative indexing is not supported."): Article.objects.all()[0:-5] def test_invalid_index(self): msg = 'QuerySet indices must be integers or slices, not str.' with self.assertRaisesMessage(TypeError, msg): Article.objects.all()['foo'] def test_can_get_number_of_items_in_queryset_using_standard_len(self): self.assertEqual(len(Article.objects.filter(name__exact='Article 1')), 1) def test_can_combine_queries_using_and_and_or_operators(self): s1 = Article.objects.filter(name__exact='Article 1') s2 = Article.objects.filter(name__exact='Article 2') self.assertQuerysetEqual( (s1 | s2).order_by('name'), ["<Article: Article 1>", "<Article: Article 2>"] ) self.assertQuerysetEqual(s1 & s2, []) class WeirdQuerysetSlicingTests(TestCase): @classmethod def setUpTestData(cls): Number.objects.create(num=1) Number.objects.create(num=2) Article.objects.create(name='one', created=datetime.datetime.now()) Article.objects.create(name='two', created=datetime.datetime.now()) Article.objects.create(name='three', created=datetime.datetime.now()) Article.objects.create(name='four', created=datetime.datetime.now()) food = Food.objects.create(name='spam') Eaten.objects.create(meal='spam with eggs', food=food) def test_tickets_7698_10202(self): # People like to slice with '0' as the high-water mark. self.assertQuerysetEqual(Article.objects.all()[0:0], []) self.assertQuerysetEqual(Article.objects.all()[0:0][:10], []) self.assertEqual(Article.objects.all()[:0].count(), 0) with self.assertRaisesMessage(TypeError, 'Cannot reverse a query once a slice has been taken.'): Article.objects.all()[:0].latest('created') def test_empty_resultset_sql(self): # ticket #12192 self.assertNumQueries(0, lambda: list(Number.objects.all()[1:1])) def test_empty_sliced_subquery(self): self.assertEqual(Eaten.objects.filter(food__in=Food.objects.all()[0:0]).count(), 0) def test_empty_sliced_subquery_exclude(self): self.assertEqual(Eaten.objects.exclude(food__in=Food.objects.all()[0:0]).count(), 1) def test_zero_length_values_slicing(self): n = 42 with self.assertNumQueries(0): self.assertQuerysetEqual(Article.objects.values()[n:n], []) self.assertQuerysetEqual(Article.objects.values_list()[n:n], []) class EscapingTests(TestCase): def test_ticket_7302(self): # Reserved names are appropriately escaped ReservedName.objects.create(name='a', order=42) ReservedName.objects.create(name='b', order=37) self.assertQuerysetEqual( ReservedName.objects.all().order_by('order'), ['<ReservedName: b>', '<ReservedName: a>'] ) self.assertQuerysetEqual( ReservedName.objects.extra(select={'stuff': 'name'}, order_by=('order', 'stuff')), ['<ReservedName: b>', '<ReservedName: a>'] ) class ToFieldTests(TestCase): def test_in_query(self): apple = Food.objects.create(name="apple") pear = Food.objects.create(name="pear") lunch = Eaten.objects.create(food=apple, meal="lunch") dinner = Eaten.objects.create(food=pear, meal="dinner") self.assertEqual( set(Eaten.objects.filter(food__in=[apple, pear])), {lunch, dinner}, ) def test_in_subquery(self): apple = Food.objects.create(name="apple") lunch = Eaten.objects.create(food=apple, meal="lunch") self.assertEqual( set(Eaten.objects.filter(food__in=Food.objects.filter(name='apple'))), {lunch} ) self.assertEqual( set(Eaten.objects.filter(food__in=Food.objects.filter(name='apple').values('eaten__meal'))), set() ) self.assertEqual( set(Food.objects.filter(eaten__in=Eaten.objects.filter(meal='lunch'))), {apple} ) def test_nested_in_subquery(self): extra = ExtraInfo.objects.create() author = Author.objects.create(num=42, extra=extra) report = Report.objects.create(creator=author) comment = ReportComment.objects.create(report=report) comments = ReportComment.objects.filter( report__in=Report.objects.filter( creator__in=extra.author_set.all(), ), ) self.assertSequenceEqual(comments, [comment]) def test_reverse_in(self): apple = Food.objects.create(name="apple") pear = Food.objects.create(name="pear") lunch_apple = Eaten.objects.create(food=apple, meal="lunch") lunch_pear = Eaten.objects.create(food=pear, meal="dinner") self.assertEqual( set(Food.objects.filter(eaten__in=[lunch_apple, lunch_pear])), {apple, pear} ) def test_single_object(self): apple = Food.objects.create(name="apple") lunch = Eaten.objects.create(food=apple, meal="lunch") dinner = Eaten.objects.create(food=apple, meal="dinner") self.assertEqual( set(Eaten.objects.filter(food=apple)), {lunch, dinner} ) def test_single_object_reverse(self): apple = Food.objects.create(name="apple") lunch = Eaten.objects.create(food=apple, meal="lunch") self.assertEqual( set(Food.objects.filter(eaten=lunch)), {apple} ) def test_recursive_fk(self): node1 = Node.objects.create(num=42) node2 = Node.objects.create(num=1, parent=node1) self.assertEqual( list(Node.objects.filter(parent=node1)), [node2] ) def test_recursive_fk_reverse(self): node1 = Node.objects.create(num=42) node2 = Node.objects.create(num=1, parent=node1) self.assertEqual( list(Node.objects.filter(node=node2)), [node1] ) class IsNullTests(TestCase): def test_primary_key(self): custom = CustomPk.objects.create(name='pk') null = Related.objects.create() notnull = Related.objects.create(custom=custom) self.assertSequenceEqual(Related.objects.filter(custom__isnull=False), [notnull]) self.assertSequenceEqual(Related.objects.filter(custom__isnull=True), [null]) def test_to_field(self): apple = Food.objects.create(name="apple") Eaten.objects.create(food=apple, meal="lunch") Eaten.objects.create(meal="lunch") self.assertQuerysetEqual( Eaten.objects.filter(food__isnull=False), ['<Eaten: apple at lunch>'] ) self.assertQuerysetEqual( Eaten.objects.filter(food__isnull=True), ['<Eaten: None at lunch>'] ) class ConditionalTests(TestCase): """Tests whose execution depend on different environment conditions like Python version or DB backend features""" @classmethod def setUpTestData(cls): generic = NamedCategory.objects.create(name="Generic") t1 = Tag.objects.create(name='t1', category=generic) Tag.objects.create(name='t2', parent=t1, category=generic) t3 = Tag.objects.create(name='t3', parent=t1) Tag.objects.create(name='t4', parent=t3) Tag.objects.create(name='t5', parent=t3) def test_infinite_loop(self): # If you're not careful, it's possible to introduce infinite loops via # default ordering on foreign keys in a cycle. We detect that. with self.assertRaisesMessage(FieldError, 'Infinite loop caused by ordering.'): list(LoopX.objects.all()) # Force queryset evaluation with list() with self.assertRaisesMessage(FieldError, 'Infinite loop caused by ordering.'): list(LoopZ.objects.all()) # Force queryset evaluation with list() # Note that this doesn't cause an infinite loop, since the default # ordering on the Tag model is empty (and thus defaults to using "id" # for the related field). self.assertEqual(len(Tag.objects.order_by('parent')), 5) # ... but you can still order in a non-recursive fashion among linked # fields (the previous test failed because the default ordering was # recursive). self.assertQuerysetEqual( LoopX.objects.all().order_by('y__x__y__x__id'), [] ) # When grouping without specifying ordering, we add an explicit "ORDER BY NULL" # portion in MySQL to prevent unnecessary sorting. @skipUnlessDBFeature('requires_explicit_null_ordering_when_grouping') def test_null_ordering_added(self): query = Tag.objects.values_list('parent_id', flat=True).order_by().query query.group_by = ['parent_id'] sql = query.get_compiler(DEFAULT_DB_ALIAS).as_sql()[0] fragment = "ORDER BY " pos = sql.find(fragment) self.assertEqual(sql.find(fragment, pos + 1), -1) self.assertEqual(sql.find("NULL", pos + len(fragment)), pos + len(fragment)) def test_in_list_limit(self): # The "in" lookup works with lists of 1000 items or more. # The numbers amount is picked to force three different IN batches # for Oracle, yet to be less than 2100 parameter limit for MSSQL. numbers = list(range(2050)) max_query_params = connection.features.max_query_params if max_query_params is None or max_query_params >= len(numbers): Number.objects.bulk_create(Number(num=num) for num in numbers) for number in [1000, 1001, 2000, len(numbers)]: with self.subTest(number=number): self.assertEqual(Number.objects.filter(num__in=numbers[:number]).count(), number) class UnionTests(unittest.TestCase): """ Tests for the union of two querysets. Bug #12252. """ @classmethod def setUpTestData(cls): objectas = [] objectbs = [] objectcs = [] a_info = ['one', 'two', 'three'] for name in a_info: o = ObjectA(name=name) o.save() objectas.append(o) b_info = [('un', 1, objectas[0]), ('deux', 2, objectas[0]), ('trois', 3, objectas[2])] for name, number, objecta in b_info: o = ObjectB(name=name, num=number, objecta=objecta) o.save() objectbs.append(o) c_info = [('ein', objectas[2], objectbs[2]), ('zwei', objectas[1], objectbs[1])] for name, objecta, objectb in c_info: o = ObjectC(name=name, objecta=objecta, objectb=objectb) o.save() objectcs.append(o) def check_union(self, model, Q1, Q2): filter = model.objects.filter self.assertEqual(set(filter(Q1) | filter(Q2)), set(filter(Q1 | Q2))) self.assertEqual(set(filter(Q2) | filter(Q1)), set(filter(Q1 | Q2))) def test_A_AB(self): Q1 = Q(name='two') Q2 = Q(objectb__name='deux') self.check_union(ObjectA, Q1, Q2) def test_A_AB2(self): Q1 = Q(name='two') Q2 = Q(objectb__name='deux', objectb__num=2) self.check_union(ObjectA, Q1, Q2) def test_AB_ACB(self): Q1 = Q(objectb__name='deux') Q2 = Q(objectc__objectb__name='deux') self.check_union(ObjectA, Q1, Q2) def test_BAB_BAC(self): Q1 = Q(objecta__objectb__name='deux') Q2 = Q(objecta__objectc__name='ein') self.check_union(ObjectB, Q1, Q2) def test_BAB_BACB(self): Q1 = Q(objecta__objectb__name='deux') Q2 = Q(objecta__objectc__objectb__name='trois') self.check_union(ObjectB, Q1, Q2) def test_BA_BCA__BAB_BAC_BCA(self): Q1 = Q(objecta__name='one', objectc__objecta__name='two') Q2 = Q(objecta__objectc__name='ein', objectc__objecta__name='three', objecta__objectb__name='trois') self.check_union(ObjectB, Q1, Q2) class DefaultValuesInsertTest(TestCase): def test_no_extra_params(self): """ Can create an instance of a model with only the PK field (#17056)." """ DumbCategory.objects.create() class ExcludeTests(TestCase): @classmethod def setUpTestData(cls): f1 = Food.objects.create(name='apples') Food.objects.create(name='oranges') Eaten.objects.create(food=f1, meal='dinner') j1 = Job.objects.create(name='Manager') cls.r1 = Responsibility.objects.create(description='Playing golf') j2 = Job.objects.create(name='Programmer') r2 = Responsibility.objects.create(description='Programming') JobResponsibilities.objects.create(job=j1, responsibility=cls.r1) JobResponsibilities.objects.create(job=j2, responsibility=r2) def test_to_field(self): self.assertQuerysetEqual( Food.objects.exclude(eaten__meal='dinner'), ['<Food: oranges>']) self.assertQuerysetEqual( Job.objects.exclude(responsibilities__description='Playing golf'), ['<Job: Programmer>']) self.assertQuerysetEqual( Responsibility.objects.exclude(jobs__name='Manager'), ['<Responsibility: Programming>']) def test_ticket14511(self): alex = Person.objects.get_or_create(name='Alex')[0] jane = Person.objects.get_or_create(name='Jane')[0] oracle = Company.objects.get_or_create(name='Oracle')[0] google = Company.objects.get_or_create(name='Google')[0] microsoft = Company.objects.get_or_create(name='Microsoft')[0] intel = Company.objects.get_or_create(name='Intel')[0] def employ(employer, employee, title): Employment.objects.get_or_create(employee=employee, employer=employer, title=title) employ(oracle, alex, 'Engineer') employ(oracle, alex, 'Developer') employ(google, alex, 'Engineer') employ(google, alex, 'Manager') employ(microsoft, alex, 'Manager') employ(intel, alex, 'Manager') employ(microsoft, jane, 'Developer') employ(intel, jane, 'Manager') alex_tech_employers = alex.employers.filter( employment__title__in=('Engineer', 'Developer')).distinct().order_by('name') self.assertSequenceEqual(alex_tech_employers, [google, oracle]) alex_nontech_employers = alex.employers.exclude( employment__title__in=('Engineer', 'Developer')).distinct().order_by('name') self.assertSequenceEqual(alex_nontech_employers, [google, intel, microsoft]) def test_exclude_reverse_fk_field_ref(self): tag = Tag.objects.create() Note.objects.create(tag=tag, note='note') annotation = Annotation.objects.create(name='annotation', tag=tag) self.assertEqual(Annotation.objects.exclude(tag__note__note=F('name')).get(), annotation) def test_exclude_with_circular_fk_relation(self): self.assertEqual(ObjectB.objects.exclude(objecta__objectb__name=F('name')).count(), 0) def test_subquery_exclude_outerref(self): qs = JobResponsibilities.objects.filter( Exists(Responsibility.objects.exclude(jobs=OuterRef('job'))), ) self.assertTrue(qs.exists()) self.r1.delete() self.assertFalse(qs.exists()) class ExcludeTest17600(TestCase): """ Some regressiontests for ticket #17600. Some of these likely duplicate other existing tests. """ @classmethod def setUpTestData(cls): # Create a few Orders. cls.o1 = Order.objects.create(pk=1) cls.o2 = Order.objects.create(pk=2) cls.o3 = Order.objects.create(pk=3) # Create some OrderItems for the first order with homogeneous # status_id values cls.oi1 = OrderItem.objects.create(order=cls.o1, status=1) cls.oi2 = OrderItem.objects.create(order=cls.o1, status=1) cls.oi3 = OrderItem.objects.create(order=cls.o1, status=1) # Create some OrderItems for the second order with heterogeneous # status_id values cls.oi4 = OrderItem.objects.create(order=cls.o2, status=1) cls.oi5 = OrderItem.objects.create(order=cls.o2, status=2) cls.oi6 = OrderItem.objects.create(order=cls.o2, status=3) # Create some OrderItems for the second order with heterogeneous # status_id values cls.oi7 = OrderItem.objects.create(order=cls.o3, status=2) cls.oi8 = OrderItem.objects.create(order=cls.o3, status=3) cls.oi9 = OrderItem.objects.create(order=cls.o3, status=4) def test_exclude_plain(self): """ This should exclude Orders which have some items with status 1 """ self.assertQuerysetEqual( Order.objects.exclude(items__status=1), ['<Order: 3>']) def test_exclude_plain_distinct(self): """ This should exclude Orders which have some items with status 1 """ self.assertQuerysetEqual( Order.objects.exclude(items__status=1).distinct(), ['<Order: 3>']) def test_exclude_with_q_object_distinct(self): """ This should exclude Orders which have some items with status 1 """ self.assertQuerysetEqual( Order.objects.exclude(Q(items__status=1)).distinct(), ['<Order: 3>']) def test_exclude_with_q_object_no_distinct(self): """ This should exclude Orders which have some items with status 1 """ self.assertQuerysetEqual( Order.objects.exclude(Q(items__status=1)), ['<Order: 3>']) def test_exclude_with_q_is_equal_to_plain_exclude(self): """ Using exclude(condition) and exclude(Q(condition)) should yield the same QuerySet """ self.assertEqual( list(Order.objects.exclude(items__status=1).distinct()), list(Order.objects.exclude(Q(items__status=1)).distinct())) def test_exclude_with_q_is_equal_to_plain_exclude_variation(self): """ Using exclude(condition) and exclude(Q(condition)) should yield the same QuerySet """ self.assertEqual( list(Order.objects.exclude(items__status=1)), list(Order.objects.exclude(Q(items__status=1)).distinct())) @unittest.expectedFailure def test_only_orders_with_all_items_having_status_1(self): """ This should only return orders having ALL items set to status 1, or those items not having any orders at all. The correct way to write this query in SQL seems to be using two nested subqueries. """ self.assertQuerysetEqual( Order.objects.exclude(~Q(items__status=1)).distinct(), ['<Order: 1>']) class Exclude15786(TestCase): """Regression test for #15786""" def test_ticket15786(self): c1 = SimpleCategory.objects.create(name='c1') c2 = SimpleCategory.objects.create(name='c2') OneToOneCategory.objects.create(category=c1) OneToOneCategory.objects.create(category=c2) rel = CategoryRelationship.objects.create(first=c1, second=c2) self.assertEqual( CategoryRelationship.objects.exclude( first__onetoonecategory=F('second__onetoonecategory') ).get(), rel ) class NullInExcludeTest(TestCase): @classmethod def setUpTestData(cls): NullableName.objects.create(name='i1') NullableName.objects.create() def test_null_in_exclude_qs(self): none_val = '' if connection.features.interprets_empty_strings_as_nulls else None self.assertQuerysetEqual( NullableName.objects.exclude(name__in=[]), ['i1', none_val], attrgetter('name')) self.assertQuerysetEqual( NullableName.objects.exclude(name__in=['i1']), [none_val], attrgetter('name')) self.assertQuerysetEqual( NullableName.objects.exclude(name__in=['i3']), ['i1', none_val], attrgetter('name')) inner_qs = NullableName.objects.filter(name='i1').values_list('name') self.assertQuerysetEqual( NullableName.objects.exclude(name__in=inner_qs), [none_val], attrgetter('name')) # The inner queryset wasn't executed - it should be turned # into subquery above self.assertIs(inner_qs._result_cache, None) @unittest.expectedFailure def test_col_not_in_list_containing_null(self): """ The following case is not handled properly because SQL's COL NOT IN (list containing null) handling is too weird to abstract away. """ self.assertQuerysetEqual( NullableName.objects.exclude(name__in=[None]), ['i1'], attrgetter('name')) def test_double_exclude(self): self.assertEqual( list(NullableName.objects.filter(~~Q(name='i1'))), list(NullableName.objects.filter(Q(name='i1')))) self.assertNotIn( 'IS NOT NULL', str(NullableName.objects.filter(~~Q(name='i1')).query)) class EmptyStringsAsNullTest(TestCase): """ Filtering on non-null character fields works as expected. The reason for these tests is that Oracle treats '' as NULL, and this can cause problems in query construction. Refs #17957. """ @classmethod def setUpTestData(cls): cls.nc = NamedCategory.objects.create(name='') def test_direct_exclude(self): self.assertQuerysetEqual( NamedCategory.objects.exclude(name__in=['nonexistent']), [self.nc.pk], attrgetter('pk') ) def test_joined_exclude(self): self.assertQuerysetEqual( DumbCategory.objects.exclude(namedcategory__name__in=['nonexistent']), [self.nc.pk], attrgetter('pk') ) def test_21001(self): foo = NamedCategory.objects.create(name='foo') self.assertQuerysetEqual( NamedCategory.objects.exclude(name=''), [foo.pk], attrgetter('pk') ) class ProxyQueryCleanupTest(TestCase): def test_evaluated_proxy_count(self): """ Generating the query string doesn't alter the query's state in irreversible ways. Refs #18248. """ ProxyCategory.objects.create() qs = ProxyCategory.objects.all() self.assertEqual(qs.count(), 1) str(qs.query) self.assertEqual(qs.count(), 1) class WhereNodeTest(SimpleTestCase): class DummyNode: def as_sql(self, compiler, connection): return 'dummy', [] class MockCompiler: def compile(self, node): return node.as_sql(self, connection) def __call__(self, name): return connection.ops.quote_name(name) def test_empty_full_handling_conjunction(self): compiler = WhereNodeTest.MockCompiler() w = WhereNode(children=[NothingNode()]) with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('', [])) w = WhereNode(children=[self.DummyNode(), self.DummyNode()]) self.assertEqual(w.as_sql(compiler, connection), ('(dummy AND dummy)', [])) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy AND dummy)', [])) w = WhereNode(children=[NothingNode(), self.DummyNode()]) with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('', [])) def test_empty_full_handling_disjunction(self): compiler = WhereNodeTest.MockCompiler() w = WhereNode(children=[NothingNode()], connector='OR') with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('', [])) w = WhereNode(children=[self.DummyNode(), self.DummyNode()], connector='OR') self.assertEqual(w.as_sql(compiler, connection), ('(dummy OR dummy)', [])) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy OR dummy)', [])) w = WhereNode(children=[NothingNode(), self.DummyNode()], connector='OR') self.assertEqual(w.as_sql(compiler, connection), ('dummy', [])) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy)', [])) def test_empty_nodes(self): compiler = WhereNodeTest.MockCompiler() empty_w = WhereNode() w = WhereNode(children=[empty_w, empty_w]) self.assertEqual(w.as_sql(compiler, connection), ('', [])) w.negate() with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) w.connector = 'OR' with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('', [])) w = WhereNode(children=[empty_w, NothingNode()], connector='OR') self.assertEqual(w.as_sql(compiler, connection), ('', [])) w = WhereNode(children=[empty_w, NothingNode()], connector='AND') with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) class QuerySetExceptionTests(SimpleTestCase): def test_iter_exceptions(self): qs = ExtraInfo.objects.only('author') msg = "'ManyToOneRel' object has no attribute 'attname'" with self.assertRaisesMessage(AttributeError, msg): list(qs) def test_invalid_qs_list(self): # Test for #19895 - second iteration over invalid queryset # raises errors. qs = Article.objects.order_by('invalid_column') msg = "Cannot resolve keyword 'invalid_column' into field." with self.assertRaisesMessage(FieldError, msg): list(qs) with self.assertRaisesMessage(FieldError, msg): list(qs) def test_invalid_order_by(self): msg = "Invalid order_by arguments: ['*']" with self.assertRaisesMessage(FieldError, msg): list(Article.objects.order_by('*')) def test_invalid_queryset_model(self): msg = 'Cannot use QuerySet for "Article": Use a QuerySet for "ExtraInfo".' with self.assertRaisesMessage(ValueError, msg): list(Author.objects.filter(extra=Article.objects.all())) class NullJoinPromotionOrTest(TestCase): @classmethod def setUpTestData(cls): cls.d1 = ModelD.objects.create(name='foo') d2 = ModelD.objects.create(name='bar') cls.a1 = ModelA.objects.create(name='a1', d=cls.d1) c = ModelC.objects.create(name='c') b = ModelB.objects.create(name='b', c=c) cls.a2 = ModelA.objects.create(name='a2', b=b, d=d2) def test_ticket_17886(self): # The first Q-object is generating the match, the rest of the filters # should not remove the match even if they do not match anything. The # problem here was that b__name generates a LOUTER JOIN, then # b__c__name generates join to c, which the ORM tried to promote but # failed as that join isn't nullable. q_obj = ( Q(d__name='foo') | Q(b__name='foo') | Q(b__c__name='foo') ) qset = ModelA.objects.filter(q_obj) self.assertEqual(list(qset), [self.a1]) # We generate one INNER JOIN to D. The join is direct and not nullable # so we can use INNER JOIN for it. However, we can NOT use INNER JOIN # for the b->c join, as a->b is nullable. self.assertEqual(str(qset.query).count('INNER JOIN'), 1) def test_isnull_filter_promotion(self): qs = ModelA.objects.filter(Q(b__name__isnull=True)) self.assertEqual(str(qs.query).count('LEFT OUTER'), 1) self.assertEqual(list(qs), [self.a1]) qs = ModelA.objects.filter(~Q(b__name__isnull=True)) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(list(qs), [self.a2]) qs = ModelA.objects.filter(~~Q(b__name__isnull=True)) self.assertEqual(str(qs.query).count('LEFT OUTER'), 1) self.assertEqual(list(qs), [self.a1]) qs = ModelA.objects.filter(Q(b__name__isnull=False)) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(list(qs), [self.a2]) qs = ModelA.objects.filter(~Q(b__name__isnull=False)) self.assertEqual(str(qs.query).count('LEFT OUTER'), 1) self.assertEqual(list(qs), [self.a1]) qs = ModelA.objects.filter(~~Q(b__name__isnull=False)) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(list(qs), [self.a2]) def test_null_join_demotion(self): qs = ModelA.objects.filter(Q(b__name__isnull=False) & Q(b__name__isnull=True)) self.assertIn(' INNER JOIN ', str(qs.query)) qs = ModelA.objects.filter(Q(b__name__isnull=True) & Q(b__name__isnull=False)) self.assertIn(' INNER JOIN ', str(qs.query)) qs = ModelA.objects.filter(Q(b__name__isnull=False) | Q(b__name__isnull=True)) self.assertIn(' LEFT OUTER JOIN ', str(qs.query)) qs = ModelA.objects.filter(Q(b__name__isnull=True) | Q(b__name__isnull=False)) self.assertIn(' LEFT OUTER JOIN ', str(qs.query)) def test_ticket_21366(self): n = Note.objects.create(note='n', misc='m') e = ExtraInfo.objects.create(info='info', note=n) a = Author.objects.create(name='Author1', num=1, extra=e) Ranking.objects.create(rank=1, author=a) r1 = Report.objects.create(name='Foo', creator=a) r2 = Report.objects.create(name='Bar') Report.objects.create(name='Bar', creator=a) qs = Report.objects.filter( Q(creator__ranking__isnull=True) | Q(creator__ranking__rank=1, name='Foo') ) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) self.assertEqual(str(qs.query).count(' JOIN '), 2) self.assertSequenceEqual(qs.order_by('name'), [r2, r1]) def test_ticket_21748(self): i1 = Identifier.objects.create(name='i1') i2 = Identifier.objects.create(name='i2') i3 = Identifier.objects.create(name='i3') Program.objects.create(identifier=i1) Channel.objects.create(identifier=i1) Program.objects.create(identifier=i2) self.assertSequenceEqual(Identifier.objects.filter(program=None, channel=None), [i3]) self.assertSequenceEqual(Identifier.objects.exclude(program=None, channel=None).order_by('name'), [i1, i2]) def test_ticket_21748_double_negated_and(self): i1 = Identifier.objects.create(name='i1') i2 = Identifier.objects.create(name='i2') Identifier.objects.create(name='i3') p1 = Program.objects.create(identifier=i1) c1 = Channel.objects.create(identifier=i1) Program.objects.create(identifier=i2) # Check the ~~Q() (or equivalently .exclude(~Q)) works like Q() for # join promotion. qs1_doubleneg = Identifier.objects.exclude(~Q(program__id=p1.id, channel__id=c1.id)).order_by('pk') qs1_filter = Identifier.objects.filter(program__id=p1.id, channel__id=c1.id).order_by('pk') self.assertQuerysetEqual(qs1_doubleneg, qs1_filter, lambda x: x) self.assertEqual(str(qs1_filter.query).count('JOIN'), str(qs1_doubleneg.query).count('JOIN')) self.assertEqual(2, str(qs1_doubleneg.query).count('INNER JOIN')) self.assertEqual(str(qs1_filter.query).count('INNER JOIN'), str(qs1_doubleneg.query).count('INNER JOIN')) def test_ticket_21748_double_negated_or(self): i1 = Identifier.objects.create(name='i1') i2 = Identifier.objects.create(name='i2') Identifier.objects.create(name='i3') p1 = Program.objects.create(identifier=i1) c1 = Channel.objects.create(identifier=i1) p2 = Program.objects.create(identifier=i2) # Test OR + doubleneg. The expected result is that channel is LOUTER # joined, program INNER joined qs1_filter = Identifier.objects.filter( Q(program__id=p2.id, channel__id=c1.id) | Q(program__id=p1.id) ).order_by('pk') qs1_doubleneg = Identifier.objects.exclude( ~Q(Q(program__id=p2.id, channel__id=c1.id) | Q(program__id=p1.id)) ).order_by('pk') self.assertQuerysetEqual(qs1_doubleneg, qs1_filter, lambda x: x) self.assertEqual(str(qs1_filter.query).count('JOIN'), str(qs1_doubleneg.query).count('JOIN')) self.assertEqual(1, str(qs1_doubleneg.query).count('INNER JOIN')) self.assertEqual(str(qs1_filter.query).count('INNER JOIN'), str(qs1_doubleneg.query).count('INNER JOIN')) def test_ticket_21748_complex_filter(self): i1 = Identifier.objects.create(name='i1') i2 = Identifier.objects.create(name='i2') Identifier.objects.create(name='i3') p1 = Program.objects.create(identifier=i1) c1 = Channel.objects.create(identifier=i1) p2 = Program.objects.create(identifier=i2) # Finally, a more complex case, one time in a way where each # NOT is pushed to lowest level in the boolean tree, and # another query where this isn't done. qs1 = Identifier.objects.filter( ~Q(~Q(program__id=p2.id, channel__id=c1.id) & Q(program__id=p1.id)) ).order_by('pk') qs2 = Identifier.objects.filter( Q(Q(program__id=p2.id, channel__id=c1.id) | ~Q(program__id=p1.id)) ).order_by('pk') self.assertQuerysetEqual(qs1, qs2, lambda x: x) self.assertEqual(str(qs1.query).count('JOIN'), str(qs2.query).count('JOIN')) self.assertEqual(0, str(qs1.query).count('INNER JOIN')) self.assertEqual(str(qs1.query).count('INNER JOIN'), str(qs2.query).count('INNER JOIN')) class ReverseJoinTrimmingTest(TestCase): def test_reverse_trimming(self): # We don't accidentally trim reverse joins - we can't know if there is # anything on the other side of the join, so trimming reverse joins # can't be done, ever. t = Tag.objects.create() qs = Tag.objects.filter(annotation__tag=t.pk) self.assertIn('INNER JOIN', str(qs.query)) self.assertEqual(list(qs), []) class JoinReuseTest(TestCase): """ The queries reuse joins sensibly (for example, direct joins are always reused). """ def test_fk_reuse(self): qs = Annotation.objects.filter(tag__name='foo').filter(tag__name='bar') self.assertEqual(str(qs.query).count('JOIN'), 1) def test_fk_reuse_select_related(self): qs = Annotation.objects.filter(tag__name='foo').select_related('tag') self.assertEqual(str(qs.query).count('JOIN'), 1) def test_fk_reuse_annotation(self): qs = Annotation.objects.filter(tag__name='foo').annotate(cnt=Count('tag__name')) self.assertEqual(str(qs.query).count('JOIN'), 1) def test_fk_reuse_disjunction(self): qs = Annotation.objects.filter(Q(tag__name='foo') | Q(tag__name='bar')) self.assertEqual(str(qs.query).count('JOIN'), 1) def test_fk_reuse_order_by(self): qs = Annotation.objects.filter(tag__name='foo').order_by('tag__name') self.assertEqual(str(qs.query).count('JOIN'), 1) def test_revo2o_reuse(self): qs = Detail.objects.filter(member__name='foo').filter(member__name='foo') self.assertEqual(str(qs.query).count('JOIN'), 1) def test_revfk_noreuse(self): qs = Author.objects.filter(report__name='r4').filter(report__name='r1') self.assertEqual(str(qs.query).count('JOIN'), 2) def test_inverted_q_across_relations(self): """ When a trimmable join is specified in the query (here school__), the ORM detects it and removes unnecessary joins. The set of reusable joins are updated after trimming the query so that other lookups don't consider that the outer query's filters are in effect for the subquery (#26551). """ springfield_elementary = School.objects.create() hogward = School.objects.create() Student.objects.create(school=springfield_elementary) hp = Student.objects.create(school=hogward) Classroom.objects.create(school=hogward, name='Potion') Classroom.objects.create(school=springfield_elementary, name='Main') qs = Student.objects.filter( ~(Q(school__classroom__name='Main') & Q(school__classroom__has_blackboard=None)) ) self.assertSequenceEqual(qs, [hp]) class DisjunctionPromotionTests(TestCase): def test_disjunction_promotion_select_related(self): fk1 = FK1.objects.create(f1='f1', f2='f2') basea = BaseA.objects.create(a=fk1) qs = BaseA.objects.filter(Q(a=fk1) | Q(b=2)) self.assertEqual(str(qs.query).count(' JOIN '), 0) qs = qs.select_related('a', 'b') self.assertEqual(str(qs.query).count(' INNER JOIN '), 0) self.assertEqual(str(qs.query).count(' LEFT OUTER JOIN '), 2) with self.assertNumQueries(1): self.assertSequenceEqual(qs, [basea]) self.assertEqual(qs[0].a, fk1) self.assertIs(qs[0].b, None) def test_disjunction_promotion1(self): # Pre-existing join, add two ORed filters to the same join, # all joins can be INNER JOINS. qs = BaseA.objects.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) qs = qs.filter(Q(b__f1='foo') | Q(b__f2='foo')) self.assertEqual(str(qs.query).count('INNER JOIN'), 2) # Reverse the order of AND and OR filters. qs = BaseA.objects.filter(Q(b__f1='foo') | Q(b__f2='foo')) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) qs = qs.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 2) def test_disjunction_promotion2(self): qs = BaseA.objects.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) # Now we have two different joins in an ORed condition, these # must be OUTER joins. The pre-existing join should remain INNER. qs = qs.filter(Q(b__f1='foo') | Q(c__f2='foo')) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) # Reverse case. qs = BaseA.objects.filter(Q(b__f1='foo') | Q(c__f2='foo')) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) qs = qs.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) def test_disjunction_promotion3(self): qs = BaseA.objects.filter(a__f2='bar') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) # The ANDed a__f2 filter allows us to use keep using INNER JOIN # even inside the ORed case. If the join to a__ returns nothing, # the ANDed filter for a__f2 can't be true. qs = qs.filter(Q(a__f1='foo') | Q(b__f2='foo')) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) def test_disjunction_promotion3_demote(self): # This one needs demotion logic: the first filter causes a to be # outer joined, the second filter makes it inner join again. qs = BaseA.objects.filter( Q(a__f1='foo') | Q(b__f2='foo')).filter(a__f2='bar') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) def test_disjunction_promotion4_demote(self): qs = BaseA.objects.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('JOIN'), 0) # Demote needed for the "a" join. It is marked as outer join by # above filter (even if it is trimmed away). qs = qs.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) def test_disjunction_promotion4(self): qs = BaseA.objects.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) qs = qs.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) def test_disjunction_promotion5_demote(self): qs = BaseA.objects.filter(Q(a=1) | Q(a=2)) # Note that the above filters on a force the join to an # inner join even if it is trimmed. self.assertEqual(str(qs.query).count('JOIN'), 0) qs = qs.filter(Q(a__f1='foo') | Q(b__f1='foo')) # So, now the a__f1 join doesn't need promotion. self.assertEqual(str(qs.query).count('INNER JOIN'), 1) # But b__f1 does. self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) qs = BaseA.objects.filter(Q(a__f1='foo') | Q(b__f1='foo')) # Now the join to a is created as LOUTER self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) qs = qs.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) def test_disjunction_promotion6(self): qs = BaseA.objects.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('JOIN'), 0) qs = BaseA.objects.filter(Q(a__f1='foo') & Q(b__f1='foo')) self.assertEqual(str(qs.query).count('INNER JOIN'), 2) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 0) qs = BaseA.objects.filter(Q(a__f1='foo') & Q(b__f1='foo')) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(qs.query).count('INNER JOIN'), 2) qs = qs.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('INNER JOIN'), 2) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 0) def test_disjunction_promotion7(self): qs = BaseA.objects.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('JOIN'), 0) qs = BaseA.objects.filter(Q(a__f1='foo') | (Q(b__f1='foo') & Q(a__f1='bar'))) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) qs = BaseA.objects.filter( (Q(a__f1='foo') | Q(b__f1='foo')) & (Q(a__f1='bar') | Q(c__f1='foo')) ) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 3) self.assertEqual(str(qs.query).count('INNER JOIN'), 0) qs = BaseA.objects.filter( (Q(a__f1='foo') | (Q(a__f1='bar')) & (Q(b__f1='bar') | Q(c__f1='foo'))) ) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) def test_disjunction_promotion_fexpression(self): qs = BaseA.objects.filter(Q(a__f1=F('b__f1')) | Q(b__f1='foo')) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) qs = BaseA.objects.filter(Q(a__f1=F('c__f1')) | Q(b__f1='foo')) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 3) qs = BaseA.objects.filter(Q(a__f1=F('b__f1')) | Q(a__f2=F('b__f2')) | Q(c__f1='foo')) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 3) qs = BaseA.objects.filter(Q(a__f1=F('c__f1')) | (Q(pk=1) & Q(pk=2))) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) self.assertEqual(str(qs.query).count('INNER JOIN'), 0) class ManyToManyExcludeTest(TestCase): def test_exclude_many_to_many(self): Identifier.objects.create(name='extra') program = Program.objects.create(identifier=Identifier.objects.create(name='program')) channel = Channel.objects.create(identifier=Identifier.objects.create(name='channel')) channel.programs.add(program) # channel contains 'program1', so all Identifiers except that one # should be returned self.assertQuerysetEqual( Identifier.objects.exclude(program__channel=channel).order_by('name'), ['<Identifier: channel>', '<Identifier: extra>'] ) self.assertQuerysetEqual( Identifier.objects.exclude(program__channel=None).order_by('name'), ['<Identifier: program>'] ) def test_ticket_12823(self): pg3 = Page.objects.create(text='pg3') pg2 = Page.objects.create(text='pg2') pg1 = Page.objects.create(text='pg1') pa1 = Paragraph.objects.create(text='pa1') pa1.page.set([pg1, pg2]) pa2 = Paragraph.objects.create(text='pa2') pa2.page.set([pg2, pg3]) pa3 = Paragraph.objects.create(text='pa3') ch1 = Chapter.objects.create(title='ch1', paragraph=pa1) ch2 = Chapter.objects.create(title='ch2', paragraph=pa2) ch3 = Chapter.objects.create(title='ch3', paragraph=pa3) b1 = Book.objects.create(title='b1', chapter=ch1) b2 = Book.objects.create(title='b2', chapter=ch2) b3 = Book.objects.create(title='b3', chapter=ch3) q = Book.objects.exclude(chapter__paragraph__page__text='pg1') self.assertNotIn('IS NOT NULL', str(q.query)) self.assertEqual(len(q), 2) self.assertNotIn(b1, q) self.assertIn(b2, q) self.assertIn(b3, q) class RelabelCloneTest(TestCase): def test_ticket_19964(self): my1 = MyObject.objects.create(data='foo') my1.parent = my1 my1.save() my2 = MyObject.objects.create(data='bar', parent=my1) parents = MyObject.objects.filter(parent=F('id')) children = MyObject.objects.filter(parent__in=parents).exclude(parent=F('id')) self.assertEqual(list(parents), [my1]) # Evaluating the children query (which has parents as part of it) does # not change results for the parents query. self.assertEqual(list(children), [my2]) self.assertEqual(list(parents), [my1]) class Ticket20101Tests(TestCase): def test_ticket_20101(self): """ Tests QuerySet ORed combining in exclude subquery case. """ t = Tag.objects.create(name='foo') a1 = Annotation.objects.create(tag=t, name='a1') a2 = Annotation.objects.create(tag=t, name='a2') a3 = Annotation.objects.create(tag=t, name='a3') n = Note.objects.create(note='foo', misc='bar') qs1 = Note.objects.exclude(annotation__in=[a1, a2]) qs2 = Note.objects.filter(annotation__in=[a3]) self.assertIn(n, qs1) self.assertNotIn(n, qs2) self.assertIn(n, (qs1 | qs2)) class EmptyStringPromotionTests(SimpleTestCase): def test_empty_string_promotion(self): qs = RelatedObject.objects.filter(single__name='') if connection.features.interprets_empty_strings_as_nulls: self.assertIn('LEFT OUTER JOIN', str(qs.query)) else: self.assertNotIn('LEFT OUTER JOIN', str(qs.query)) class ValuesSubqueryTests(TestCase): def test_values_in_subquery(self): # If a values() queryset is used, then the given values # will be used instead of forcing use of the relation's field. o1 = Order.objects.create(id=-2) o2 = Order.objects.create(id=-1) oi1 = OrderItem.objects.create(order=o1, status=0) oi1.status = oi1.pk oi1.save() OrderItem.objects.create(order=o2, status=0) # The query below should match o1 as it has related order_item # with id == status. self.assertSequenceEqual(Order.objects.filter(items__in=OrderItem.objects.values_list('status')), [o1]) class DoubleInSubqueryTests(TestCase): def test_double_subquery_in(self): lfa1 = LeafA.objects.create(data='foo') lfa2 = LeafA.objects.create(data='bar') lfb1 = LeafB.objects.create(data='lfb1') lfb2 = LeafB.objects.create(data='lfb2') Join.objects.create(a=lfa1, b=lfb1) Join.objects.create(a=lfa2, b=lfb2) leaf_as = LeafA.objects.filter(data='foo').values_list('pk', flat=True) joins = Join.objects.filter(a__in=leaf_as).values_list('b__id', flat=True) qs = LeafB.objects.filter(pk__in=joins) self.assertSequenceEqual(qs, [lfb1]) class Ticket18785Tests(SimpleTestCase): def test_ticket_18785(self): # Test join trimming from ticket18785 qs = Item.objects.exclude( note__isnull=False ).filter( name='something', creator__extra__isnull=True ).order_by() self.assertEqual(1, str(qs.query).count('INNER JOIN')) self.assertEqual(0, str(qs.query).count('OUTER JOIN')) class Ticket20788Tests(TestCase): def test_ticket_20788(self): Paragraph.objects.create() paragraph = Paragraph.objects.create() page = paragraph.page.create() chapter = Chapter.objects.create(paragraph=paragraph) Book.objects.create(chapter=chapter) paragraph2 = Paragraph.objects.create() Page.objects.create() chapter2 = Chapter.objects.create(paragraph=paragraph2) book2 = Book.objects.create(chapter=chapter2) sentences_not_in_pub = Book.objects.exclude(chapter__paragraph__page=page) self.assertSequenceEqual(sentences_not_in_pub, [book2]) class Ticket12807Tests(TestCase): def test_ticket_12807(self): p1 = Paragraph.objects.create() p2 = Paragraph.objects.create() # The ORed condition below should have no effect on the query - the # ~Q(pk__in=[]) will always be True. qs = Paragraph.objects.filter((Q(pk=p2.pk) | ~Q(pk__in=[])) & Q(pk=p1.pk)) self.assertSequenceEqual(qs, [p1]) class RelatedLookupTypeTests(TestCase): error = 'Cannot query "%s": Must be "%s" instance.' @classmethod def setUpTestData(cls): cls.oa = ObjectA.objects.create(name="oa") cls.poa = ProxyObjectA.objects.get(name="oa") cls.coa = ChildObjectA.objects.create(name="coa") cls.wrong_type = Order.objects.create(id=cls.oa.pk) cls.ob = ObjectB.objects.create(name="ob", objecta=cls.oa, num=1) ProxyObjectB.objects.create(name="pob", objecta=cls.oa, num=2) cls.pob = ProxyObjectB.objects.all() ObjectC.objects.create(childobjecta=cls.coa) def test_wrong_type_lookup(self): """ A ValueError is raised when the incorrect object type is passed to a query lookup. """ # Passing incorrect object type with self.assertRaisesMessage(ValueError, self.error % (self.wrong_type, ObjectA._meta.object_name)): ObjectB.objects.get(objecta=self.wrong_type) with self.assertRaisesMessage(ValueError, self.error % (self.wrong_type, ObjectA._meta.object_name)): ObjectB.objects.filter(objecta__in=[self.wrong_type]) with self.assertRaisesMessage(ValueError, self.error % (self.wrong_type, ObjectA._meta.object_name)): ObjectB.objects.filter(objecta=self.wrong_type) with self.assertRaisesMessage(ValueError, self.error % (self.wrong_type, ObjectB._meta.object_name)): ObjectA.objects.filter(objectb__in=[self.wrong_type, self.ob]) # Passing an object of the class on which query is done. with self.assertRaisesMessage(ValueError, self.error % (self.ob, ObjectA._meta.object_name)): ObjectB.objects.filter(objecta__in=[self.poa, self.ob]) with self.assertRaisesMessage(ValueError, self.error % (self.ob, ChildObjectA._meta.object_name)): ObjectC.objects.exclude(childobjecta__in=[self.coa, self.ob]) def test_wrong_backward_lookup(self): """ A ValueError is raised when the incorrect object type is passed to a query lookup for backward relations. """ with self.assertRaisesMessage(ValueError, self.error % (self.oa, ObjectB._meta.object_name)): ObjectA.objects.filter(objectb__in=[self.oa, self.ob]) with self.assertRaisesMessage(ValueError, self.error % (self.oa, ObjectB._meta.object_name)): ObjectA.objects.exclude(objectb=self.oa) with self.assertRaisesMessage(ValueError, self.error % (self.wrong_type, ObjectB._meta.object_name)): ObjectA.objects.get(objectb=self.wrong_type) def test_correct_lookup(self): """ When passing proxy model objects, child objects, or parent objects, lookups work fine. """ out_a = ['<ObjectA: oa>'] out_b = ['<ObjectB: ob>', '<ObjectB: pob>'] out_c = ['<ObjectC: >'] # proxy model objects self.assertQuerysetEqual(ObjectB.objects.filter(objecta=self.poa).order_by('name'), out_b) self.assertQuerysetEqual(ObjectA.objects.filter(objectb__in=self.pob).order_by('pk'), out_a * 2) # child objects self.assertQuerysetEqual(ObjectB.objects.filter(objecta__in=[self.coa]), []) self.assertQuerysetEqual(ObjectB.objects.filter(objecta__in=[self.poa, self.coa]).order_by('name'), out_b) self.assertQuerysetEqual( ObjectB.objects.filter(objecta__in=iter([self.poa, self.coa])).order_by('name'), out_b ) # parent objects self.assertQuerysetEqual(ObjectC.objects.exclude(childobjecta=self.oa), out_c) # QuerySet related object type checking shouldn't issue queries # (the querysets aren't evaluated here, hence zero queries) (#23266). with self.assertNumQueries(0): ObjectB.objects.filter(objecta__in=ObjectA.objects.all()) def test_values_queryset_lookup(self): """ #23396 - Ensure ValueQuerySets are not checked for compatibility with the lookup field """ # Make sure the num and objecta field values match. ob = ObjectB.objects.get(name='ob') ob.num = ob.objecta.pk ob.save() pob = ObjectB.objects.get(name='pob') pob.num = pob.objecta.pk pob.save() self.assertQuerysetEqual(ObjectB.objects.filter( objecta__in=ObjectB.objects.all().values_list('num') ).order_by('pk'), ['<ObjectB: ob>', '<ObjectB: pob>']) class Ticket14056Tests(TestCase): def test_ticket_14056(self): s1 = SharedConnection.objects.create(data='s1') s2 = SharedConnection.objects.create(data='s2') s3 = SharedConnection.objects.create(data='s3') PointerA.objects.create(connection=s2) expected_ordering = ( [s1, s3, s2] if connection.features.nulls_order_largest else [s2, s1, s3] ) self.assertSequenceEqual(SharedConnection.objects.order_by('-pointera__connection', 'pk'), expected_ordering) class Ticket20955Tests(TestCase): def test_ticket_20955(self): jack = Staff.objects.create(name='jackstaff') jackstaff = StaffUser.objects.create(staff=jack) jill = Staff.objects.create(name='jillstaff') jillstaff = StaffUser.objects.create(staff=jill) task = Task.objects.create(creator=jackstaff, owner=jillstaff, title="task") task_get = Task.objects.get(pk=task.pk) # Load data so that assertNumQueries doesn't complain about the get # version's queries. task_get.creator.staffuser.staff task_get.owner.staffuser.staff qs = Task.objects.select_related( 'creator__staffuser__staff', 'owner__staffuser__staff') self.assertEqual(str(qs.query).count(' JOIN '), 6) task_select_related = qs.get(pk=task.pk) with self.assertNumQueries(0): self.assertEqual(task_select_related.creator.staffuser.staff, task_get.creator.staffuser.staff) self.assertEqual(task_select_related.owner.staffuser.staff, task_get.owner.staffuser.staff) class Ticket21203Tests(TestCase): def test_ticket_21203(self): p = Ticket21203Parent.objects.create(parent_bool=True) c = Ticket21203Child.objects.create(parent=p) qs = Ticket21203Child.objects.select_related('parent').defer('parent__created') self.assertSequenceEqual(qs, [c]) self.assertIs(qs[0].parent.parent_bool, True) class ValuesJoinPromotionTests(TestCase): def test_values_no_promotion_for_existing(self): qs = Node.objects.filter(parent__parent__isnull=False) self.assertIn(' INNER JOIN ', str(qs.query)) qs = qs.values('parent__parent__id') self.assertIn(' INNER JOIN ', str(qs.query)) # Make sure there is a left outer join without the filter. qs = Node.objects.values('parent__parent__id') self.assertIn(' LEFT OUTER JOIN ', str(qs.query)) def test_non_nullable_fk_not_promoted(self): qs = ObjectB.objects.values('objecta__name') self.assertIn(' INNER JOIN ', str(qs.query)) def test_ticket_21376(self): a = ObjectA.objects.create() ObjectC.objects.create(objecta=a) qs = ObjectC.objects.filter( Q(objecta=a) | Q(objectb__objecta=a), ) qs = qs.filter( Q(objectb=1) | Q(objecta=a), ) self.assertEqual(qs.count(), 1) tblname = connection.ops.quote_name(ObjectB._meta.db_table) self.assertIn(' LEFT OUTER JOIN %s' % tblname, str(qs.query)) class ForeignKeyToBaseExcludeTests(TestCase): def test_ticket_21787(self): sc1 = SpecialCategory.objects.create(special_name='sc1', name='sc1') sc2 = SpecialCategory.objects.create(special_name='sc2', name='sc2') sc3 = SpecialCategory.objects.create(special_name='sc3', name='sc3') c1 = CategoryItem.objects.create(category=sc1) CategoryItem.objects.create(category=sc2) self.assertSequenceEqual(SpecialCategory.objects.exclude(categoryitem__id=c1.pk).order_by('name'), [sc2, sc3]) self.assertSequenceEqual(SpecialCategory.objects.filter(categoryitem__id=c1.pk), [sc1]) class ReverseM2MCustomPkTests(TestCase): def test_ticket_21879(self): cpt1 = CustomPkTag.objects.create(id='cpt1', tag='cpt1') cp1 = CustomPk.objects.create(name='cp1', extra='extra') cp1.custompktag_set.add(cpt1) self.assertSequenceEqual(CustomPk.objects.filter(custompktag=cpt1), [cp1]) self.assertSequenceEqual(CustomPkTag.objects.filter(custom_pk=cp1), [cpt1]) class Ticket22429Tests(TestCase): def test_ticket_22429(self): sc1 = School.objects.create() st1 = Student.objects.create(school=sc1) sc2 = School.objects.create() st2 = Student.objects.create(school=sc2) cr = Classroom.objects.create(school=sc1) cr.students.add(st1) queryset = Student.objects.filter(~Q(classroom__school=F('school'))) self.assertSequenceEqual(queryset, [st2]) class Ticket23605Tests(TestCase): def test_ticket_23605(self): # Test filtering on a complicated q-object from ticket's report. # The query structure is such that we have multiple nested subqueries. # The original problem was that the inner queries weren't relabeled # correctly. # See also #24090. a1 = Ticket23605A.objects.create() a2 = Ticket23605A.objects.create() c1 = Ticket23605C.objects.create(field_c0=10000.0) Ticket23605B.objects.create( field_b0=10000.0, field_b1=True, modelc_fk=c1, modela_fk=a1) complex_q = Q(pk__in=Ticket23605A.objects.filter( Q( # True for a1 as field_b0 = 10000, field_c0=10000 # False for a2 as no ticket23605b found ticket23605b__field_b0__gte=1000000 / F("ticket23605b__modelc_fk__field_c0") ) & # True for a1 (field_b1=True) Q(ticket23605b__field_b1=True) & ~Q(ticket23605b__pk__in=Ticket23605B.objects.filter( ~( # Same filters as above commented filters, but # double-negated (one for Q() above, one for # parentheses). So, again a1 match, a2 not. Q(field_b1=True) & Q(field_b0__gte=1000000 / F("modelc_fk__field_c0")) ) ))).filter(ticket23605b__field_b1=True)) qs1 = Ticket23605A.objects.filter(complex_q) self.assertSequenceEqual(qs1, [a1]) qs2 = Ticket23605A.objects.exclude(complex_q) self.assertSequenceEqual(qs2, [a2]) class TestTicket24279(TestCase): def test_ticket_24278(self): School.objects.create() qs = School.objects.filter(Q(pk__in=()) | Q()) self.assertQuerysetEqual(qs, []) class TestInvalidValuesRelation(SimpleTestCase): def test_invalid_values(self): msg = "Field 'id' expected a number but got 'abc'." with self.assertRaisesMessage(ValueError, msg): Annotation.objects.filter(tag='abc') with self.assertRaisesMessage(ValueError, msg): Annotation.objects.filter(tag__in=[123, 'abc']) class TestTicket24605(TestCase): def test_ticket_24605(self): """ Subquery table names should be quoted. """ i1 = Individual.objects.create(alive=True) RelatedIndividual.objects.create(related=i1) i2 = Individual.objects.create(alive=False) RelatedIndividual.objects.create(related=i2) i3 = Individual.objects.create(alive=True) i4 = Individual.objects.create(alive=False) self.assertSequenceEqual(Individual.objects.filter(Q(alive=False), Q(related_individual__isnull=True)), [i4]) self.assertSequenceEqual( Individual.objects.exclude(Q(alive=False), Q(related_individual__isnull=True)).order_by('pk'), [i1, i2, i3] ) class Ticket23622Tests(TestCase): @skipUnlessDBFeature('can_distinct_on_fields') def test_ticket_23622(self): """ Make sure __pk__in and __in work the same for related fields when using a distinct on subquery. """ a1 = Ticket23605A.objects.create() a2 = Ticket23605A.objects.create() c1 = Ticket23605C.objects.create(field_c0=0.0) Ticket23605B.objects.create( modela_fk=a1, field_b0=123, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a1, field_b0=23, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a1, field_b0=234, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a1, field_b0=12, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a2, field_b0=567, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a2, field_b0=76, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a2, field_b0=7, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a2, field_b0=56, field_b1=True, modelc_fk=c1, ) qx = ( Q(ticket23605b__pk__in=Ticket23605B.objects.order_by('modela_fk', '-field_b1').distinct('modela_fk')) & Q(ticket23605b__field_b0__gte=300) ) qy = ( Q(ticket23605b__in=Ticket23605B.objects.order_by('modela_fk', '-field_b1').distinct('modela_fk')) & Q(ticket23605b__field_b0__gte=300) ) self.assertEqual( set(Ticket23605A.objects.filter(qx).values_list('pk', flat=True)), set(Ticket23605A.objects.filter(qy).values_list('pk', flat=True)) ) self.assertSequenceEqual(Ticket23605A.objects.filter(qx), [a2])
5e5402d55cbbb3a47fa7adc0c0bcb154cc03d08c1d989ca832482f4d62eb3189
""" Various complex queries that have been problematic in the past. """ import threading from django.db import models from django.db.models.functions import Now class DumbCategory(models.Model): pass class ProxyCategory(DumbCategory): class Meta: proxy = True class NamedCategory(DumbCategory): name = models.CharField(max_length=10) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=10) parent = models.ForeignKey( 'self', models.SET_NULL, blank=True, null=True, related_name='children', ) category = models.ForeignKey(NamedCategory, models.SET_NULL, null=True, default=None) class Meta: ordering = ['name'] def __str__(self): return self.name class Note(models.Model): note = models.CharField(max_length=100) misc = models.CharField(max_length=10) tag = models.ForeignKey(Tag, models.SET_NULL, blank=True, null=True) class Meta: ordering = ['note'] def __str__(self): return self.note def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Regression for #13227 -- having an attribute that # is unpicklable doesn't stop you from cloning queries # that use objects of that type as an argument. self.lock = threading.Lock() class Annotation(models.Model): name = models.CharField(max_length=10) tag = models.ForeignKey(Tag, models.CASCADE) notes = models.ManyToManyField(Note) def __str__(self): return self.name class DateTimePK(models.Model): date = models.DateTimeField(primary_key=True, auto_now_add=True) class ExtraInfo(models.Model): info = models.CharField(max_length=100) note = models.ForeignKey(Note, models.CASCADE, null=True) value = models.IntegerField(null=True) date = models.ForeignKey(DateTimePK, models.SET_NULL, null=True) class Meta: ordering = ['info'] def __str__(self): return self.info class Author(models.Model): name = models.CharField(max_length=10) num = models.IntegerField(unique=True) extra = models.ForeignKey(ExtraInfo, models.CASCADE) class Meta: ordering = ['name'] def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=10) created = models.DateTimeField() modified = models.DateTimeField(blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True) creator = models.ForeignKey(Author, models.CASCADE) note = models.ForeignKey(Note, models.CASCADE) class Meta: ordering = ['-note', 'name'] def __str__(self): return self.name class Report(models.Model): name = models.CharField(max_length=10) creator = models.ForeignKey(Author, models.SET_NULL, to_field='num', null=True) def __str__(self): return self.name class ReportComment(models.Model): report = models.ForeignKey(Report, models.CASCADE) class Ranking(models.Model): rank = models.IntegerField() author = models.ForeignKey(Author, models.CASCADE) class Meta: # A complex ordering specification. Should stress the system a bit. ordering = ('author__extra__note', 'author__name', 'rank') def __str__(self): return '%d: %s' % (self.rank, self.author.name) class Cover(models.Model): title = models.CharField(max_length=50) item = models.ForeignKey(Item, models.CASCADE) class Meta: ordering = ['item'] def __str__(self): return self.title class Number(models.Model): num = models.IntegerField() other_num = models.IntegerField(null=True) def __str__(self): return str(self.num) # Symmetrical m2m field with a normal field using the reverse accessor name # ("valid"). class Valid(models.Model): valid = models.CharField(max_length=10) parent = models.ManyToManyField('self') class Meta: ordering = ['valid'] # Some funky cross-linked models for testing a couple of infinite recursion # cases. class X(models.Model): y = models.ForeignKey('Y', models.CASCADE) class Y(models.Model): x1 = models.ForeignKey(X, models.CASCADE, related_name='y1') # Some models with a cycle in the default ordering. This would be bad if we # didn't catch the infinite loop. class LoopX(models.Model): y = models.ForeignKey('LoopY', models.CASCADE) class Meta: ordering = ['y'] class LoopY(models.Model): x = models.ForeignKey(LoopX, models.CASCADE) class Meta: ordering = ['x'] class LoopZ(models.Model): z = models.ForeignKey('self', models.CASCADE) class Meta: ordering = ['z'] # A model and custom default manager combination. class CustomManager(models.Manager): def get_queryset(self): qs = super().get_queryset() return qs.filter(public=True, tag__name='t1') class ManagedModel(models.Model): data = models.CharField(max_length=10) tag = models.ForeignKey(Tag, models.CASCADE) public = models.BooleanField(default=True) objects = CustomManager() normal_manager = models.Manager() def __str__(self): return self.data # An inter-related setup with multiple paths from Child to Detail. class Detail(models.Model): data = models.CharField(max_length=10) class MemberManager(models.Manager): def get_queryset(self): return super().get_queryset().select_related("details") class Member(models.Model): name = models.CharField(max_length=10) details = models.OneToOneField(Detail, models.CASCADE, primary_key=True) objects = MemberManager() class Child(models.Model): person = models.OneToOneField(Member, models.CASCADE, primary_key=True) parent = models.ForeignKey(Member, models.CASCADE, related_name="children") # Custom primary keys interfered with ordering in the past. class CustomPk(models.Model): name = models.CharField(max_length=10, primary_key=True) extra = models.CharField(max_length=10) class Meta: ordering = ['name', 'extra'] class Related(models.Model): custom = models.ForeignKey(CustomPk, models.CASCADE, null=True) class CustomPkTag(models.Model): id = models.CharField(max_length=20, primary_key=True) custom_pk = models.ManyToManyField(CustomPk) tag = models.CharField(max_length=20) # An inter-related setup with a model subclass that has a nullable # path to another model, and a return path from that model. class Celebrity(models.Model): name = models.CharField("Name", max_length=20) greatest_fan = models.ForeignKey("Fan", models.SET_NULL, null=True, unique=True) def __str__(self): return self.name class TvChef(Celebrity): pass class Fan(models.Model): fan_of = models.ForeignKey(Celebrity, models.CASCADE) # Multiple foreign keys class LeafA(models.Model): data = models.CharField(max_length=10) def __str__(self): return self.data class LeafB(models.Model): data = models.CharField(max_length=10) class Join(models.Model): a = models.ForeignKey(LeafA, models.CASCADE) b = models.ForeignKey(LeafB, models.CASCADE) class ReservedName(models.Model): name = models.CharField(max_length=20) order = models.IntegerField() def __str__(self): return self.name # A simpler shared-foreign-key setup that can expose some problems. class SharedConnection(models.Model): data = models.CharField(max_length=10) def __str__(self): return self.data class PointerA(models.Model): connection = models.ForeignKey(SharedConnection, models.CASCADE) class PointerB(models.Model): connection = models.ForeignKey(SharedConnection, models.CASCADE) # Multi-layer ordering class SingleObject(models.Model): name = models.CharField(max_length=10) class Meta: ordering = ['name'] def __str__(self): return self.name class RelatedObject(models.Model): single = models.ForeignKey(SingleObject, models.SET_NULL, null=True) f = models.IntegerField(null=True) class Meta: ordering = ['single'] class Plaything(models.Model): name = models.CharField(max_length=10) others = models.ForeignKey(RelatedObject, models.SET_NULL, null=True) class Meta: ordering = ['others'] def __str__(self): return self.name class Article(models.Model): name = models.CharField(max_length=20) created = models.DateTimeField() def __str__(self): return self.name class Food(models.Model): name = models.CharField(max_length=20, unique=True) def __str__(self): return self.name class Eaten(models.Model): food = models.ForeignKey(Food, models.SET_NULL, to_field="name", null=True) meal = models.CharField(max_length=20) def __str__(self): return "%s at %s" % (self.food, self.meal) class Node(models.Model): num = models.IntegerField(unique=True) parent = models.ForeignKey("self", models.SET_NULL, to_field="num", null=True) def __str__(self): return "%s" % self.num # Bug #12252 class ObjectA(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name def __iter__(self): # Ticket #23721 assert False, 'type checking should happen without calling model __iter__' class ProxyObjectA(ObjectA): class Meta: proxy = True class ChildObjectA(ObjectA): pass class ObjectB(models.Model): name = models.CharField(max_length=50) objecta = models.ForeignKey(ObjectA, models.CASCADE) num = models.PositiveSmallIntegerField() def __str__(self): return self.name class ProxyObjectB(ObjectB): class Meta: proxy = True class ObjectC(models.Model): name = models.CharField(max_length=50) objecta = models.ForeignKey(ObjectA, models.SET_NULL, null=True) objectb = models.ForeignKey(ObjectB, models.SET_NULL, null=True) childobjecta = models.ForeignKey(ChildObjectA, models.SET_NULL, null=True, related_name='ca_pk') def __str__(self): return self.name class SimpleCategory(models.Model): name = models.CharField(max_length=15) def __str__(self): return self.name class SpecialCategory(SimpleCategory): special_name = models.CharField(max_length=15) def __str__(self): return self.name + " " + self.special_name class CategoryItem(models.Model): category = models.ForeignKey(SimpleCategory, models.CASCADE) def __str__(self): return "category item: " + str(self.category) class MixedCaseFieldCategoryItem(models.Model): CaTeGoRy = models.ForeignKey(SimpleCategory, models.CASCADE) class MixedCaseDbColumnCategoryItem(models.Model): category = models.ForeignKey(SimpleCategory, models.CASCADE, db_column='CaTeGoRy_Id') class OneToOneCategory(models.Model): new_name = models.CharField(max_length=15) category = models.OneToOneField(SimpleCategory, models.CASCADE) def __str__(self): return "one2one " + self.new_name class CategoryRelationship(models.Model): first = models.ForeignKey(SimpleCategory, models.CASCADE, related_name='first_rel') second = models.ForeignKey(SimpleCategory, models.CASCADE, related_name='second_rel') class CommonMixedCaseForeignKeys(models.Model): category = models.ForeignKey(CategoryItem, models.CASCADE) mixed_case_field_category = models.ForeignKey(MixedCaseFieldCategoryItem, models.CASCADE) mixed_case_db_column_category = models.ForeignKey(MixedCaseDbColumnCategoryItem, models.CASCADE) class NullableName(models.Model): name = models.CharField(max_length=20, null=True) class Meta: ordering = ['id'] class ModelD(models.Model): name = models.TextField() class ModelC(models.Model): name = models.TextField() class ModelB(models.Model): name = models.TextField() c = models.ForeignKey(ModelC, models.CASCADE) class ModelA(models.Model): name = models.TextField() b = models.ForeignKey(ModelB, models.SET_NULL, null=True) d = models.ForeignKey(ModelD, models.CASCADE) class Job(models.Model): name = models.CharField(max_length=20, unique=True) def __str__(self): return self.name class JobResponsibilities(models.Model): job = models.ForeignKey(Job, models.CASCADE, to_field='name') responsibility = models.ForeignKey('Responsibility', models.CASCADE, to_field='description') class Responsibility(models.Model): description = models.CharField(max_length=20, unique=True) jobs = models.ManyToManyField(Job, through=JobResponsibilities, related_name='responsibilities') def __str__(self): return self.description # Models for disjunction join promotion low level testing. class FK1(models.Model): f1 = models.TextField() f2 = models.TextField() class FK2(models.Model): f1 = models.TextField() f2 = models.TextField() class FK3(models.Model): f1 = models.TextField() f2 = models.TextField() class BaseA(models.Model): a = models.ForeignKey(FK1, models.SET_NULL, null=True) b = models.ForeignKey(FK2, models.SET_NULL, null=True) c = models.ForeignKey(FK3, models.SET_NULL, null=True) class Identifier(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Program(models.Model): identifier = models.OneToOneField(Identifier, models.CASCADE) class Channel(models.Model): programs = models.ManyToManyField(Program) identifier = models.OneToOneField(Identifier, models.CASCADE) class Book(models.Model): title = models.TextField() chapter = models.ForeignKey('Chapter', models.CASCADE) class Chapter(models.Model): title = models.TextField() paragraph = models.ForeignKey('Paragraph', models.CASCADE) class Paragraph(models.Model): text = models.TextField() page = models.ManyToManyField('Page') class Page(models.Model): text = models.TextField() class MyObject(models.Model): parent = models.ForeignKey('self', models.SET_NULL, null=True, blank=True, related_name='children') data = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) # Models for #17600 regressions class Order(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=12, null=True, default='') class Meta: ordering = ('pk',) def __str__(self): return '%s' % self.pk class OrderItem(models.Model): order = models.ForeignKey(Order, models.CASCADE, related_name='items') status = models.IntegerField() class Meta: ordering = ('pk',) def __str__(self): return '%s' % self.pk class BaseUser(models.Model): pass class Task(models.Model): title = models.CharField(max_length=10) owner = models.ForeignKey(BaseUser, models.CASCADE, related_name='owner') creator = models.ForeignKey(BaseUser, models.CASCADE, related_name='creator') def __str__(self): return self.title class Staff(models.Model): name = models.CharField(max_length=10) def __str__(self): return self.name class StaffUser(BaseUser): staff = models.OneToOneField(Staff, models.CASCADE, related_name='user') def __str__(self): return self.staff class Ticket21203Parent(models.Model): parentid = models.AutoField(primary_key=True) parent_bool = models.BooleanField(default=True) created = models.DateTimeField(auto_now=True) class Ticket21203Child(models.Model): childid = models.AutoField(primary_key=True) parent = models.ForeignKey(Ticket21203Parent, models.CASCADE) class Person(models.Model): name = models.CharField(max_length=128) class Company(models.Model): name = models.CharField(max_length=128) employees = models.ManyToManyField(Person, related_name='employers', through='Employment') def __str__(self): return self.name class Employment(models.Model): employer = models.ForeignKey(Company, models.CASCADE) employee = models.ForeignKey(Person, models.CASCADE) title = models.CharField(max_length=128) class School(models.Model): pass class Student(models.Model): school = models.ForeignKey(School, models.CASCADE) class Classroom(models.Model): name = models.CharField(max_length=20) has_blackboard = models.BooleanField(null=True) school = models.ForeignKey(School, models.CASCADE) students = models.ManyToManyField(Student, related_name='classroom') class Teacher(models.Model): schools = models.ManyToManyField(School) friends = models.ManyToManyField('self') class Ticket23605AParent(models.Model): pass class Ticket23605A(Ticket23605AParent): pass class Ticket23605B(models.Model): modela_fk = models.ForeignKey(Ticket23605A, models.CASCADE) modelc_fk = models.ForeignKey("Ticket23605C", models.CASCADE) field_b0 = models.IntegerField(null=True) field_b1 = models.BooleanField(default=False) class Ticket23605C(models.Model): field_c0 = models.FloatField() # db_table names have capital letters to ensure they are quoted in queries. class Individual(models.Model): alive = models.BooleanField() class Meta: db_table = 'Individual' class RelatedIndividual(models.Model): related = models.ForeignKey(Individual, models.CASCADE, related_name='related_individual') class Meta: db_table = 'RelatedIndividual' class CustomDbColumn(models.Model): custom_column = models.IntegerField(db_column='custom_name', null=True) ip_address = models.GenericIPAddressField(null=True) class CreatedField(models.DateTimeField): db_returning = True def __init__(self, *args, **kwargs): kwargs.setdefault('default', Now) super().__init__(*args, **kwargs) class ReturningModel(models.Model): created = CreatedField(editable=False) class NonIntegerPKReturningModel(models.Model): created = CreatedField(editable=False, primary_key=True)
535b5a32f2525a614d900440eb66bb2d661aaf257c8527169801d2f041e480c8
from django.db import connection from django.db.models import Exists, F, IntegerField, OuterRef, Value from django.db.utils import DatabaseError, NotSupportedError from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from .models import Number, ReservedName @skipUnlessDBFeature('supports_select_union') class QuerySetSetOperationTests(TestCase): @classmethod def setUpTestData(cls): Number.objects.bulk_create(Number(num=i, other_num=10 - i) for i in range(10)) def number_transform(self, value): return value.num def assertNumbersEqual(self, queryset, expected_numbers, ordered=True): self.assertQuerysetEqual(queryset, expected_numbers, self.number_transform, ordered) def test_simple_union(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=8) qs3 = Number.objects.filter(num=5) self.assertNumbersEqual(qs1.union(qs2, qs3), [0, 1, 5, 8, 9], ordered=False) @skipUnlessDBFeature('supports_select_intersection') def test_simple_intersection(self): qs1 = Number.objects.filter(num__lte=5) qs2 = Number.objects.filter(num__gte=5) qs3 = Number.objects.filter(num__gte=4, num__lte=6) self.assertNumbersEqual(qs1.intersection(qs2, qs3), [5], ordered=False) @skipUnlessDBFeature('supports_select_intersection') def test_intersection_with_values(self): ReservedName.objects.create(name='a', order=2) qs1 = ReservedName.objects.all() reserved_name = qs1.intersection(qs1).values('name', 'order', 'id').get() self.assertEqual(reserved_name['name'], 'a') self.assertEqual(reserved_name['order'], 2) reserved_name = qs1.intersection(qs1).values_list('name', 'order', 'id').get() self.assertEqual(reserved_name[:2], ('a', 2)) @skipUnlessDBFeature('supports_select_difference') def test_simple_difference(self): qs1 = Number.objects.filter(num__lte=5) qs2 = Number.objects.filter(num__lte=4) self.assertNumbersEqual(qs1.difference(qs2), [5], ordered=False) def test_union_distinct(self): qs1 = Number.objects.all() qs2 = Number.objects.all() self.assertEqual(len(list(qs1.union(qs2, all=True))), 20) self.assertEqual(len(list(qs1.union(qs2))), 10) @skipUnlessDBFeature('supports_select_intersection') def test_intersection_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.intersection(qs2)), 0) self.assertEqual(len(qs1.intersection(qs3)), 0) self.assertEqual(len(qs2.intersection(qs1)), 0) self.assertEqual(len(qs3.intersection(qs1)), 0) self.assertEqual(len(qs2.intersection(qs2)), 0) self.assertEqual(len(qs3.intersection(qs3)), 0) @skipUnlessDBFeature('supports_select_difference') def test_difference_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.difference(qs2)), 10) self.assertEqual(len(qs1.difference(qs3)), 10) self.assertEqual(len(qs2.difference(qs1)), 0) self.assertEqual(len(qs3.difference(qs1)), 0) self.assertEqual(len(qs2.difference(qs2)), 0) self.assertEqual(len(qs3.difference(qs3)), 0) @skipUnlessDBFeature('supports_select_difference') def test_difference_with_values(self): ReservedName.objects.create(name='a', order=2) qs1 = ReservedName.objects.all() qs2 = ReservedName.objects.none() reserved_name = qs1.difference(qs2).values('name', 'order', 'id').get() self.assertEqual(reserved_name['name'], 'a') self.assertEqual(reserved_name['order'], 2) reserved_name = qs1.difference(qs2).values_list('name', 'order', 'id').get() self.assertEqual(reserved_name[:2], ('a', 2)) def test_union_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.union(qs2)), 10) self.assertEqual(len(qs2.union(qs1)), 10) self.assertEqual(len(qs1.union(qs3)), 10) self.assertEqual(len(qs3.union(qs1)), 10) self.assertEqual(len(qs2.union(qs1, qs1, qs1)), 10) self.assertEqual(len(qs2.union(qs1, qs1, all=True)), 20) self.assertEqual(len(qs2.union(qs2)), 0) self.assertEqual(len(qs3.union(qs3)), 0) def test_limits(self): qs1 = Number.objects.all() qs2 = Number.objects.all() self.assertEqual(len(list(qs1.union(qs2)[:2])), 2) def test_ordering(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=2, num__lte=3) self.assertNumbersEqual(qs1.union(qs2).order_by('-num'), [3, 2, 1, 0]) def test_ordering_by_f_expression(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=2, num__lte=3) self.assertNumbersEqual(qs1.union(qs2).order_by(F('num').desc()), [3, 2, 1, 0]) def test_union_with_values(self): ReservedName.objects.create(name='a', order=2) qs1 = ReservedName.objects.all() reserved_name = qs1.union(qs1).values('name', 'order', 'id').get() self.assertEqual(reserved_name['name'], 'a') self.assertEqual(reserved_name['order'], 2) reserved_name = qs1.union(qs1).values_list('name', 'order', 'id').get() self.assertEqual(reserved_name[:2], ('a', 2)) # List of columns can be changed. reserved_name = qs1.union(qs1).values_list('order').get() self.assertEqual(reserved_name, (2,)) def test_union_with_two_annotated_values_list(self): qs1 = Number.objects.filter(num=1).annotate( count=Value(0, IntegerField()), ).values_list('num', 'count') qs2 = Number.objects.filter(num=2).values('pk').annotate( count=F('num'), ).annotate( num=Value(1, IntegerField()), ).values_list('num', 'count') self.assertCountEqual(qs1.union(qs2), [(1, 0), (2, 1)]) def test_union_with_extra_and_values_list(self): qs1 = Number.objects.filter(num=1).extra( select={'count': 0}, ).values_list('num', 'count') qs2 = Number.objects.filter(num=2).extra(select={'count': 1}) self.assertCountEqual(qs1.union(qs2), [(1, 0), (2, 1)]) def test_union_with_values_list_on_annotated_and_unannotated(self): ReservedName.objects.create(name='rn1', order=1) qs1 = Number.objects.annotate( has_reserved_name=Exists(ReservedName.objects.filter(order=OuterRef('num'))) ).filter(has_reserved_name=True) qs2 = Number.objects.filter(num=9) self.assertCountEqual(qs1.union(qs2).values_list('num', flat=True), [1, 9]) def test_union_with_values_list_and_order(self): ReservedName.objects.bulk_create([ ReservedName(name='rn1', order=7), ReservedName(name='rn2', order=5), ReservedName(name='rn0', order=6), ReservedName(name='rn9', order=-1), ]) qs1 = ReservedName.objects.filter(order__gte=6) qs2 = ReservedName.objects.filter(order__lte=5) union_qs = qs1.union(qs2) for qs, expected_result in ( # Order by a single column. (union_qs.order_by('-pk').values_list('order', flat=True), [-1, 6, 5, 7]), (union_qs.order_by('pk').values_list('order', flat=True), [7, 5, 6, -1]), (union_qs.values_list('order', flat=True).order_by('-pk'), [-1, 6, 5, 7]), (union_qs.values_list('order', flat=True).order_by('pk'), [7, 5, 6, -1]), # Order by multiple columns. (union_qs.order_by('-name', 'pk').values_list('order', flat=True), [-1, 5, 7, 6]), (union_qs.values_list('order', flat=True).order_by('-name', 'pk'), [-1, 5, 7, 6]), ): with self.subTest(qs=qs): self.assertEqual(list(qs), expected_result) def test_count_union(self): qs1 = Number.objects.filter(num__lte=1).values('num') qs2 = Number.objects.filter(num__gte=2, num__lte=3).values('num') self.assertEqual(qs1.union(qs2).count(), 4) def test_count_union_empty_result(self): qs = Number.objects.filter(pk__in=[]) self.assertEqual(qs.union(qs).count(), 0) @skipUnlessDBFeature('supports_select_difference') def test_count_difference(self): qs1 = Number.objects.filter(num__lt=10) qs2 = Number.objects.filter(num__lt=9) self.assertEqual(qs1.difference(qs2).count(), 1) @skipUnlessDBFeature('supports_select_intersection') def test_count_intersection(self): qs1 = Number.objects.filter(num__gte=5) qs2 = Number.objects.filter(num__lte=5) self.assertEqual(qs1.intersection(qs2).count(), 1) @skipUnlessDBFeature('supports_slicing_ordering_in_compound') def test_ordering_subqueries(self): qs1 = Number.objects.order_by('num')[:2] qs2 = Number.objects.order_by('-num')[:2] self.assertNumbersEqual(qs1.union(qs2).order_by('-num')[:4], [9, 8, 1, 0]) @skipIfDBFeature('supports_slicing_ordering_in_compound') def test_unsupported_ordering_slicing_raises_db_error(self): qs1 = Number.objects.all() qs2 = Number.objects.all() msg = 'LIMIT/OFFSET not allowed in subqueries of compound statements' with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2[:10])) msg = 'ORDER BY not allowed in subqueries of compound statements' with self.assertRaisesMessage(DatabaseError, msg): list(qs1.order_by('id').union(qs2)) @skipIfDBFeature('supports_select_intersection') def test_unsupported_intersection_raises_db_error(self): qs1 = Number.objects.all() qs2 = Number.objects.all() msg = 'intersection is not supported on this database backend' with self.assertRaisesMessage(NotSupportedError, msg): list(qs1.intersection(qs2)) def test_combining_multiple_models(self): ReservedName.objects.create(name='99 little bugs', order=99) qs1 = Number.objects.filter(num=1).values_list('num', flat=True) qs2 = ReservedName.objects.values_list('order') self.assertEqual(list(qs1.union(qs2).order_by('num')), [1, 99]) def test_order_raises_on_non_selected_column(self): qs1 = Number.objects.filter().annotate( annotation=Value(1, IntegerField()), ).values('annotation', num2=F('num')) qs2 = Number.objects.filter().values('id', 'num') # Should not raise list(qs1.union(qs2).order_by('annotation')) list(qs1.union(qs2).order_by('num2')) msg = 'ORDER BY term does not match any column in the result set' # 'id' is not part of the select with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by('id')) # 'num' got realiased to num2 with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by('num')) # switched order, now 'exists' again: list(qs2.union(qs1).order_by('num')) @skipUnlessDBFeature('supports_select_difference', 'supports_select_intersection') def test_qs_with_subcompound_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.intersection(Number.objects.filter(num__gt=1)) self.assertEqual(qs1.difference(qs2).count(), 2) def test_order_by_same_type(self): qs = Number.objects.all() union = qs.union(qs) numbers = list(range(10)) self.assertNumbersEqual(union.order_by('num'), numbers) self.assertNumbersEqual(union.order_by('other_num'), reversed(numbers)) def test_unsupported_operations_on_combined_qs(self): qs = Number.objects.all() msg = 'Calling QuerySet.%s() after %s() is not supported.' combinators = ['union'] if connection.features.supports_select_difference: combinators.append('difference') if connection.features.supports_select_intersection: combinators.append('intersection') for combinator in combinators: for operation in ( 'annotate', 'defer', 'exclude', 'extra', 'filter', 'only', 'prefetch_related', 'select_related', ): with self.subTest(combinator=combinator, operation=operation): with self.assertRaisesMessage( NotSupportedError, msg % (operation, combinator), ): getattr(getattr(qs, combinator)(qs), operation)()
e6ea47177c0b9b0e94ce7fa9446b9c7b684a88f6afae34c3f82c5039f3a25673
import datetime from django.db import connection from django.test import TestCase, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from .models import DumbCategory, NonIntegerPKReturningModel, ReturningModel @skipUnlessDBFeature('can_return_columns_from_insert') class ReturningValuesTests(TestCase): def test_insert_returning(self): with CaptureQueriesContext(connection) as captured_queries: DumbCategory.objects.create() self.assertIn( 'RETURNING %s.%s' % ( connection.ops.quote_name(DumbCategory._meta.db_table), connection.ops.quote_name(DumbCategory._meta.get_field('id').column), ), captured_queries[-1]['sql'], ) def test_insert_returning_non_integer(self): obj = NonIntegerPKReturningModel.objects.create() self.assertTrue(obj.created) self.assertIsInstance(obj.created, datetime.datetime) def test_insert_returning_multiple(self): with CaptureQueriesContext(connection) as captured_queries: obj = ReturningModel.objects.create() table_name = connection.ops.quote_name(ReturningModel._meta.db_table) self.assertIn( 'RETURNING %s.%s, %s.%s' % ( table_name, connection.ops.quote_name(ReturningModel._meta.get_field('id').column), table_name, connection.ops.quote_name(ReturningModel._meta.get_field('created').column), ), captured_queries[-1]['sql'], ) self.assertTrue(obj.pk) self.assertIsInstance(obj.created, datetime.datetime) @skipUnlessDBFeature('can_return_rows_from_bulk_insert') def test_bulk_insert(self): objs = [ReturningModel(), ReturningModel(pk=2 ** 11), ReturningModel()] ReturningModel.objects.bulk_create(objs) for obj in objs: with self.subTest(obj=obj): self.assertTrue(obj.pk) self.assertIsInstance(obj.created, datetime.datetime)
77cf015fda3a3d48fb107e536e068394a9732dd1009346046e999486072668d5
from datetime import datetime from django.core.exceptions import FieldError from django.db.models import CharField, F, Q from django.db.models.expressions import SimpleCol from django.db.models.fields.related_lookups import RelatedIsNull from django.db.models.functions import Lower from django.db.models.lookups import Exact, GreaterThan, IsNull, LessThan from django.db.models.sql.query import Query from django.db.models.sql.where import OR from django.test import SimpleTestCase from django.test.utils import register_lookup from .models import Author, Item, ObjectC, Ranking class TestQuery(SimpleTestCase): def test_simple_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2)) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_simplecol_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2, name__isnull=False) | Q(num__lt=F('id'))) name_isnull_lookup, num_gt_lookup = where.children[0].children self.assertIsInstance(num_gt_lookup, GreaterThan) self.assertIsInstance(num_gt_lookup.lhs, SimpleCol) self.assertIsInstance(name_isnull_lookup, IsNull) self.assertIsInstance(name_isnull_lookup.lhs, SimpleCol) num_lt_lookup = where.children[1] self.assertIsInstance(num_lt_lookup, LessThan) self.assertIsInstance(num_lt_lookup.rhs, SimpleCol) self.assertIsInstance(num_lt_lookup.lhs, SimpleCol) def test_complex_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2) | Q(num__lt=0)) self.assertEqual(where.connector, OR) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) lookup = where.children[1] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.rhs, 0) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_multiple_fields(self): query = Query(Item) where = query.build_where(Q(modified__gt=F('created'))) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertIsInstance(lookup.rhs, SimpleCol) self.assertIsInstance(lookup.lhs, SimpleCol) self.assertEqual(lookup.rhs.target, Item._meta.get_field('created')) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_transform(self): query = Query(Author) with register_lookup(CharField, Lower): where = query.build_where(~Q(name__lower='foo')) lookup = where.children[0] self.assertIsInstance(lookup, Exact) self.assertIsInstance(lookup.lhs, Lower) self.assertIsInstance(lookup.lhs.lhs, SimpleCol) self.assertEqual(lookup.lhs.lhs.target, Author._meta.get_field('name')) def test_negated_nullable(self): query = Query(Item) where = query.build_where(~Q(modified__lt=datetime(2017, 1, 1))) self.assertTrue(where.negated) lookup = where.children[0] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) lookup = where.children[1] self.assertIsInstance(lookup, IsNull) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_foreign_key(self): query = Query(Item) msg = 'Joined field references are not permitted in this query' with self.assertRaisesMessage(FieldError, msg): query.build_where(Q(creator__num__gt=2)) def test_foreign_key_f(self): query = Query(Ranking) with self.assertRaises(FieldError): query.build_where(Q(rank__gt=F('author__num'))) def test_foreign_key_exclusive(self): query = Query(ObjectC) where = query.build_where(Q(objecta=None) | Q(objectb=None)) a_isnull = where.children[0] self.assertIsInstance(a_isnull, RelatedIsNull) self.assertIsInstance(a_isnull.lhs, SimpleCol) self.assertEqual(a_isnull.lhs.target, ObjectC._meta.get_field('objecta')) b_isnull = where.children[1] self.assertIsInstance(b_isnull, RelatedIsNull) self.assertIsInstance(b_isnull.lhs, SimpleCol) self.assertEqual(b_isnull.lhs.target, ObjectC._meta.get_field('objectb')) def test_clone_select_related(self): query = Query(Item) query.add_select_related(['creator']) clone = query.clone() clone.add_select_related(['note', 'creator__extra']) self.assertEqual(query.select_related, {'creator': {}})
470c82fe9166b721b1d837195bbbd5542b14ee4d434f306407ce3bf9b476fd6f
from unittest import mock from django.http import HttpRequest from django.template import ( Context, Engine, RequestContext, Template, Variable, VariableDoesNotExist, ) from django.template.context import RenderContext from django.test import RequestFactory, SimpleTestCase class ContextTests(SimpleTestCase): def test_context(self): c = Context({"a": 1, "b": "xyzzy"}) self.assertEqual(c["a"], 1) self.assertEqual(c.push(), {}) c["a"] = 2 self.assertEqual(c["a"], 2) self.assertEqual(c.get("a"), 2) self.assertEqual(c.pop(), {"a": 2}) self.assertEqual(c["a"], 1) self.assertEqual(c.get("foo", 42), 42) self.assertEqual(c, mock.ANY) def test_push_context_manager(self): c = Context({"a": 1}) with c.push(): c['a'] = 2 self.assertEqual(c['a'], 2) self.assertEqual(c['a'], 1) with c.push(a=3): self.assertEqual(c['a'], 3) self.assertEqual(c['a'], 1) def test_update_context_manager(self): c = Context({"a": 1}) with c.update({}): c['a'] = 2 self.assertEqual(c['a'], 2) self.assertEqual(c['a'], 1) with c.update({'a': 3}): self.assertEqual(c['a'], 3) self.assertEqual(c['a'], 1) def test_push_context_manager_with_context_object(self): c = Context({'a': 1}) with c.push(Context({'a': 3})): self.assertEqual(c['a'], 3) self.assertEqual(c['a'], 1) def test_update_context_manager_with_context_object(self): c = Context({'a': 1}) with c.update(Context({'a': 3})): self.assertEqual(c['a'], 3) self.assertEqual(c['a'], 1) def test_push_proper_layering(self): c = Context({'a': 1}) c.push(Context({'b': 2})) c.push(Context({'c': 3, 'd': {'z': '26'}})) self.assertEqual( c.dicts, [ {'False': False, 'None': None, 'True': True}, {'a': 1}, {'b': 2}, {'c': 3, 'd': {'z': '26'}}, ] ) def test_update_proper_layering(self): c = Context({'a': 1}) c.update(Context({'b': 2})) c.update(Context({'c': 3, 'd': {'z': '26'}})) self.assertEqual( c.dicts, [ {'False': False, 'None': None, 'True': True}, {'a': 1}, {'b': 2}, {'c': 3, 'd': {'z': '26'}}, ] ) def test_setdefault(self): c = Context() x = c.setdefault('x', 42) self.assertEqual(x, 42) self.assertEqual(c['x'], 42) x = c.setdefault('x', 100) self.assertEqual(x, 42) self.assertEqual(c['x'], 42) def test_resolve_on_context_method(self): """ #17778 -- Variable shouldn't resolve RequestContext methods """ empty_context = Context() with self.assertRaises(VariableDoesNotExist): Variable('no_such_variable').resolve(empty_context) with self.assertRaises(VariableDoesNotExist): Variable('new').resolve(empty_context) self.assertEqual( Variable('new').resolve(Context({'new': 'foo'})), 'foo', ) def test_render_context(self): test_context = RenderContext({'fruit': 'papaya'}) # push() limits access to the topmost dict test_context.push() test_context['vegetable'] = 'artichoke' self.assertEqual(list(test_context), ['vegetable']) self.assertNotIn('fruit', test_context) with self.assertRaises(KeyError): test_context['fruit'] self.assertIsNone(test_context.get('fruit')) def test_flatten_context(self): a = Context() a.update({'a': 2}) a.update({'b': 4}) a.update({'c': 8}) self.assertEqual(a.flatten(), { 'False': False, 'None': None, 'True': True, 'a': 2, 'b': 4, 'c': 8 }) def test_flatten_context_with_context(self): """ Context.push() with a Context argument should work. """ a = Context({'a': 2}) a.push(Context({'z': '8'})) self.assertEqual(a.flatten(), { 'False': False, 'None': None, 'True': True, 'a': 2, 'z': '8', }) def test_context_comparable(self): """ #21765 -- equality comparison should work """ test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}} self.assertEqual(Context(test_data), Context(test_data)) a = Context() b = Context() self.assertEqual(a, b) # update only a a.update({'a': 1}) self.assertNotEqual(a, b) # update both to check regression a.update({'c': 3}) b.update({'c': 3}) self.assertNotEqual(a, b) # make contexts equals again b.update({'a': 1}) self.assertEqual(a, b) def test_copy_request_context_twice(self): """ #24273 -- Copy twice shouldn't raise an exception """ RequestContext(HttpRequest()).new().new() def test_set_upward(self): c = Context({'a': 1}) c.set_upward('a', 2) self.assertEqual(c.get('a'), 2) def test_set_upward_empty_context(self): empty_context = Context() empty_context.set_upward('a', 1) self.assertEqual(empty_context.get('a'), 1) def test_set_upward_with_push(self): """ The highest context which has the given key is used. """ c = Context({'a': 1}) c.push({'a': 2}) c.set_upward('a', 3) self.assertEqual(c.get('a'), 3) c.pop() self.assertEqual(c.get('a'), 1) def test_set_upward_with_push_no_match(self): """ The highest context is used if the given key isn't found. """ c = Context({'b': 1}) c.push({'b': 2}) c.set_upward('a', 2) self.assertEqual(len(c.dicts), 3) self.assertEqual(c.dicts[-1]['a'], 2) class RequestContextTests(SimpleTestCase): request_factory = RequestFactory() def test_include_only(self): """ #15721 -- ``{% include %}`` and ``RequestContext`` should work together. """ engine = Engine(loaders=[ ('django.template.loaders.locmem.Loader', { 'child': '{{ var|default:"none" }}', }), ]) request = self.request_factory.get('/') ctx = RequestContext(request, {'var': 'parent'}) self.assertEqual(engine.from_string('{% include "child" %}').render(ctx), 'parent') self.assertEqual(engine.from_string('{% include "child" only %}').render(ctx), 'none') def test_stack_size(self): """Optimized RequestContext construction (#7116).""" request = self.request_factory.get('/') ctx = RequestContext(request, {}) # The stack contains 4 items: # [builtins, supplied context, context processor, empty dict] self.assertEqual(len(ctx.dicts), 4) def test_context_comparable(self): # Create an engine without any context processors. test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}} # test comparing RequestContext to prevent problems if somebody # adds __eq__ in the future request = self.request_factory.get('/') self.assertEqual( RequestContext(request, dict_=test_data), RequestContext(request, dict_=test_data), ) def test_modify_context_and_render(self): template = Template('{{ foo }}') request = self.request_factory.get('/') context = RequestContext(request, {}) context['foo'] = 'foo' self.assertEqual(template.render(context), 'foo')
21320cefeeb91fb38e55d63f7c9d40010cabe69454d129e5722bd2ab7fbf3f46
import datetime from unittest import skipIf, skipUnless from django.db import connection from django.db.models import Index from django.db.models.deletion import CASCADE from django.db.models.fields.related import ForeignKey from django.db.models.query_utils import Q from django.test import ( TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import override_settings from django.utils import timezone from .models import ( Article, ArticleTranslation, IndexedArticle2, IndexTogetherSingleList, ) class SchemaIndexesTests(TestCase): """ Test index handling by the db.backends.schema infrastructure. """ def test_index_name_hash(self): """ Index names should be deterministic. """ editor = connection.schema_editor() index_name = editor._create_index_name( table_name=Article._meta.db_table, column_names=("c1",), suffix="123", ) self.assertEqual(index_name, "indexes_article_c1_a52bd80b123") def test_index_name(self): """ Index names on the built-in database backends:: * Are truncated as needed. * Include all the column names. * Include a deterministic hash. """ long_name = 'l%sng' % ('o' * 100) editor = connection.schema_editor() index_name = editor._create_index_name( table_name=Article._meta.db_table, column_names=('c1', 'c2', long_name), suffix='ix', ) expected = { 'mysql': 'indexes_article_c1_c2_looooooooooooooooooo_255179b2ix', 'oracle': 'indexes_a_c1_c2_loo_255179b2ix', 'postgresql': 'indexes_article_c1_c2_loooooooooooooooooo_255179b2ix', 'sqlite': 'indexes_article_c1_c2_l%sng_255179b2ix' % ('o' * 100), } if connection.vendor not in expected: self.skipTest('This test is only supported on the built-in database backends.') self.assertEqual(index_name, expected[connection.vendor]) def test_index_together(self): editor = connection.schema_editor() index_sql = [str(statement) for statement in editor._model_indexes_sql(Article)] self.assertEqual(len(index_sql), 1) # Ensure the index name is properly quoted self.assertIn( connection.ops.quote_name( editor._create_index_name(Article._meta.db_table, ['headline', 'pub_date'], suffix='_idx') ), index_sql[0] ) def test_index_together_single_list(self): # Test for using index_together with a single list (#22172) index_sql = connection.schema_editor()._model_indexes_sql(IndexTogetherSingleList) self.assertEqual(len(index_sql), 1) @skipIf(connection.vendor == 'postgresql', 'opclasses are PostgreSQL only') class SchemaIndexesNotPostgreSQLTests(TransactionTestCase): available_apps = ['indexes'] def test_create_index_ignores_opclasses(self): index = Index( name='test_ops_class', fields=['headline'], opclasses=['varchar_pattern_ops'], ) with connection.schema_editor() as editor: # This would error if opclasses weren't ignored. editor.add_index(IndexedArticle2, index) # The `condition` parameter is ignored by databases that don't support partial # indexes. @skipIfDBFeature('supports_partial_indexes') class PartialIndexConditionIgnoredTests(TransactionTestCase): available_apps = ['indexes'] def test_condition_ignored(self): index = Index( name='test_condition_ignored', fields=['published'], condition=Q(published=True), ) with connection.schema_editor() as editor: # This would error if condition weren't ignored. editor.add_index(Article, index) self.assertNotIn( 'WHERE %s' % editor.quote_name('published'), str(index.create_sql(Article, editor)) ) @skipUnless(connection.vendor == 'postgresql', 'PostgreSQL tests') class SchemaIndexesPostgreSQLTests(TransactionTestCase): available_apps = ['indexes'] get_opclass_query = ''' SELECT opcname, c.relname FROM pg_opclass AS oc JOIN pg_index as i on oc.oid = ANY(i.indclass) JOIN pg_class as c on c.oid = i.indexrelid WHERE c.relname = '%s' ''' def test_text_indexes(self): """Test creation of PostgreSQL-specific text indexes (#12234)""" from .models import IndexedArticle index_sql = [str(statement) for statement in connection.schema_editor()._model_indexes_sql(IndexedArticle)] self.assertEqual(len(index_sql), 5) self.assertIn('("headline" varchar_pattern_ops)', index_sql[1]) self.assertIn('("body" text_pattern_ops)', index_sql[3]) # unique=True and db_index=True should only create the varchar-specific # index (#19441). self.assertIn('("slug" varchar_pattern_ops)', index_sql[4]) def test_virtual_relation_indexes(self): """Test indexes are not created for related objects""" index_sql = connection.schema_editor()._model_indexes_sql(Article) self.assertEqual(len(index_sql), 1) def test_ops_class(self): index = Index( name='test_ops_class', fields=['headline'], opclasses=['varchar_pattern_ops'], ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % 'test_ops_class') self.assertEqual(cursor.fetchall(), [('varchar_pattern_ops', 'test_ops_class')]) def test_ops_class_multiple_columns(self): index = Index( name='test_ops_class_multiple', fields=['headline', 'body'], opclasses=['varchar_pattern_ops', 'text_pattern_ops'], ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % 'test_ops_class_multiple') expected_ops_classes = ( ('varchar_pattern_ops', 'test_ops_class_multiple'), ('text_pattern_ops', 'test_ops_class_multiple'), ) self.assertCountEqual(cursor.fetchall(), expected_ops_classes) def test_ops_class_partial(self): index = Index( name='test_ops_class_partial', fields=['body'], opclasses=['text_pattern_ops'], condition=Q(headline__contains='China'), ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % 'test_ops_class_partial') self.assertCountEqual(cursor.fetchall(), [('text_pattern_ops', 'test_ops_class_partial')]) def test_ops_class_partial_tablespace(self): indexname = 'test_ops_class_tblspace' index = Index( name=indexname, fields=['body'], opclasses=['text_pattern_ops'], condition=Q(headline__contains='China'), db_tablespace='pg_default', ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) self.assertIn('TABLESPACE "pg_default" ', str(index.create_sql(IndexedArticle2, editor))) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % indexname) self.assertCountEqual(cursor.fetchall(), [('text_pattern_ops', indexname)]) @skipUnless(connection.vendor == 'mysql', 'MySQL tests') class SchemaIndexesMySQLTests(TransactionTestCase): available_apps = ['indexes'] def test_no_index_for_foreignkey(self): """ MySQL on InnoDB already creates indexes automatically for foreign keys. (#14180). An index should be created if db_constraint=False (#26171). """ storage = connection.introspection.get_storage_engine( connection.cursor(), ArticleTranslation._meta.db_table ) if storage != "InnoDB": self.skip("This test only applies to the InnoDB storage engine") index_sql = [str(statement) for statement in connection.schema_editor()._model_indexes_sql(ArticleTranslation)] self.assertEqual(index_sql, [ 'CREATE INDEX `indexes_articletranslation_article_no_constraint_id_d6c0806b` ' 'ON `indexes_articletranslation` (`article_no_constraint_id`)' ]) # The index also shouldn't be created if the ForeignKey is added after # the model was created. field_created = False try: with connection.schema_editor() as editor: new_field = ForeignKey(Article, CASCADE) new_field.set_attributes_from_name('new_foreign_key') editor.add_field(ArticleTranslation, new_field) field_created = True # No deferred SQL. The FK constraint is included in the # statement to add the field. self.assertFalse(editor.deferred_sql) finally: if field_created: with connection.schema_editor() as editor: editor.remove_field(ArticleTranslation, new_field) @skipUnlessDBFeature('supports_partial_indexes') # SQLite doesn't support timezone-aware datetimes when USE_TZ is False. @override_settings(USE_TZ=True) class PartialIndexTests(TransactionTestCase): # Schema editor is used to create the index to test that it works. available_apps = ['indexes'] def test_partial_index(self): with connection.schema_editor() as editor: index = Index( name='recent_article_idx', fields=['pub_date'], condition=Q( pub_date__gt=datetime.datetime( year=2015, month=1, day=1, # PostgreSQL would otherwise complain about the lookup # being converted to a mutable function (by removing # the timezone in the cast) which is forbidden. tzinfo=timezone.get_current_timezone(), ), ) ) self.assertIn( 'WHERE %s' % editor.quote_name('pub_date'), str(index.create_sql(Article, schema_editor=editor)) ) editor.add_index(index=index, model=Article) self.assertIn(index.name, connection.introspection.get_constraints( cursor=connection.cursor(), table_name=Article._meta.db_table, )) editor.remove_index(index=index, model=Article) def test_integer_restriction_partial(self): with connection.schema_editor() as editor: index = Index( name='recent_article_idx', fields=['id'], condition=Q(pk__gt=1), ) self.assertIn( 'WHERE %s' % editor.quote_name('id'), str(index.create_sql(Article, schema_editor=editor)) ) editor.add_index(index=index, model=Article) self.assertIn(index.name, connection.introspection.get_constraints( cursor=connection.cursor(), table_name=Article._meta.db_table, )) editor.remove_index(index=index, model=Article) def test_boolean_restriction_partial(self): with connection.schema_editor() as editor: index = Index( name='published_index', fields=['published'], condition=Q(published=True), ) self.assertIn( 'WHERE %s' % editor.quote_name('published'), str(index.create_sql(Article, schema_editor=editor)) ) editor.add_index(index=index, model=Article) self.assertIn(index.name, connection.introspection.get_constraints( cursor=connection.cursor(), table_name=Article._meta.db_table, )) editor.remove_index(index=index, model=Article) @skipUnlessDBFeature('supports_functions_in_partial_indexes') def test_multiple_conditions(self): with connection.schema_editor() as editor: index = Index( name='recent_article_idx', fields=['pub_date', 'headline'], condition=( Q(pub_date__gt=datetime.datetime( year=2015, month=1, day=1, tzinfo=timezone.get_current_timezone(), )) & Q(headline__contains='China') ), ) sql = str(index.create_sql(Article, schema_editor=editor)) where = sql.find('WHERE') self.assertIn( 'WHERE (%s' % editor.quote_name('pub_date'), sql ) # Because each backend has different syntax for the operators, # check ONLY the occurrence of headline in the SQL. self.assertGreater(sql.rfind('headline'), where) editor.add_index(index=index, model=Article) self.assertIn(index.name, connection.introspection.get_constraints( cursor=connection.cursor(), table_name=Article._meta.db_table, )) editor.remove_index(index=index, model=Article) def test_is_null_condition(self): with connection.schema_editor() as editor: index = Index( name='recent_article_idx', fields=['pub_date'], condition=Q(pub_date__isnull=False), ) self.assertIn( 'WHERE %s IS NOT NULL' % editor.quote_name('pub_date'), str(index.create_sql(Article, schema_editor=editor)) ) editor.add_index(index=index, model=Article) self.assertIn(index.name, connection.introspection.get_constraints( cursor=connection.cursor(), table_name=Article._meta.db_table, )) editor.remove_index(index=index, model=Article)
83ff6300e212c8043999e2e35095e430a697185ec073b3079a3b7aa759c336b2
from datetime import date, datetime from operator import attrgetter from django.db import IntegrityError from django.test import TestCase from .models import ( CustomMembership, Employee, Event, Friendship, Group, Ingredient, Invitation, Membership, Person, PersonSelfRefM2M, Recipe, RecipeIngredient, Relationship, SymmetricalFriendship, ) class M2mThroughTests(TestCase): @classmethod def setUpTestData(cls): cls.bob = Person.objects.create(name='Bob') cls.jim = Person.objects.create(name='Jim') cls.jane = Person.objects.create(name='Jane') cls.rock = Group.objects.create(name='Rock') cls.roll = Group.objects.create(name='Roll') def test_retrieve_intermediate_items(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock) expected = ['Jane', 'Jim'] self.assertQuerysetEqual( self.rock.members.all(), expected, attrgetter("name") ) def test_get_on_intermediate_model(self): Membership.objects.create(person=self.jane, group=self.rock) queryset = Membership.objects.get(person=self.jane, group=self.rock) self.assertEqual( repr(queryset), '<Membership: Jane is a member of Rock>' ) def test_filter_on_intermediate_model(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock) queryset = Membership.objects.filter(group=self.rock) expected = [ '<Membership: Jim is a member of Rock>', '<Membership: Jane is a member of Rock>', ] self.assertQuerysetEqual( queryset, expected ) def test_add_on_m2m_with_intermediate_model(self): self.rock.members.add(self.bob, through_defaults={'invite_reason': 'He is good.'}) self.assertSequenceEqual(self.rock.members.all(), [self.bob]) self.assertEqual(self.rock.membership_set.get().invite_reason, 'He is good.') def test_add_on_m2m_with_intermediate_model_value_required(self): self.rock.nodefaultsnonulls.add(self.jim, through_defaults={'nodefaultnonull': 1}) self.assertEqual(self.rock.testnodefaultsornulls_set.get().nodefaultnonull, 1) def test_add_on_m2m_with_intermediate_model_value_required_fails(self): with self.assertRaises(IntegrityError): self.rock.nodefaultsnonulls.add(self.jim) def test_create_on_m2m_with_intermediate_model(self): annie = self.rock.members.create(name='Annie', through_defaults={'invite_reason': 'She was just awesome.'}) self.assertSequenceEqual(self.rock.members.all(), [annie]) self.assertEqual(self.rock.membership_set.get().invite_reason, 'She was just awesome.') def test_create_on_m2m_with_intermediate_model_value_required(self): self.rock.nodefaultsnonulls.create(name='Test', through_defaults={'nodefaultnonull': 1}) self.assertEqual(self.rock.testnodefaultsornulls_set.get().nodefaultnonull, 1) def test_create_on_m2m_with_intermediate_model_value_required_fails(self): with self.assertRaises(IntegrityError): self.rock.nodefaultsnonulls.create(name='Test') def test_get_or_create_on_m2m_with_intermediate_model_value_required(self): self.rock.nodefaultsnonulls.get_or_create(name='Test', through_defaults={'nodefaultnonull': 1}) self.assertEqual(self.rock.testnodefaultsornulls_set.get().nodefaultnonull, 1) def test_get_or_create_on_m2m_with_intermediate_model_value_required_fails(self): with self.assertRaises(IntegrityError): self.rock.nodefaultsnonulls.get_or_create(name='Test') def test_update_or_create_on_m2m_with_intermediate_model_value_required(self): self.rock.nodefaultsnonulls.update_or_create(name='Test', through_defaults={'nodefaultnonull': 1}) self.assertEqual(self.rock.testnodefaultsornulls_set.get().nodefaultnonull, 1) def test_update_or_create_on_m2m_with_intermediate_model_value_required_fails(self): with self.assertRaises(IntegrityError): self.rock.nodefaultsnonulls.update_or_create(name='Test') def test_remove_on_m2m_with_intermediate_model(self): Membership.objects.create(person=self.jim, group=self.rock) self.rock.members.remove(self.jim) self.assertSequenceEqual(self.rock.members.all(), []) def test_remove_on_m2m_with_intermediate_model_multiple(self): Membership.objects.create(person=self.jim, group=self.rock, invite_reason='1') Membership.objects.create(person=self.jim, group=self.rock, invite_reason='2') self.assertSequenceEqual(self.rock.members.all(), [self.jim, self.jim]) self.rock.members.remove(self.jim) self.assertSequenceEqual(self.rock.members.all(), []) def test_set_on_m2m_with_intermediate_model(self): members = list(Person.objects.filter(name__in=['Bob', 'Jim'])) self.rock.members.set(members) self.assertSequenceEqual(self.rock.members.all(), [self.bob, self.jim]) def test_set_on_m2m_with_intermediate_model_value_required(self): self.rock.nodefaultsnonulls.set([self.jim], through_defaults={'nodefaultnonull': 1}) self.assertEqual(self.rock.testnodefaultsornulls_set.get().nodefaultnonull, 1) self.rock.nodefaultsnonulls.set([self.jim], through_defaults={'nodefaultnonull': 2}) self.assertEqual(self.rock.testnodefaultsornulls_set.get().nodefaultnonull, 1) self.rock.nodefaultsnonulls.set([self.jim], through_defaults={'nodefaultnonull': 2}, clear=True) self.assertEqual(self.rock.testnodefaultsornulls_set.get().nodefaultnonull, 2) def test_set_on_m2m_with_intermediate_model_value_required_fails(self): with self.assertRaises(IntegrityError): self.rock.nodefaultsnonulls.set([self.jim]) def test_clear_removes_all_the_m2m_relationships(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock) self.rock.members.clear() self.assertQuerysetEqual( self.rock.members.all(), [] ) def test_retrieve_reverse_intermediate_items(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jim, group=self.roll) expected = ['Rock', 'Roll'] self.assertQuerysetEqual( self.jim.group_set.all(), expected, attrgetter("name") ) def test_add_on_reverse_m2m_with_intermediate_model(self): self.bob.group_set.add(self.rock) self.assertSequenceEqual(self.bob.group_set.all(), [self.rock]) def test_create_on_reverse_m2m_with_intermediate_model(self): funk = self.bob.group_set.create(name='Funk') self.assertSequenceEqual(self.bob.group_set.all(), [funk]) def test_remove_on_reverse_m2m_with_intermediate_model(self): Membership.objects.create(person=self.bob, group=self.rock) self.bob.group_set.remove(self.rock) self.assertSequenceEqual(self.bob.group_set.all(), []) def test_set_on_reverse_m2m_with_intermediate_model(self): members = list(Group.objects.filter(name__in=['Rock', 'Roll'])) self.bob.group_set.set(members) self.assertSequenceEqual(self.bob.group_set.all(), [self.rock, self.roll]) def test_clear_on_reverse_removes_all_the_m2m_relationships(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jim, group=self.roll) self.jim.group_set.clear() self.assertQuerysetEqual( self.jim.group_set.all(), [] ) def test_query_model_by_attribute_name_of_related_model(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock) Membership.objects.create(person=self.bob, group=self.roll) Membership.objects.create(person=self.jim, group=self.roll) Membership.objects.create(person=self.jane, group=self.roll) self.assertQuerysetEqual( Group.objects.filter(members__name='Bob'), ['Roll'], attrgetter("name") ) def test_order_by_relational_field_through_model(self): CustomMembership.objects.create(person=self.jim, group=self.rock) CustomMembership.objects.create(person=self.bob, group=self.rock) CustomMembership.objects.create(person=self.jane, group=self.roll) CustomMembership.objects.create(person=self.jim, group=self.roll) self.assertSequenceEqual( self.rock.custom_members.order_by('custom_person_related_name'), [self.jim, self.bob] ) self.assertSequenceEqual( self.roll.custom_members.order_by('custom_person_related_name'), [self.jane, self.jim] ) def test_query_first_model_by_intermediate_model_attribute(self): Membership.objects.create( person=self.jane, group=self.roll, invite_reason="She was just awesome." ) Membership.objects.create( person=self.jim, group=self.roll, invite_reason="He is good." ) Membership.objects.create(person=self.bob, group=self.roll) qs = Group.objects.filter( membership__invite_reason="She was just awesome." ) self.assertQuerysetEqual( qs, ['Roll'], attrgetter("name") ) def test_query_second_model_by_intermediate_model_attribute(self): Membership.objects.create( person=self.jane, group=self.roll, invite_reason="She was just awesome." ) Membership.objects.create( person=self.jim, group=self.roll, invite_reason="He is good." ) Membership.objects.create(person=self.bob, group=self.roll) qs = Person.objects.filter( membership__invite_reason="She was just awesome." ) self.assertQuerysetEqual( qs, ['Jane'], attrgetter("name") ) def test_query_model_by_related_model_name(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock) Membership.objects.create(person=self.bob, group=self.roll) Membership.objects.create(person=self.jim, group=self.roll) Membership.objects.create(person=self.jane, group=self.roll) self.assertQuerysetEqual( Person.objects.filter(group__name="Rock"), ['Jane', 'Jim'], attrgetter("name") ) def test_query_model_by_custom_related_name(self): CustomMembership.objects.create(person=self.bob, group=self.rock) CustomMembership.objects.create(person=self.jim, group=self.rock) self.assertQuerysetEqual( Person.objects.filter(custom__name="Rock"), ['Bob', 'Jim'], attrgetter("name") ) def test_query_model_by_intermediate_can_return_non_unique_queryset(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create( person=self.jane, group=self.rock, date_joined=datetime(2006, 1, 1) ) Membership.objects.create( person=self.bob, group=self.roll, date_joined=datetime(2004, 1, 1)) Membership.objects.create(person=self.jim, group=self.roll) Membership.objects.create( person=self.jane, group=self.roll, date_joined=datetime(2004, 1, 1)) qs = Person.objects.filter( membership__date_joined__gt=datetime(2004, 1, 1) ) self.assertQuerysetEqual( qs, ['Jane', 'Jim', 'Jim'], attrgetter("name") ) def test_custom_related_name_forward_empty_qs(self): self.assertQuerysetEqual( self.rock.custom_members.all(), [] ) def test_custom_related_name_reverse_empty_qs(self): self.assertQuerysetEqual( self.bob.custom.all(), [] ) def test_custom_related_name_forward_non_empty_qs(self): CustomMembership.objects.create(person=self.bob, group=self.rock) CustomMembership.objects.create(person=self.jim, group=self.rock) self.assertQuerysetEqual( self.rock.custom_members.all(), ['Bob', 'Jim'], attrgetter("name") ) def test_custom_related_name_reverse_non_empty_qs(self): CustomMembership.objects.create(person=self.bob, group=self.rock) CustomMembership.objects.create(person=self.jim, group=self.rock) self.assertQuerysetEqual( self.bob.custom.all(), ['Rock'], attrgetter("name") ) def test_custom_related_name_doesnt_conflict_with_fky_related_name(self): CustomMembership.objects.create(person=self.bob, group=self.rock) self.assertQuerysetEqual( self.bob.custom_person_related_name.all(), ['<CustomMembership: Bob is a member of Rock>'] ) def test_through_fields(self): """ Relations with intermediary tables with multiple FKs to the M2M's ``to`` model are possible. """ event = Event.objects.create(title='Rockwhale 2014') Invitation.objects.create(event=event, inviter=self.bob, invitee=self.jim) Invitation.objects.create(event=event, inviter=self.bob, invitee=self.jane) self.assertQuerysetEqual( event.invitees.all(), ['Jane', 'Jim'], attrgetter('name') ) class M2mThroughReferentialTests(TestCase): def test_self_referential_empty_qs(self): tony = PersonSelfRefM2M.objects.create(name="Tony") self.assertQuerysetEqual( tony.friends.all(), [] ) def test_self_referential_non_symmetrical_first_side(self): tony = PersonSelfRefM2M.objects.create(name="Tony") chris = PersonSelfRefM2M.objects.create(name="Chris") Friendship.objects.create( first=tony, second=chris, date_friended=datetime.now() ) self.assertQuerysetEqual( tony.friends.all(), ['Chris'], attrgetter("name") ) def test_self_referential_non_symmetrical_second_side(self): tony = PersonSelfRefM2M.objects.create(name="Tony") chris = PersonSelfRefM2M.objects.create(name="Chris") Friendship.objects.create( first=tony, second=chris, date_friended=datetime.now() ) self.assertQuerysetEqual( chris.friends.all(), [] ) def test_self_referential_non_symmetrical_clear_first_side(self): tony = PersonSelfRefM2M.objects.create(name="Tony") chris = PersonSelfRefM2M.objects.create(name="Chris") Friendship.objects.create( first=tony, second=chris, date_friended=datetime.now() ) chris.friends.clear() self.assertQuerysetEqual( chris.friends.all(), [] ) # Since this isn't a symmetrical relation, Tony's friend link still exists. self.assertQuerysetEqual( tony.friends.all(), ['Chris'], attrgetter("name") ) def test_self_referential_non_symmetrical_both(self): tony = PersonSelfRefM2M.objects.create(name="Tony") chris = PersonSelfRefM2M.objects.create(name="Chris") Friendship.objects.create( first=tony, second=chris, date_friended=datetime.now() ) Friendship.objects.create( first=chris, second=tony, date_friended=datetime.now() ) self.assertQuerysetEqual( tony.friends.all(), ['Chris'], attrgetter("name") ) self.assertQuerysetEqual( chris.friends.all(), ['Tony'], attrgetter("name") ) def test_through_fields_self_referential(self): john = Employee.objects.create(name='john') peter = Employee.objects.create(name='peter') mary = Employee.objects.create(name='mary') harry = Employee.objects.create(name='harry') Relationship.objects.create(source=john, target=peter, another=None) Relationship.objects.create(source=john, target=mary, another=None) Relationship.objects.create(source=john, target=harry, another=peter) self.assertQuerysetEqual( john.subordinates.all(), ['peter', 'mary', 'harry'], attrgetter('name') ) def test_self_referential_symmetrical(self): tony = PersonSelfRefM2M.objects.create(name='Tony') chris = PersonSelfRefM2M.objects.create(name='Chris') SymmetricalFriendship.objects.create( first=tony, second=chris, date_friended=date.today(), ) self.assertSequenceEqual(tony.sym_friends.all(), [chris]) # Manually created symmetrical m2m relation doesn't add mirror entry # automatically. self.assertSequenceEqual(chris.sym_friends.all(), []) SymmetricalFriendship.objects.create( first=chris, second=tony, date_friended=date.today() ) self.assertSequenceEqual(chris.sym_friends.all(), [tony]) def test_add_on_symmetrical_m2m_with_intermediate_model(self): tony = PersonSelfRefM2M.objects.create(name='Tony') chris = PersonSelfRefM2M.objects.create(name='Chris') date_friended = date(2017, 1, 3) tony.sym_friends.add(chris, through_defaults={'date_friended': date_friended}) self.assertSequenceEqual(tony.sym_friends.all(), [chris]) self.assertSequenceEqual(chris.sym_friends.all(), [tony]) friendship = tony.symmetricalfriendship_set.get() self.assertEqual(friendship.date_friended, date_friended) def test_set_on_symmetrical_m2m_with_intermediate_model(self): tony = PersonSelfRefM2M.objects.create(name='Tony') chris = PersonSelfRefM2M.objects.create(name='Chris') anne = PersonSelfRefM2M.objects.create(name='Anne') kate = PersonSelfRefM2M.objects.create(name='Kate') date_friended_add = date(2013, 1, 5) date_friended_set = date.today() tony.sym_friends.add( anne, chris, through_defaults={'date_friended': date_friended_add}, ) tony.sym_friends.set( [anne, kate], through_defaults={'date_friended': date_friended_set}, ) self.assertSequenceEqual(tony.sym_friends.all(), [anne, kate]) self.assertSequenceEqual(anne.sym_friends.all(), [tony]) self.assertSequenceEqual(kate.sym_friends.all(), [tony]) self.assertEqual( kate.symmetricalfriendship_set.get().date_friended, date_friended_set, ) # Date is preserved. self.assertEqual( anne.symmetricalfriendship_set.get().date_friended, date_friended_add, ) # Recreate relationship. tony.sym_friends.set( [anne], clear=True, through_defaults={'date_friended': date_friended_set}, ) self.assertSequenceEqual(tony.sym_friends.all(), [anne]) self.assertSequenceEqual(anne.sym_friends.all(), [tony]) self.assertEqual( anne.symmetricalfriendship_set.get().date_friended, date_friended_set, ) class M2mThroughToFieldsTests(TestCase): @classmethod def setUpTestData(cls): cls.pea = Ingredient.objects.create(iname='pea') cls.potato = Ingredient.objects.create(iname='potato') cls.tomato = Ingredient.objects.create(iname='tomato') cls.curry = Recipe.objects.create(rname='curry') RecipeIngredient.objects.create(recipe=cls.curry, ingredient=cls.potato) RecipeIngredient.objects.create(recipe=cls.curry, ingredient=cls.pea) RecipeIngredient.objects.create(recipe=cls.curry, ingredient=cls.tomato) def test_retrieval(self): # Forward retrieval self.assertSequenceEqual(self.curry.ingredients.all(), [self.pea, self.potato, self.tomato]) # Backward retrieval self.assertEqual(self.tomato.recipes.get(), self.curry) def test_choices(self): field = Recipe._meta.get_field('ingredients') self.assertEqual( [choice[0] for choice in field.get_choices(include_blank=False)], ['pea', 'potato', 'tomato'] )
76e46ae01d9bff51dc912507f0d3f7be85c674368cbae72b19be351678199505
from datetime import datetime from django.db import models # M2M described on one of the models class Person(models.Model): name = models.CharField(max_length=128) class Meta: ordering = ('name',) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') custom_members = models.ManyToManyField(Person, through='CustomMembership', related_name="custom") nodefaultsnonulls = models.ManyToManyField( Person, through='TestNoDefaultsOrNulls', related_name="testnodefaultsnonulls", ) class Meta: ordering = ('name',) def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, models.CASCADE) group = models.ForeignKey(Group, models.CASCADE) date_joined = models.DateTimeField(default=datetime.now) invite_reason = models.CharField(max_length=64, null=True) class Meta: ordering = ('date_joined', 'invite_reason', 'group') def __str__(self): return "%s is a member of %s" % (self.person.name, self.group.name) class CustomMembership(models.Model): person = models.ForeignKey( Person, models.CASCADE, db_column="custom_person_column", related_name="custom_person_related_name", ) group = models.ForeignKey(Group, models.CASCADE) weird_fk = models.ForeignKey(Membership, models.SET_NULL, null=True) date_joined = models.DateTimeField(default=datetime.now) class Meta: db_table = "test_table" ordering = ["date_joined"] def __str__(self): return "%s is a member of %s" % (self.person.name, self.group.name) class TestNoDefaultsOrNulls(models.Model): person = models.ForeignKey(Person, models.CASCADE) group = models.ForeignKey(Group, models.CASCADE) nodefaultnonull = models.IntegerField() class PersonSelfRefM2M(models.Model): name = models.CharField(max_length=5) friends = models.ManyToManyField('self', through="Friendship", symmetrical=False) sym_friends = models.ManyToManyField('self', through='SymmetricalFriendship', symmetrical=True) def __str__(self): return self.name class Friendship(models.Model): first = models.ForeignKey(PersonSelfRefM2M, models.CASCADE, related_name="rel_from_set") second = models.ForeignKey(PersonSelfRefM2M, models.CASCADE, related_name="rel_to_set") date_friended = models.DateTimeField() class SymmetricalFriendship(models.Model): first = models.ForeignKey(PersonSelfRefM2M, models.CASCADE) second = models.ForeignKey(PersonSelfRefM2M, models.CASCADE, related_name='+') date_friended = models.DateField() # Custom through link fields class Event(models.Model): title = models.CharField(max_length=50) invitees = models.ManyToManyField( Person, through='Invitation', through_fields=('event', 'invitee'), related_name='events_invited', ) def __str__(self): return self.title class Invitation(models.Model): event = models.ForeignKey(Event, models.CASCADE, related_name='invitations') # field order is deliberately inverted. the target field is "invitee". inviter = models.ForeignKey(Person, models.CASCADE, related_name='invitations_sent') invitee = models.ForeignKey(Person, models.CASCADE, related_name='invitations') class Employee(models.Model): name = models.CharField(max_length=5) subordinates = models.ManyToManyField( 'self', through="Relationship", through_fields=('source', 'target'), symmetrical=False, ) class Meta: ordering = ('pk',) def __str__(self): return self.name class Relationship(models.Model): # field order is deliberately inverted. another = models.ForeignKey(Employee, models.SET_NULL, related_name="rel_another_set", null=True) target = models.ForeignKey(Employee, models.CASCADE, related_name="rel_target_set") source = models.ForeignKey(Employee, models.CASCADE, related_name="rel_source_set") class Ingredient(models.Model): iname = models.CharField(max_length=20, unique=True) class Meta: ordering = ('iname',) class Recipe(models.Model): rname = models.CharField(max_length=20, unique=True) ingredients = models.ManyToManyField( Ingredient, through='RecipeIngredient', related_name='recipes', ) class Meta: ordering = ('rname',) class RecipeIngredient(models.Model): ingredient = models.ForeignKey(Ingredient, models.CASCADE, to_field='iname') recipe = models.ForeignKey(Recipe, models.CASCADE, to_field='rname')
4d714a5cbec281e87d4d352c25e7003dd7194c75062d144a179b9d4958142e39
import datetime from copy import deepcopy from django.core.exceptions import FieldError, MultipleObjectsReturned from django.db import models, transaction from django.db.utils import IntegrityError from django.test import TestCase from django.utils.translation import gettext_lazy from .models import ( Article, Category, Child, ChildNullableParent, City, Country, District, First, Parent, Record, Relation, Reporter, School, Student, Third, ToFieldChild, ) class ManyToOneTests(TestCase): def setUp(self): # Create a few Reporters. self.r = Reporter(first_name='John', last_name='Smith', email='[email protected]') self.r.save() self.r2 = Reporter(first_name='Paul', last_name='Jones', email='[email protected]') self.r2.save() # Create an Article. self.a = Article(headline="This is a test", pub_date=datetime.date(2005, 7, 27), reporter=self.r) self.a.save() def test_get(self): # Article objects have access to their related Reporter objects. r = self.a.reporter self.assertEqual(r.id, self.r.id) self.assertEqual((r.first_name, self.r.last_name), ('John', 'Smith')) def test_create(self): # You can also instantiate an Article by passing the Reporter's ID # instead of a Reporter object. a3 = Article(headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id) a3.save() self.assertEqual(a3.reporter.id, self.r.id) # Similarly, the reporter ID can be a string. a4 = Article(headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id)) a4.save() self.assertEqual(repr(a4.reporter), "<Reporter: John Smith>") def test_add(self): # Create an Article via the Reporter object. new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29)) self.assertEqual(repr(new_article), "<Article: John's second story>") self.assertEqual(new_article.reporter.id, self.r.id) # Create a new article, and add it to the article set. new_article2 = Article(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) msg = "<Article: Paul's story> instance isn't saved. Use bulk=False or save the object first." with self.assertRaisesMessage(ValueError, msg): self.r.article_set.add(new_article2) self.r.article_set.add(new_article2, bulk=False) self.assertEqual(new_article2.reporter.id, self.r.id) self.assertQuerysetEqual( self.r.article_set.all(), ["<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>"] ) # Add the same article to a different article set - check that it moves. self.r2.article_set.add(new_article2) self.assertEqual(new_article2.reporter.id, self.r2.id) self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"]) # Adding an object of the wrong type raises TypeError. with transaction.atomic(): with self.assertRaisesMessage(TypeError, "'Article' instance expected, got <Reporter:"): self.r.article_set.add(self.r2) self.assertQuerysetEqual( self.r.article_set.all(), ["<Article: John's second story>", "<Article: This is a test>"] ) def test_set(self): new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29)) new_article2 = self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) # Assign the article to the reporter. new_article2.reporter = self.r new_article2.save() self.assertEqual(repr(new_article2.reporter), "<Reporter: John Smith>") self.assertEqual(new_article2.reporter.id, self.r.id) self.assertQuerysetEqual(self.r.article_set.all(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) self.assertQuerysetEqual(self.r2.article_set.all(), []) # Set the article back again. self.r2.article_set.set([new_article, new_article2]) self.assertQuerysetEqual(self.r.article_set.all(), ["<Article: This is a test>"]) self.assertQuerysetEqual( self.r2.article_set.all(), ["<Article: John's second story>", "<Article: Paul's story>"] ) # Funny case - because the ForeignKey cannot be null, # existing members of the set must remain. self.r.article_set.set([new_article]) self.assertQuerysetEqual( self.r.article_set.all(), ["<Article: John's second story>", "<Article: This is a test>"] ) self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"]) def test_reverse_assignment_deprecation(self): msg = ( "Direct assignment to the reverse side of a related set is " "prohibited. Use article_set.set() instead." ) with self.assertRaisesMessage(TypeError, msg): self.r2.article_set = [] def test_assign(self): new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29)) new_article2 = self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) # Assign the article to the reporter directly using the descriptor. new_article2.reporter = self.r new_article2.save() self.assertEqual(repr(new_article2.reporter), "<Reporter: John Smith>") self.assertEqual(new_article2.reporter.id, self.r.id) self.assertQuerysetEqual(self.r.article_set.all(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) self.assertQuerysetEqual(self.r2.article_set.all(), []) # Set the article back again using set() method. self.r2.article_set.set([new_article, new_article2]) self.assertQuerysetEqual(self.r.article_set.all(), ["<Article: This is a test>"]) self.assertQuerysetEqual( self.r2.article_set.all(), ["<Article: John's second story>", "<Article: Paul's story>"] ) # Because the ForeignKey cannot be null, existing members of the set # must remain. self.r.article_set.set([new_article]) self.assertQuerysetEqual( self.r.article_set.all(), ["<Article: John's second story>", "<Article: This is a test>"] ) self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"]) # Reporter cannot be null - there should not be a clear or remove method self.assertFalse(hasattr(self.r2.article_set, 'remove')) self.assertFalse(hasattr(self.r2.article_set, 'clear')) def test_assign_fk_id_value(self): parent = Parent.objects.create(name='jeff') child1 = Child.objects.create(name='frank', parent=parent) child2 = Child.objects.create(name='randy', parent=parent) parent.bestchild = child1 parent.save() parent.bestchild_id = child2.pk parent.save() self.assertEqual(parent.bestchild_id, child2.pk) self.assertFalse(Parent.bestchild.is_cached(parent)) self.assertEqual(parent.bestchild, child2) self.assertTrue(Parent.bestchild.is_cached(parent)) # Reassigning the same value doesn't clear cached instance. parent.bestchild_id = child2.pk self.assertTrue(Parent.bestchild.is_cached(parent)) def test_assign_fk_id_none(self): parent = Parent.objects.create(name='jeff') child = Child.objects.create(name='frank', parent=parent) parent.bestchild = child parent.save() parent.bestchild_id = None parent.save() self.assertIsNone(parent.bestchild_id) self.assertFalse(Parent.bestchild.is_cached(parent)) self.assertIsNone(parent.bestchild) self.assertTrue(Parent.bestchild.is_cached(parent)) def test_selects(self): self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29)) self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) # Reporter objects have access to their related Article objects. self.assertQuerysetEqual(self.r.article_set.all(), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual(self.r.article_set.filter(headline__startswith='This'), ["<Article: This is a test>"]) self.assertEqual(self.r.article_set.count(), 2) self.assertEqual(self.r2.article_set.count(), 1) # Get articles by id self.assertQuerysetEqual(Article.objects.filter(id__exact=self.a.id), ["<Article: This is a test>"]) self.assertQuerysetEqual(Article.objects.filter(pk=self.a.id), ["<Article: This is a test>"]) # Query on an article property self.assertQuerysetEqual(Article.objects.filter(headline__startswith='This'), ["<Article: This is a test>"]) # The API automatically follows relationships as far as you need. # Use double underscores to separate relationships. # This works as many levels deep as you want. There's no limit. # Find all Articles for any Reporter whose first name is "John". self.assertQuerysetEqual( Article.objects.filter(reporter__first_name__exact='John'), ["<Article: John's second story>", "<Article: This is a test>"] ) # Implied __exact also works self.assertQuerysetEqual( Article.objects.filter(reporter__first_name='John'), ["<Article: John's second story>", "<Article: This is a test>"] ) # Query twice over the related field. self.assertQuerysetEqual( Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith'), ["<Article: John's second story>", "<Article: This is a test>"] ) # The underlying query only makes one join when a related table is referenced twice. queryset = Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith') self.assertNumQueries(1, list, queryset) self.assertEqual(queryset.query.get_compiler(queryset.db).as_sql()[0].count('INNER JOIN'), 1) # The automatically joined table has a predictable name. self.assertQuerysetEqual( Article.objects.filter(reporter__first_name__exact='John').extra( where=["many_to_one_reporter.last_name='Smith'"]), ["<Article: John's second story>", "<Article: This is a test>"] ) # ... and should work fine with the string that comes out of forms.Form.cleaned_data self.assertQuerysetEqual( (Article.objects .filter(reporter__first_name__exact='John') .extra(where=["many_to_one_reporter.last_name='%s'" % 'Smith'])), ["<Article: John's second story>", "<Article: This is a test>"] ) # Find all Articles for a Reporter. # Use direct ID check, pk check, and object comparison self.assertQuerysetEqual( Article.objects.filter(reporter__id__exact=self.r.id), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter__pk=self.r.id), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter=self.r.id), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter=self.r), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter__in=[self.r.id, self.r2.id]).distinct(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter__in=[self.r, self.r2]).distinct(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) # You can also use a queryset instead of a literal list of instances. # The queryset must be reduced to a list of values using values(), # then converted into a query self.assertQuerysetEqual( Article.objects.filter( reporter__in=Reporter.objects.filter(first_name='John').values('pk').query ).distinct(), [ "<Article: John's second story>", "<Article: This is a test>", ]) def test_reverse_selects(self): a3 = Article.objects.create( headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id, ) Article.objects.create( headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id, ) john_smith = ["<Reporter: John Smith>"] # Reporters can be queried self.assertQuerysetEqual(Reporter.objects.filter(id__exact=self.r.id), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(pk=self.r.id), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(first_name__startswith='John'), john_smith) # Reporters can query in opposite direction of ForeignKey definition self.assertQuerysetEqual(Reporter.objects.filter(article__id__exact=self.a.id), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article__pk=self.a.id), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article=self.a.id), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article=self.a), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article__in=[self.a.id, a3.id]).distinct(), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article__in=[self.a.id, a3]).distinct(), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article__in=[self.a, a3]).distinct(), john_smith) self.assertQuerysetEqual( Reporter.objects.filter(article__headline__startswith='T'), ["<Reporter: John Smith>", "<Reporter: John Smith>"], ordered=False ) self.assertQuerysetEqual(Reporter.objects.filter(article__headline__startswith='T').distinct(), john_smith) # Counting in the opposite direction works in conjunction with distinct() self.assertEqual(Reporter.objects.filter(article__headline__startswith='T').count(), 2) self.assertEqual(Reporter.objects.filter(article__headline__startswith='T').distinct().count(), 1) # Queries can go round in circles. self.assertQuerysetEqual( Reporter.objects.filter(article__reporter__first_name__startswith='John'), [ "<Reporter: John Smith>", "<Reporter: John Smith>", "<Reporter: John Smith>", ], ordered=False ) self.assertQuerysetEqual( Reporter.objects.filter(article__reporter__first_name__startswith='John').distinct(), john_smith ) self.assertQuerysetEqual(Reporter.objects.filter(article__reporter__exact=self.r).distinct(), john_smith) # Implied __exact also works. self.assertQuerysetEqual(Reporter.objects.filter(article__reporter=self.r).distinct(), john_smith) # It's possible to use values() calls across many-to-one relations. # (Note, too, that we clear the ordering here so as not to drag the # 'headline' field into the columns being used to determine uniqueness) d = {'reporter__first_name': 'John', 'reporter__last_name': 'Smith'} qs = Article.objects.filter( reporter=self.r, ).distinct().order_by().values('reporter__first_name', 'reporter__last_name') self.assertEqual([d], list(qs)) def test_select_related(self): # Article.objects.select_related().dates() works properly when there # are multiple Articles with the same date but different foreign-key # objects (Reporters). r1 = Reporter.objects.create(first_name='Mike', last_name='Royko', email='[email protected]') r2 = Reporter.objects.create(first_name='John', last_name='Kass', email='[email protected]') Article.objects.create(headline='First', pub_date=datetime.date(1980, 4, 23), reporter=r1) Article.objects.create(headline='Second', pub_date=datetime.date(1980, 4, 23), reporter=r2) self.assertEqual( list(Article.objects.select_related().dates('pub_date', 'day')), [datetime.date(1980, 4, 23), datetime.date(2005, 7, 27)] ) self.assertEqual( list(Article.objects.select_related().dates('pub_date', 'month')), [datetime.date(1980, 4, 1), datetime.date(2005, 7, 1)] ) self.assertEqual( list(Article.objects.select_related().dates('pub_date', 'year')), [datetime.date(1980, 1, 1), datetime.date(2005, 1, 1)] ) def test_delete(self): self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29)) self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) Article.objects.create(headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id) Article.objects.create( headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id), ) # If you delete a reporter, his articles will be deleted. self.assertQuerysetEqual( Article.objects.all(), [ "<Article: Fourth article>", "<Article: John's second story>", "<Article: Paul's story>", "<Article: Third article>", "<Article: This is a test>", ] ) self.assertQuerysetEqual( Reporter.objects.order_by('first_name'), ["<Reporter: John Smith>", "<Reporter: Paul Jones>"] ) self.r2.delete() self.assertQuerysetEqual( Article.objects.all(), [ "<Article: Fourth article>", "<Article: John's second story>", "<Article: Third article>", "<Article: This is a test>", ] ) self.assertQuerysetEqual(Reporter.objects.order_by('first_name'), ["<Reporter: John Smith>"]) # You can delete using a JOIN in the query. Reporter.objects.filter(article__headline__startswith='This').delete() self.assertQuerysetEqual(Reporter.objects.all(), []) self.assertQuerysetEqual(Article.objects.all(), []) def test_explicit_fk(self): # Create a new Article with get_or_create using an explicit value # for a ForeignKey. a2, created = Article.objects.get_or_create( headline="John's second test", pub_date=datetime.date(2011, 5, 7), reporter_id=self.r.id, ) self.assertTrue(created) self.assertEqual(a2.reporter.id, self.r.id) # You can specify filters containing the explicit FK value. self.assertQuerysetEqual( Article.objects.filter(reporter_id__exact=self.r.id), ["<Article: John's second test>", "<Article: This is a test>"] ) # Create an Article by Paul for the same date. a3 = Article.objects.create( headline="Paul's commentary", pub_date=datetime.date(2011, 5, 7), reporter_id=self.r2.id, ) self.assertEqual(a3.reporter.id, self.r2.id) # Get should respect explicit foreign keys as well. msg = 'get() returned more than one Article -- it returned 2!' with self.assertRaisesMessage(MultipleObjectsReturned, msg): Article.objects.get(reporter_id=self.r.id) self.assertEqual( repr(a3), repr(Article.objects.get(reporter_id=self.r2.id, pub_date=datetime.date(2011, 5, 7))) ) def test_deepcopy_and_circular_references(self): # Regression for #12876 -- Model methods that include queries that # recursive don't cause recursion depth problems under deepcopy. self.r.cached_query = Article.objects.filter(reporter=self.r) self.assertEqual(repr(deepcopy(self.r)), "<Reporter: John Smith>") def test_manager_class_caching(self): r1 = Reporter.objects.create(first_name='Mike') r2 = Reporter.objects.create(first_name='John') # Same twice self.assertIs(r1.article_set.__class__, r1.article_set.__class__) # Same as each other self.assertIs(r1.article_set.__class__, r2.article_set.__class__) def test_create_relation_with_gettext_lazy(self): reporter = Reporter.objects.create(first_name='John', last_name='Smith', email='[email protected]') lazy = gettext_lazy('test') reporter.article_set.create(headline=lazy, pub_date=datetime.date(2011, 6, 10)) notlazy = str(lazy) article = reporter.article_set.get() self.assertEqual(article.headline, notlazy) def test_values_list_exception(self): expected_message = "Cannot resolve keyword 'notafield' into field. Choices are: %s" reporter_fields = ', '.join(sorted(f.name for f in Reporter._meta.get_fields())) with self.assertRaisesMessage(FieldError, expected_message % reporter_fields): Article.objects.values_list('reporter__notafield') article_fields = ', '.join(['EXTRA'] + sorted(f.name for f in Article._meta.get_fields())) with self.assertRaisesMessage(FieldError, expected_message % article_fields): Article.objects.extra(select={'EXTRA': 'EXTRA_SELECT'}).values_list('notafield') def test_fk_assignment_and_related_object_cache(self): # Tests of ForeignKey assignment and the related-object cache (see #6886). p = Parent.objects.create(name="Parent") c = Child.objects.create(name="Child", parent=p) # Look up the object again so that we get a "fresh" object. c = Child.objects.get(name="Child") p = c.parent # Accessing the related object again returns the exactly same object. self.assertIs(c.parent, p) # But if we kill the cache, we get a new object. del c._state.fields_cache['parent'] self.assertIsNot(c.parent, p) # Assigning a new object results in that object getting cached immediately. p2 = Parent.objects.create(name="Parent 2") c.parent = p2 self.assertIs(c.parent, p2) # Assigning None succeeds if field is null=True. p.bestchild = None self.assertIsNone(p.bestchild) # bestchild should still be None after saving. p.save() self.assertIsNone(p.bestchild) # bestchild should still be None after fetching the object again. p = Parent.objects.get(name="Parent") self.assertIsNone(p.bestchild) # Assigning None will not fail: Child.parent is null=False. setattr(c, "parent", None) # You also can't assign an object of the wrong type here msg = ( 'Cannot assign "<First: First object (1)>": "Child.parent" must ' 'be a "Parent" instance.' ) with self.assertRaisesMessage(ValueError, msg): setattr(c, "parent", First(id=1, second=1)) # You can assign None to Child.parent during object creation. Child(name='xyzzy', parent=None) # But when trying to save a Child with parent=None, the database will # raise IntegrityError. with self.assertRaises(IntegrityError), transaction.atomic(): Child.objects.create(name='xyzzy', parent=None) # Creation using keyword argument should cache the related object. p = Parent.objects.get(name="Parent") c = Child(parent=p) self.assertIs(c.parent, p) # Creation using keyword argument and unsaved related instance (#8070). p = Parent() msg = "save() prohibited to prevent data loss due to unsaved related object 'parent'." with self.assertRaisesMessage(ValueError, msg): Child.objects.create(parent=p) msg = "save() prohibited to prevent data loss due to unsaved related object 'parent'." with self.assertRaisesMessage(ValueError, msg): ToFieldChild.objects.create(parent=p) # Creation using attname keyword argument and an id will cause the # related object to be fetched. p = Parent.objects.get(name="Parent") c = Child(parent_id=p.id) self.assertIsNot(c.parent, p) self.assertEqual(c.parent, p) def test_save_nullable_fk_after_parent(self): parent = Parent() child = ChildNullableParent(parent=parent) parent.save() child.save() child.refresh_from_db() self.assertEqual(child.parent, parent) def test_save_nullable_fk_after_parent_with_to_field(self): parent = Parent(name='jeff') child = ToFieldChild(parent=parent) parent.save() child.save() child.refresh_from_db() self.assertEqual(child.parent, parent) self.assertEqual(child.parent_id, parent.name) def test_fk_to_bigautofield(self): ch = City.objects.create(name='Chicago') District.objects.create(city=ch, name='Far South') District.objects.create(city=ch, name='North') ny = City.objects.create(name='New York', id=2 ** 33) District.objects.create(city=ny, name='Brooklyn') District.objects.create(city=ny, name='Manhattan') def test_fk_to_smallautofield(self): us = Country.objects.create(name='United States') City.objects.create(country=us, name='Chicago') City.objects.create(country=us, name='New York') uk = Country.objects.create(name='United Kingdom', id=2 ** 11) City.objects.create(country=uk, name='London') City.objects.create(country=uk, name='Edinburgh') def test_multiple_foreignkeys(self): # Test of multiple ForeignKeys to the same model (bug #7125). c1 = Category.objects.create(name='First') c2 = Category.objects.create(name='Second') c3 = Category.objects.create(name='Third') r1 = Record.objects.create(category=c1) r2 = Record.objects.create(category=c1) r3 = Record.objects.create(category=c2) r4 = Record.objects.create(category=c2) r5 = Record.objects.create(category=c3) Relation.objects.create(left=r1, right=r2) Relation.objects.create(left=r3, right=r4) Relation.objects.create(left=r1, right=r3) Relation.objects.create(left=r5, right=r2) Relation.objects.create(left=r3, right=r2) q1 = Relation.objects.filter(left__category__name__in=['First'], right__category__name__in=['Second']) self.assertQuerysetEqual(q1, ["<Relation: First - Second>"]) q2 = Category.objects.filter(record__left_set__right__category__name='Second').order_by('name') self.assertQuerysetEqual(q2, ["<Category: First>", "<Category: Second>"]) p = Parent.objects.create(name="Parent") c = Child.objects.create(name="Child", parent=p) msg = 'Cannot assign "%r": "Child.parent" must be a "Parent" instance.' % c with self.assertRaisesMessage(ValueError, msg): Child.objects.create(name="Grandchild", parent=c) def test_fk_instantiation_outside_model(self): # Regression for #12190 -- Should be able to instantiate a FK outside # of a model, and interrogate its related field. cat = models.ForeignKey(Category, models.CASCADE) self.assertEqual('id', cat.remote_field.get_related_field().name) def test_relation_unsaved(self): # The <field>_set manager does not join on Null value fields (#17541) Third.objects.create(name='Third 1') Third.objects.create(name='Third 2') th = Third(name="testing") # The object isn't saved and thus the relation field is null - we won't even # execute a query in this case. with self.assertNumQueries(0): self.assertEqual(th.child_set.count(), 0) th.save() # Now the model is saved, so we will need to execute a query. with self.assertNumQueries(1): self.assertEqual(th.child_set.count(), 0) def test_related_object(self): public_school = School.objects.create(is_public=True) public_student = Student.objects.create(school=public_school) private_school = School.objects.create(is_public=False) private_student = Student.objects.create(school=private_school) # Only one school is available via all() due to the custom default manager. self.assertSequenceEqual(School.objects.all(), [public_school]) self.assertEqual(public_student.school, public_school) # Make sure the base manager is used so that a student can still access # its related school even if the default manager doesn't normally # allow it. self.assertEqual(private_student.school, private_school) School._meta.base_manager_name = 'objects' School._meta._expire_cache() try: private_student = Student.objects.get(pk=private_student.pk) with self.assertRaises(School.DoesNotExist): private_student.school finally: School._meta.base_manager_name = None School._meta._expire_cache() def test_hasattr_related_object(self): # The exception raised on attribute access when a related object # doesn't exist should be an instance of a subclass of `AttributeError` # refs #21563 self.assertFalse(hasattr(Article(), 'reporter')) def test_clear_after_prefetch(self): c = City.objects.create(name='Musical City') District.objects.create(name='Ladida', city=c) city = City.objects.prefetch_related('districts').get(id=c.id) self.assertQuerysetEqual(city.districts.all(), ['<District: Ladida>']) city.districts.clear() self.assertQuerysetEqual(city.districts.all(), []) def test_remove_after_prefetch(self): c = City.objects.create(name='Musical City') d = District.objects.create(name='Ladida', city=c) city = City.objects.prefetch_related('districts').get(id=c.id) self.assertQuerysetEqual(city.districts.all(), ['<District: Ladida>']) city.districts.remove(d) self.assertQuerysetEqual(city.districts.all(), []) def test_add_after_prefetch(self): c = City.objects.create(name='Musical City') District.objects.create(name='Ladida', city=c) d2 = District.objects.create(name='Ladidu') city = City.objects.prefetch_related('districts').get(id=c.id) self.assertEqual(city.districts.count(), 1) city.districts.add(d2) self.assertEqual(city.districts.count(), 2) def test_set_after_prefetch(self): c = City.objects.create(name='Musical City') District.objects.create(name='Ladida', city=c) d2 = District.objects.create(name='Ladidu') city = City.objects.prefetch_related('districts').get(id=c.id) self.assertEqual(city.districts.count(), 1) city.districts.set([d2]) self.assertQuerysetEqual(city.districts.all(), ['<District: Ladidu>']) def test_add_then_remove_after_prefetch(self): c = City.objects.create(name='Musical City') District.objects.create(name='Ladida', city=c) d2 = District.objects.create(name='Ladidu') city = City.objects.prefetch_related('districts').get(id=c.id) self.assertEqual(city.districts.count(), 1) city.districts.add(d2) self.assertEqual(city.districts.count(), 2) city.districts.remove(d2) self.assertEqual(city.districts.count(), 1) def test_cached_relation_invalidated_on_save(self): """ Model.save() invalidates stale ForeignKey relations after a primary key assignment. """ self.assertEqual(self.a.reporter, self.r) # caches a.reporter self.a.reporter_id = self.r2.pk self.a.save() self.assertEqual(self.a.reporter, self.r2) def test_cached_foreign_key_with_to_field_not_cleared_by_save(self): parent = Parent.objects.create(name='a') child = ToFieldChild.objects.create(parent=parent) with self.assertNumQueries(0): self.assertIs(child.parent, parent) def test_reverse_foreign_key_instance_to_field_caching(self): parent = Parent.objects.create(name='a') ToFieldChild.objects.create(parent=parent) child = parent.to_field_children.get() with self.assertNumQueries(0): self.assertIs(child.parent, parent)
60a8a8ab2587fd6c52a4a5cc100970558b5870634030c7b55c11ae5cb766fbdd
""" Many-to-one relationships To define a many-to-one relationship, use ``ForeignKey()``. """ from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, models.CASCADE) class Meta: ordering = ('headline',) def __str__(self): return self.headline class Country(models.Model): id = models.SmallAutoField(primary_key=True) name = models.CharField(max_length=50) class City(models.Model): id = models.BigAutoField(primary_key=True) country = models.ForeignKey(Country, models.CASCADE, related_name='cities', null=True) name = models.CharField(max_length=50) def __str__(self): return self.name class District(models.Model): city = models.ForeignKey(City, models.CASCADE, related_name='districts', null=True) name = models.CharField(max_length=50) def __str__(self): return self.name # If ticket #1578 ever slips back in, these models will not be able to be # created (the field names being lowercased versions of their opposite classes # is important here). class First(models.Model): second = models.IntegerField() class Second(models.Model): first = models.ForeignKey(First, models.CASCADE, related_name='the_first') # Protect against repetition of #1839, #2415 and #2536. class Third(models.Model): name = models.CharField(max_length=20) third = models.ForeignKey('self', models.SET_NULL, null=True, related_name='child_set') class Parent(models.Model): name = models.CharField(max_length=20, unique=True) bestchild = models.ForeignKey('Child', models.SET_NULL, null=True, related_name='favored_by') class Child(models.Model): name = models.CharField(max_length=20) parent = models.ForeignKey(Parent, models.CASCADE) class ChildNullableParent(models.Model): parent = models.ForeignKey(Parent, models.CASCADE, null=True) class ToFieldChild(models.Model): parent = models.ForeignKey(Parent, models.CASCADE, to_field='name', related_name='to_field_children') # Multiple paths to the same model (#7110, #7125) class Category(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Record(models.Model): category = models.ForeignKey(Category, models.CASCADE) class Relation(models.Model): left = models.ForeignKey(Record, models.CASCADE, related_name='left_set') right = models.ForeignKey(Record, models.CASCADE, related_name='right_set') def __str__(self): return "%s - %s" % (self.left.category.name, self.right.category.name) # Test related objects visibility. class SchoolManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_public=True) class School(models.Model): is_public = models.BooleanField(default=False) objects = SchoolManager() class Student(models.Model): school = models.ForeignKey(School, models.CASCADE)
dd849fdbd00ce961ca228c33c88a27522d2e37b833c75a4dad5950a6674cdb72
""" Testing using the Test Client The test client is a class that can act like a simple browser for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. ``Client`` objects are stateful - they will retain cookie (and thus session) details for the lifetime of the ``Client`` instance. This is not intended as a replacement for Twill, Selenium, or other browser automation frameworks - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ import itertools import tempfile from unittest import mock from django.contrib.auth.models import User from django.core import mail from django.http import HttpResponse from django.test import ( Client, RequestFactory, SimpleTestCase, TestCase, override_settings, ) from django.urls import reverse_lazy from .views import TwoArgException, get_view, post_view, trace_view @override_settings(ROOT_URLCONF='test_client.urls') class ClientTest(TestCase): @classmethod def setUpTestData(cls): cls.u1 = User.objects.create_user(username='testclient', password='password') cls.u2 = User.objects.create_user(username='inactive', password='password', is_active=False) def test_get_view(self): "GET a view" # The data is ignored, but let's check it doesn't crash the system # anyway. data = {'var': '\xf2'} response = self.client.get('/get_view/', data) # Check some response details self.assertContains(response, 'This is a test') self.assertEqual(response.context['var'], '\xf2') self.assertEqual(response.templates[0].name, 'GET Template') def test_query_string_encoding(self): # WSGI requires latin-1 encoded strings. response = self.client.get('/get_view/?var=1\ufffd') self.assertEqual(response.context['var'], '1\ufffd') def test_get_data_none(self): msg = ( "Cannot encode None for key 'value' in a query string. Did you " "mean to pass an empty string or omit the value?" ) with self.assertRaisesMessage(TypeError, msg): self.client.get('/get_view/', {'value': None}) def test_get_post_view(self): "GET a view that normally expects POSTs" response = self.client.get('/post_view/', {}) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, 'Empty GET Template') self.assertTemplateUsed(response, 'Empty GET Template') self.assertTemplateNotUsed(response, 'Empty POST Template') def test_empty_post(self): "POST an empty dictionary to a view" response = self.client.post('/post_view/', {}) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, 'Empty POST Template') self.assertTemplateNotUsed(response, 'Empty GET Template') self.assertTemplateUsed(response, 'Empty POST Template') def test_post(self): "POST some data to a view" post_data = { 'value': 37 } response = self.client.post('/post_view/', post_data) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.context['data'], '37') self.assertEqual(response.templates[0].name, 'POST Template') self.assertContains(response, 'Data received') def test_post_data_none(self): msg = ( "Cannot encode None for key 'value' as POST data. Did you mean " "to pass an empty string or omit the value?" ) with self.assertRaisesMessage(TypeError, msg): self.client.post('/post_view/', {'value': None}) def test_json_serialization(self): """The test client serializes JSON data.""" methods = ('post', 'put', 'patch', 'delete') tests = ( ({'value': 37}, {'value': 37}), ([37, True], [37, True]), ((37, False), [37, False]), ) for method in methods: with self.subTest(method=method): for data, expected in tests: with self.subTest(data): client_method = getattr(self.client, method) method_name = method.upper() response = client_method('/json_view/', data, content_type='application/json') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['data'], expected) self.assertContains(response, 'Viewing %s page.' % method_name) def test_json_encoder_argument(self): """The test Client accepts a json_encoder.""" mock_encoder = mock.MagicMock() mock_encoding = mock.MagicMock() mock_encoder.return_value = mock_encoding mock_encoding.encode.return_value = '{"value": 37}' client = self.client_class(json_encoder=mock_encoder) # Vendored tree JSON content types are accepted. client.post('/json_view/', {'value': 37}, content_type='application/vnd.api+json') self.assertTrue(mock_encoder.called) self.assertTrue(mock_encoding.encode.called) def test_put(self): response = self.client.put('/put_view/', {'foo': 'bar'}) self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, 'PUT Template') self.assertEqual(response.context['data'], "{'foo': 'bar'}") self.assertEqual(response.context['Content-Length'], '14') def test_trace(self): """TRACE a view""" response = self.client.trace('/trace_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['method'], 'TRACE') self.assertEqual(response.templates[0].name, 'TRACE Template') def test_response_headers(self): "Check the value of HTTP headers returned in a response" response = self.client.get("/header_view/") self.assertEqual(response['X-DJANGO-TEST'], 'Slartibartfast') def test_response_attached_request(self): """ The returned response has a ``request`` attribute with the originating environ dict and a ``wsgi_request`` with the originating WSGIRequest. """ response = self.client.get("/header_view/") self.assertTrue(hasattr(response, 'request')) self.assertTrue(hasattr(response, 'wsgi_request')) for key, value in response.request.items(): self.assertIn(key, response.wsgi_request.environ) self.assertEqual(response.wsgi_request.environ[key], value) def test_response_resolver_match(self): """ The response contains a ResolverMatch instance. """ response = self.client.get('/header_view/') self.assertTrue(hasattr(response, 'resolver_match')) def test_response_resolver_match_redirect_follow(self): """ The response ResolverMatch instance contains the correct information when following redirects. """ response = self.client.get('/redirect_view/', follow=True) self.assertEqual(response.resolver_match.url_name, 'get_view') def test_response_resolver_match_regular_view(self): """ The response ResolverMatch instance contains the correct information when accessing a regular view. """ response = self.client.get('/get_view/') self.assertEqual(response.resolver_match.url_name, 'get_view') def test_raw_post(self): "POST raw data (with a content type) to a view" test_doc = """<?xml version="1.0" encoding="utf-8"?> <library><book><title>Blink</title><author>Malcolm Gladwell</author></book></library> """ response = self.client.post('/raw_post_view/', test_doc, content_type='text/xml') self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "Book template") self.assertEqual(response.content, b"Blink - Malcolm Gladwell") def test_insecure(self): "GET a URL through http" response = self.client.get('/secure_view/', secure=False) self.assertFalse(response.test_was_secure_request) self.assertEqual(response.test_server_port, '80') def test_secure(self): "GET a URL through https" response = self.client.get('/secure_view/', secure=True) self.assertTrue(response.test_was_secure_request) self.assertEqual(response.test_server_port, '443') def test_redirect(self): "GET a URL that redirects elsewhere" response = self.client.get('/redirect_view/') self.assertRedirects(response, '/get_view/') def test_redirect_with_query(self): "GET a URL that redirects with given GET parameters" response = self.client.get('/redirect_view/', {'var': 'value'}) self.assertRedirects(response, '/get_view/?var=value') def test_redirect_with_query_ordering(self): """assertRedirects() ignores the order of query string parameters.""" response = self.client.get('/redirect_view/', {'var': 'value', 'foo': 'bar'}) self.assertRedirects(response, '/get_view/?var=value&foo=bar') self.assertRedirects(response, '/get_view/?foo=bar&var=value') def test_permanent_redirect(self): "GET a URL that redirects permanently elsewhere" response = self.client.get('/permanent_redirect_view/') self.assertRedirects(response, '/get_view/', status_code=301) def test_temporary_redirect(self): "GET a URL that does a non-permanent redirect" response = self.client.get('/temporary_redirect_view/') self.assertRedirects(response, '/get_view/', status_code=302) def test_redirect_to_strange_location(self): "GET a URL that redirects to a non-200 page" response = self.client.get('/double_redirect_view/') # The response was a 302, and that the attempt to get the redirection # location returned 301 when retrieved self.assertRedirects(response, '/permanent_redirect_view/', target_status_code=301) def test_follow_redirect(self): "A URL that redirects can be followed to termination." response = self.client.get('/double_redirect_view/', follow=True) self.assertRedirects(response, '/get_view/', status_code=302, target_status_code=200) self.assertEqual(len(response.redirect_chain), 2) def test_follow_relative_redirect(self): "A URL with a relative redirect can be followed." response = self.client.get('/accounts/', follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.request['PATH_INFO'], '/accounts/login/') def test_follow_relative_redirect_no_trailing_slash(self): "A URL with a relative redirect with no trailing slash can be followed." response = self.client.get('/accounts/no_trailing_slash', follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.request['PATH_INFO'], '/accounts/login/') def test_follow_307_and_308_redirect(self): """ A 307 or 308 redirect preserves the request method after the redirect. """ methods = ('get', 'post', 'head', 'options', 'put', 'patch', 'delete', 'trace') codes = (307, 308) for method, code in itertools.product(methods, codes): with self.subTest(method=method, code=code): req_method = getattr(self.client, method) response = req_method('/redirect_view_%s/' % code, data={'value': 'test'}, follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.request['PATH_INFO'], '/post_view/') self.assertEqual(response.request['REQUEST_METHOD'], method.upper()) def test_follow_307_and_308_preserves_post_data(self): for code in (307, 308): with self.subTest(code=code): response = self.client.post('/redirect_view_%s/' % code, data={'value': 'test'}, follow=True) self.assertContains(response, 'test is the value') def test_follow_307_and_308_preserves_put_body(self): for code in (307, 308): with self.subTest(code=code): response = self.client.put('/redirect_view_%s/?to=/put_view/' % code, data='a=b', follow=True) self.assertContains(response, 'a=b is the body') def test_follow_307_and_308_preserves_get_params(self): data = {'var': 30, 'to': '/get_view/'} for code in (307, 308): with self.subTest(code=code): response = self.client.get('/redirect_view_%s/' % code, data=data, follow=True) self.assertContains(response, '30 is the value') def test_redirect_http(self): "GET a URL that redirects to an http URI" response = self.client.get('/http_redirect_view/', follow=True) self.assertFalse(response.test_was_secure_request) def test_redirect_https(self): "GET a URL that redirects to an https URI" response = self.client.get('/https_redirect_view/', follow=True) self.assertTrue(response.test_was_secure_request) def test_notfound_response(self): "GET a URL that responds as '404:Not Found'" response = self.client.get('/bad_view/') self.assertContains(response, 'MAGIC', status_code=404) def test_valid_form(self): "POST valid data to a form" post_data = { 'text': 'Hello World', 'email': '[email protected]', 'value': 37, 'single': 'b', 'multi': ('b', 'c', 'e') } response = self.client.post('/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Valid POST Template") def test_valid_form_with_hints(self): "GET a form, providing hints in the GET data" hints = { 'text': 'Hello World', 'multi': ('b', 'c', 'e') } response = self.client.get('/form_view/', data=hints) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Form GET Template") # The multi-value data has been rolled out ok self.assertContains(response, 'Select a valid choice.', 0) def test_incomplete_data_form(self): "POST incomplete data to a form" post_data = { 'text': 'Hello World', 'value': 37 } response = self.client.post('/form_view/', post_data) self.assertContains(response, 'This field is required.', 3) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'This field is required.') self.assertFormError(response, 'form', 'single', 'This field is required.') self.assertFormError(response, 'form', 'multi', 'This field is required.') def test_form_error(self): "POST erroneous data to a form" post_data = { 'text': 'Hello World', 'email': 'not an email address', 'value': 37, 'single': 'b', 'multi': ('b', 'c', 'e') } response = self.client.post('/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'Enter a valid email address.') def test_valid_form_with_template(self): "POST valid data to a form using multiple templates" post_data = { 'text': 'Hello World', 'email': '[email protected]', 'value': 37, 'single': 'b', 'multi': ('b', 'c', 'e') } response = self.client.post('/form_view_with_template/', post_data) self.assertContains(response, 'POST data OK') self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, 'base.html') self.assertTemplateNotUsed(response, "Valid POST Template") def test_incomplete_data_form_with_template(self): "POST incomplete data to a form using multiple templates" post_data = { 'text': 'Hello World', 'value': 37 } response = self.client.post('/form_view_with_template/', post_data) self.assertContains(response, 'POST data has errors') self.assertTemplateUsed(response, 'form_view.html') self.assertTemplateUsed(response, 'base.html') self.assertTemplateNotUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'This field is required.') self.assertFormError(response, 'form', 'single', 'This field is required.') self.assertFormError(response, 'form', 'multi', 'This field is required.') def test_form_error_with_template(self): "POST erroneous data to a form using multiple templates" post_data = { 'text': 'Hello World', 'email': 'not an email address', 'value': 37, 'single': 'b', 'multi': ('b', 'c', 'e') } response = self.client.post('/form_view_with_template/', post_data) self.assertContains(response, 'POST data has errors') self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, 'base.html') self.assertTemplateNotUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'Enter a valid email address.') def test_unknown_page(self): "GET an invalid URL" response = self.client.get('/unknown_view/') # The response was a 404 self.assertEqual(response.status_code, 404) def test_url_parameters(self): "Make sure that URL ;-parameters are not stripped." response = self.client.get('/unknown_view/;some-parameter') # The path in the response includes it (ignore that it's a 404) self.assertEqual(response.request['PATH_INFO'], '/unknown_view/;some-parameter') def test_view_with_login(self): "Request a page that is protected with @login_required" # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') @override_settings( INSTALLED_APPS=['django.contrib.auth'], SESSION_ENGINE='django.contrib.sessions.backends.file', ) def test_view_with_login_when_sessions_app_is_not_installed(self): self.test_view_with_login() def test_view_with_force_login(self): "Request a page that is protected with @login_required" # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/') # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_method_login(self): "Request a page that is protected with a @login_required method" # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_method_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_method_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Request a page that requires a login response = self.client.get('/login_protected_method_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_method_force_login(self): "Request a page that is protected with a @login_required method" # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_method_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_method_view/') # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get('/login_protected_method_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_login_and_custom_redirect(self): "Request a page that is protected with @login_required(redirect_field_name='redirect_to')" # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_view_custom_redirect/') self.assertRedirects(response, '/accounts/login/?redirect_to=/login_protected_view_custom_redirect/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Request a page that requires a login response = self.client.get('/login_protected_view_custom_redirect/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_force_login_and_custom_redirect(self): """ Request a page that is protected with @login_required(redirect_field_name='redirect_to') """ # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_view_custom_redirect/') self.assertRedirects(response, '/accounts/login/?redirect_to=/login_protected_view_custom_redirect/') # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get('/login_protected_view_custom_redirect/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_bad_login(self): "Request a page that is protected with @login, but use bad credentials" login = self.client.login(username='otheruser', password='nopassword') self.assertFalse(login) def test_view_with_inactive_login(self): """ An inactive user may login if the authenticate backend allows it. """ credentials = {'username': 'inactive', 'password': 'password'} self.assertFalse(self.client.login(**credentials)) with self.settings(AUTHENTICATION_BACKENDS=['django.contrib.auth.backends.AllowAllUsersModelBackend']): self.assertTrue(self.client.login(**credentials)) @override_settings( AUTHENTICATION_BACKENDS=[ 'django.contrib.auth.backends.ModelBackend', 'django.contrib.auth.backends.AllowAllUsersModelBackend', ] ) def test_view_with_inactive_force_login(self): "Request a page that is protected with @login, but use an inactive login" # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/') # Log in self.client.force_login(self.u2, backend='django.contrib.auth.backends.AllowAllUsersModelBackend') # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'inactive') def test_logout(self): "Request a logout after logging in" # Log in self.client.login(username='testclient', password='password') # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') # Log out self.client.logout() # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/') def test_logout_with_force_login(self): "Request a logout after logging in" # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') # Log out self.client.logout() # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/') @override_settings( AUTHENTICATION_BACKENDS=[ 'django.contrib.auth.backends.ModelBackend', 'test_client.auth_backends.TestClientBackend', ], ) def test_force_login_with_backend(self): """ Request a page that is protected with @login_required when using force_login() and passing a backend. """ # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/') # Log in self.client.force_login(self.u1, backend='test_client.auth_backends.TestClientBackend') self.assertEqual(self.u1.backend, 'test_client.auth_backends.TestClientBackend') # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') @override_settings( AUTHENTICATION_BACKENDS=[ 'django.contrib.auth.backends.ModelBackend', 'test_client.auth_backends.TestClientBackend', ], ) def test_force_login_without_backend(self): """ force_login() without passing a backend and with multiple backends configured should automatically use the first backend. """ self.client.force_login(self.u1) response = self.client.get('/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') self.assertEqual(self.u1.backend, 'django.contrib.auth.backends.ModelBackend') @override_settings(AUTHENTICATION_BACKENDS=[ 'test_client.auth_backends.BackendWithoutGetUserMethod', 'django.contrib.auth.backends.ModelBackend', ]) def test_force_login_with_backend_missing_get_user(self): """ force_login() skips auth backends without a get_user() method. """ self.client.force_login(self.u1) self.assertEqual(self.u1.backend, 'django.contrib.auth.backends.ModelBackend') @override_settings(SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies") def test_logout_cookie_sessions(self): self.test_logout() def test_view_with_permissions(self): "Request a page that is protected with @permission_required" # Get the page without logging in. Should result in 302. response = self.client.get('/permission_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/permission_protected_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Log in with wrong permissions. Should result in 302. response = self.client.get('/permission_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/permission_protected_view/') # TODO: Log in with right permissions and request the page again def test_view_with_permissions_exception(self): "Request a page that is protected with @permission_required but raises an exception" # Get the page without logging in. Should result in 403. response = self.client.get('/permission_protected_view_exception/') self.assertEqual(response.status_code, 403) # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Log in with wrong permissions. Should result in 403. response = self.client.get('/permission_protected_view_exception/') self.assertEqual(response.status_code, 403) def test_view_with_method_permissions(self): "Request a page that is protected with a @permission_required method" # Get the page without logging in. Should result in 302. response = self.client.get('/permission_protected_method_view/') self.assertRedirects(response, '/accounts/login/?next=/permission_protected_method_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Log in with wrong permissions. Should result in 302. response = self.client.get('/permission_protected_method_view/') self.assertRedirects(response, '/accounts/login/?next=/permission_protected_method_view/') # TODO: Log in with right permissions and request the page again def test_external_redirect(self): response = self.client.get('/django_project_redirect/') self.assertRedirects(response, 'https://www.djangoproject.com/', fetch_redirect_response=False) def test_external_redirect_with_fetch_error_msg(self): """ assertRedirects without fetch_redirect_response=False raises a relevant ValueError rather than a non-descript AssertionError. """ response = self.client.get('/django_project_redirect/') msg = ( "The test client is unable to fetch remote URLs (got " "https://www.djangoproject.com/). If the host is served by Django, " "add 'www.djangoproject.com' to ALLOWED_HOSTS. " "Otherwise, use assertRedirects(..., fetch_redirect_response=False)." ) with self.assertRaisesMessage(ValueError, msg): self.assertRedirects(response, 'https://www.djangoproject.com/') def test_session_modifying_view(self): "Request a page that modifies the session" # Session value isn't set initially with self.assertRaises(KeyError): self.client.session['tobacconist'] self.client.post('/session_view/') # The session was modified self.assertEqual(self.client.session['tobacconist'], 'hovercraft') @override_settings( INSTALLED_APPS=[], SESSION_ENGINE='django.contrib.sessions.backends.file', ) def test_sessions_app_is_not_installed(self): self.test_session_modifying_view() @override_settings( INSTALLED_APPS=[], SESSION_ENGINE='django.contrib.sessions.backends.nonexistent', ) def test_session_engine_is_invalid(self): with self.assertRaisesMessage(ImportError, 'nonexistent'): self.test_session_modifying_view() def test_view_with_exception(self): "Request a page that is known to throw an error" with self.assertRaises(KeyError): self.client.get("/broken_view/") def test_exc_info(self): client = Client(raise_request_exception=False) response = client.get("/broken_view/") self.assertEqual(response.status_code, 500) exc_type, exc_value, exc_traceback = response.exc_info self.assertIs(exc_type, KeyError) self.assertIsInstance(exc_value, KeyError) self.assertEqual(str(exc_value), "'Oops! Looks like you wrote some bad code.'") self.assertIsNotNone(exc_traceback) def test_exc_info_none(self): response = self.client.get("/get_view/") self.assertIsNone(response.exc_info) def test_mail_sending(self): "Mail is redirected to a dummy outbox during test setup" response = self.client.get('/mail_sending_view/') self.assertEqual(response.status_code, 200) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Test message') self.assertEqual(mail.outbox[0].body, 'This is a test email') self.assertEqual(mail.outbox[0].from_email, '[email protected]') self.assertEqual(mail.outbox[0].to[0], '[email protected]') self.assertEqual(mail.outbox[0].to[1], '[email protected]') def test_reverse_lazy_decodes(self): "reverse_lazy() works in the test client" data = {'var': 'data'} response = self.client.get(reverse_lazy('get_view'), data) # Check some response details self.assertContains(response, 'This is a test') def test_relative_redirect(self): response = self.client.get('/accounts/') self.assertRedirects(response, '/accounts/login/') def test_relative_redirect_no_trailing_slash(self): response = self.client.get('/accounts/no_trailing_slash') self.assertRedirects(response, '/accounts/login/') def test_mass_mail_sending(self): "Mass mail is redirected to a dummy outbox during test setup" response = self.client.get('/mass_mail_sending_view/') self.assertEqual(response.status_code, 200) self.assertEqual(len(mail.outbox), 2) self.assertEqual(mail.outbox[0].subject, 'First Test message') self.assertEqual(mail.outbox[0].body, 'This is the first test email') self.assertEqual(mail.outbox[0].from_email, '[email protected]') self.assertEqual(mail.outbox[0].to[0], '[email protected]') self.assertEqual(mail.outbox[0].to[1], '[email protected]') self.assertEqual(mail.outbox[1].subject, 'Second Test message') self.assertEqual(mail.outbox[1].body, 'This is the second test email') self.assertEqual(mail.outbox[1].from_email, '[email protected]') self.assertEqual(mail.outbox[1].to[0], '[email protected]') self.assertEqual(mail.outbox[1].to[1], '[email protected]') def test_exception_following_nested_client_request(self): """ A nested test client request shouldn't clobber exception signals from the outer client request. """ with self.assertRaisesMessage(Exception, 'exception message'): self.client.get('/nesting_exception_view/') def test_response_raises_multi_arg_exception(self): """A request may raise an exception with more than one required arg.""" with self.assertRaises(TwoArgException) as cm: self.client.get('/two_arg_exception/') self.assertEqual(cm.exception.args, ('one', 'two')) def test_uploading_temp_file(self): with tempfile.TemporaryFile() as test_file: response = self.client.post('/upload_view/', data={'temp_file': test_file}) self.assertEqual(response.content, b'temp_file') def test_uploading_named_temp_file(self): test_file = tempfile.NamedTemporaryFile() response = self.client.post('/upload_view/', data={'named_temp_file': test_file}) self.assertEqual(response.content, b'named_temp_file') @override_settings( MIDDLEWARE=['django.middleware.csrf.CsrfViewMiddleware'], ROOT_URLCONF='test_client.urls', ) class CSRFEnabledClientTests(SimpleTestCase): def test_csrf_enabled_client(self): "A client can be instantiated with CSRF checks enabled" csrf_client = Client(enforce_csrf_checks=True) # The normal client allows the post response = self.client.post('/post_view/', {}) self.assertEqual(response.status_code, 200) # The CSRF-enabled client rejects it response = csrf_client.post('/post_view/', {}) self.assertEqual(response.status_code, 403) class CustomTestClient(Client): i_am_customized = "Yes" class CustomTestClientTest(SimpleTestCase): client_class = CustomTestClient def test_custom_test_client(self): """A test case can specify a custom class for self.client.""" self.assertIs(hasattr(self.client, "i_am_customized"), True) def _generic_view(request): return HttpResponse(status=200) @override_settings(ROOT_URLCONF='test_client.urls') class RequestFactoryTest(SimpleTestCase): """Tests for the request factory.""" # A mapping between names of HTTP/1.1 methods and their test views. http_methods_and_views = ( ('get', get_view), ('post', post_view), ('put', _generic_view), ('patch', _generic_view), ('delete', _generic_view), ('head', _generic_view), ('options', _generic_view), ('trace', trace_view), ) request_factory = RequestFactory() def test_request_factory(self): """The request factory implements all the HTTP/1.1 methods.""" for method_name, view in self.http_methods_and_views: method = getattr(self.request_factory, method_name) request = method('/somewhere/') response = view(request) self.assertEqual(response.status_code, 200) def test_get_request_from_factory(self): """ The request factory returns a templated response for a GET request. """ request = self.request_factory.get('/somewhere/') response = get_view(request) self.assertContains(response, 'This is a test') def test_trace_request_from_factory(self): """The request factory returns an echo response for a TRACE request.""" url_path = '/somewhere/' request = self.request_factory.trace(url_path) response = trace_view(request) protocol = request.META["SERVER_PROTOCOL"] echoed_request_line = "TRACE {} {}".format(url_path, protocol) self.assertContains(response, echoed_request_line)
46d961c54e3d69fb286c59b24e438fd1f48f6a49fda8397c4da4499c96cdef5e
from django.core.exceptions import ImproperlyConfigured from django.core.servers.basehttp import get_internal_wsgi_application from django.core.signals import request_started from django.core.wsgi import get_wsgi_application from django.db import close_old_connections from django.http import FileResponse from django.test import SimpleTestCase, override_settings from django.test.client import RequestFactory @override_settings(ROOT_URLCONF='wsgi.urls') class WSGITest(SimpleTestCase): request_factory = RequestFactory() def setUp(self): request_started.disconnect(close_old_connections) def tearDown(self): request_started.connect(close_old_connections) def test_get_wsgi_application(self): """ get_wsgi_application() returns a functioning WSGI callable. """ application = get_wsgi_application() environ = self.request_factory._base_environ( PATH_INFO="/", CONTENT_TYPE="text/html; charset=utf-8", REQUEST_METHOD="GET" ) response_data = {} def start_response(status, headers): response_data["status"] = status response_data["headers"] = headers response = application(environ, start_response) self.assertEqual(response_data["status"], "200 OK") self.assertEqual( set(response_data["headers"]), {('Content-Length', '12'), ('Content-Type', 'text/html; charset=utf-8')}) self.assertIn(bytes(response), [ b"Content-Length: 12\r\nContent-Type: text/html; charset=utf-8\r\n\r\nHello World!", b"Content-Type: text/html; charset=utf-8\r\nContent-Length: 12\r\n\r\nHello World!" ]) def test_file_wrapper(self): """ FileResponse uses wsgi.file_wrapper. """ class FileWrapper: def __init__(self, filelike, block_size=None): self.block_size = block_size filelike.close() application = get_wsgi_application() environ = self.request_factory._base_environ( PATH_INFO='/file/', REQUEST_METHOD='GET', **{'wsgi.file_wrapper': FileWrapper} ) response_data = {} def start_response(status, headers): response_data['status'] = status response_data['headers'] = headers response = application(environ, start_response) self.assertEqual(response_data['status'], '200 OK') self.assertIsInstance(response, FileWrapper) self.assertEqual(response.block_size, FileResponse.block_size) class GetInternalWSGIApplicationTest(SimpleTestCase): @override_settings(WSGI_APPLICATION="wsgi.wsgi.application") def test_success(self): """ If ``WSGI_APPLICATION`` is a dotted path, the referenced object is returned. """ app = get_internal_wsgi_application() from .wsgi import application self.assertIs(app, application) @override_settings(WSGI_APPLICATION=None) def test_default(self): """ If ``WSGI_APPLICATION`` is ``None``, the return value of ``get_wsgi_application`` is returned. """ # Mock out get_wsgi_application so we know its return value is used fake_app = object() def mock_get_wsgi_app(): return fake_app from django.core.servers import basehttp _orig_get_wsgi_app = basehttp.get_wsgi_application basehttp.get_wsgi_application = mock_get_wsgi_app try: app = get_internal_wsgi_application() self.assertIs(app, fake_app) finally: basehttp.get_wsgi_application = _orig_get_wsgi_app @override_settings(WSGI_APPLICATION="wsgi.noexist.app") def test_bad_module(self): msg = "WSGI application 'wsgi.noexist.app' could not be loaded; Error importing" with self.assertRaisesMessage(ImproperlyConfigured, msg): get_internal_wsgi_application() @override_settings(WSGI_APPLICATION="wsgi.wsgi.noexist") def test_bad_name(self): msg = "WSGI application 'wsgi.wsgi.noexist' could not be loaded; Error importing" with self.assertRaisesMessage(ImproperlyConfigured, msg): get_internal_wsgi_application()
c1e7bfbd6ef1a86180c1990457f78c0f8265a81c42dcdebfc2404fa13d591189
import datetime import itertools import unittest from copy import copy from unittest import mock from django.core.management.color import no_style from django.db import ( DatabaseError, IntegrityError, OperationalError, connection, ) from django.db.models import Index, Model, Q from django.db.models.constraints import CheckConstraint, UniqueConstraint from django.db.models.deletion import CASCADE, PROTECT from django.db.models.fields import ( AutoField, BigAutoField, BigIntegerField, BinaryField, BooleanField, CharField, DateField, DateTimeField, IntegerField, PositiveIntegerField, SlugField, SmallAutoField, SmallIntegerField, TextField, TimeField, UUIDField, ) from django.db.models.fields.related import ( ForeignKey, ForeignObject, ManyToManyField, OneToOneField, ) from django.db.transaction import TransactionManagementError, atomic from django.db.utils import DataError from django.test import ( TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import CaptureQueriesContext, isolate_apps from django.utils import timezone from .fields import ( CustomManyToManyField, InheritedManyToManyField, MediumBlobField, ) from .models import ( Author, AuthorCharFieldWithIndex, AuthorTextFieldWithIndex, AuthorWithDefaultHeight, AuthorWithEvenLongerName, AuthorWithIndexedName, AuthorWithIndexedNameAndBirthday, AuthorWithUniqueName, AuthorWithUniqueNameAndBirthday, Book, BookForeignObj, BookWeak, BookWithLongName, BookWithO2O, BookWithoutAuthor, BookWithSlug, IntegerPK, Node, Note, NoteRename, Tag, TagIndexed, TagM2MTest, TagUniqueRename, Thing, UniqueTest, new_apps, ) class SchemaTests(TransactionTestCase): """ Tests for the schema-alteration code. Be aware that these tests are more liable than most to false results, as sometimes the code to check if a test has worked is almost as complex as the code it is testing. """ available_apps = [] models = [ Author, AuthorCharFieldWithIndex, AuthorTextFieldWithIndex, AuthorWithDefaultHeight, AuthorWithEvenLongerName, Book, BookWeak, BookWithLongName, BookWithO2O, BookWithSlug, IntegerPK, Node, Note, Tag, TagIndexed, TagM2MTest, TagUniqueRename, Thing, UniqueTest, ] # Utility functions def setUp(self): # local_models should contain test dependent model classes that will be # automatically removed from the app cache on test tear down. self.local_models = [] # isolated_local_models contains models that are in test methods # decorated with @isolate_apps. self.isolated_local_models = [] def tearDown(self): # Delete any tables made for our models self.delete_tables() new_apps.clear_cache() for model in new_apps.get_models(): model._meta._expire_cache() if 'schema' in new_apps.all_models: for model in self.local_models: for many_to_many in model._meta.many_to_many: through = many_to_many.remote_field.through if through and through._meta.auto_created: del new_apps.all_models['schema'][through._meta.model_name] del new_apps.all_models['schema'][model._meta.model_name] if self.isolated_local_models: with connection.schema_editor() as editor: for model in self.isolated_local_models: editor.delete_model(model) def delete_tables(self): "Deletes all model tables for our models for a clean test environment" converter = connection.introspection.identifier_converter with connection.schema_editor() as editor: connection.disable_constraint_checking() table_names = connection.introspection.table_names() for model in itertools.chain(SchemaTests.models, self.local_models): tbl = converter(model._meta.db_table) if tbl in table_names: editor.delete_model(model) table_names.remove(tbl) connection.enable_constraint_checking() def column_classes(self, model): with connection.cursor() as cursor: columns = { d[0]: (connection.introspection.get_field_type(d[1], d), d) for d in connection.introspection.get_table_description( cursor, model._meta.db_table, ) } # SQLite has a different format for field_type for name, (type, desc) in columns.items(): if isinstance(type, tuple): columns[name] = (type[0], desc) # SQLite also doesn't error properly if not columns: raise DatabaseError("Table does not exist (empty pragma)") return columns def get_primary_key(self, table): with connection.cursor() as cursor: return connection.introspection.get_primary_key_column(cursor, table) def get_indexes(self, table): """ Get the indexes on the table using a new cursor. """ with connection.cursor() as cursor: return [ c['columns'][0] for c in connection.introspection.get_constraints(cursor, table).values() if c['index'] and len(c['columns']) == 1 ] def get_uniques(self, table): with connection.cursor() as cursor: return [ c['columns'][0] for c in connection.introspection.get_constraints(cursor, table).values() if c['unique'] and len(c['columns']) == 1 ] def get_constraints(self, table): """ Get the constraints on a table using a new cursor. """ with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) def get_constraints_for_column(self, model, column_name): constraints = self.get_constraints(model._meta.db_table) constraints_for_column = [] for name, details in constraints.items(): if details['columns'] == [column_name]: constraints_for_column.append(name) return sorted(constraints_for_column) def check_added_field_default(self, schema_editor, model, field, field_name, expected_default, cast_function=None): with connection.cursor() as cursor: schema_editor.add_field(model, field) cursor.execute("SELECT {} FROM {};".format(field_name, model._meta.db_table)) database_default = cursor.fetchall()[0][0] if cast_function and not type(database_default) == type(expected_default): database_default = cast_function(database_default) self.assertEqual(database_default, expected_default) def get_constraints_count(self, table, column, fk_to): """ Return a dict with keys 'fks', 'uniques, and 'indexes' indicating the number of foreign keys, unique constraints, and indexes on `table`.`column`. The `fk_to` argument is a 2-tuple specifying the expected foreign key relationship's (table, column). """ with connection.cursor() as cursor: constraints = connection.introspection.get_constraints(cursor, table) counts = {'fks': 0, 'uniques': 0, 'indexes': 0} for c in constraints.values(): if c['columns'] == [column]: if c['foreign_key'] == fk_to: counts['fks'] += 1 if c['unique']: counts['uniques'] += 1 elif c['index']: counts['indexes'] += 1 return counts def assertIndexOrder(self, table, index, order): constraints = self.get_constraints(table) self.assertIn(index, constraints) index_orders = constraints[index]['orders'] self.assertTrue(all(val == expected for val, expected in zip(index_orders, order))) def assertForeignKeyExists(self, model, column, expected_fk_table, field='id'): """ Fail if the FK constraint on `model.Meta.db_table`.`column` to `expected_fk_table`.id doesn't exist. """ constraints = self.get_constraints(model._meta.db_table) constraint_fk = None for details in constraints.values(): if details['columns'] == [column] and details['foreign_key']: constraint_fk = details['foreign_key'] break self.assertEqual(constraint_fk, (expected_fk_table, field)) def assertForeignKeyNotExists(self, model, column, expected_fk_table): with self.assertRaises(AssertionError): self.assertForeignKeyExists(model, column, expected_fk_table) # Tests def test_creation_deletion(self): """ Tries creating a model's table, and then deleting it. """ with connection.schema_editor() as editor: # Create the table editor.create_model(Author) # The table is there list(Author.objects.all()) # Clean up that table editor.delete_model(Author) # No deferred SQL should be left over. self.assertEqual(editor.deferred_sql, []) # The table is gone with self.assertRaises(DatabaseError): list(Author.objects.all()) @skipUnlessDBFeature('supports_foreign_keys') def test_fk(self): "Creating tables out of FK order, then repointing, works" # Create the table with connection.schema_editor() as editor: editor.create_model(Book) editor.create_model(Author) editor.create_model(Tag) # Initial tables are there list(Author.objects.all()) list(Book.objects.all()) # Make sure the FK constraint is present with self.assertRaises(IntegrityError): Book.objects.create( author_id=1, title="Much Ado About Foreign Keys", pub_date=datetime.datetime.now(), ) # Repoint the FK constraint old_field = Book._meta.get_field("author") new_field = ForeignKey(Tag, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) self.assertForeignKeyExists(Book, 'author_id', 'schema_tag') @skipUnlessDBFeature('can_create_inline_fk') def test_inline_fk(self): # Create some tables. with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) editor.create_model(Note) self.assertForeignKeyNotExists(Note, 'book_id', 'schema_book') # Add a foreign key from one to the other. with connection.schema_editor() as editor: new_field = ForeignKey(Book, CASCADE) new_field.set_attributes_from_name('book') editor.add_field(Note, new_field) self.assertForeignKeyExists(Note, 'book_id', 'schema_book') # Creating a FK field with a constraint uses a single statement without # a deferred ALTER TABLE. self.assertFalse([ sql for sql in (str(statement) for statement in editor.deferred_sql) if sql.startswith('ALTER TABLE') and 'ADD CONSTRAINT' in sql ]) @skipUnlessDBFeature('supports_foreign_keys') def test_char_field_with_db_index_to_fk(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(AuthorCharFieldWithIndex) # Change CharField to FK old_field = AuthorCharFieldWithIndex._meta.get_field('char_field') new_field = ForeignKey(Author, CASCADE, blank=True) new_field.set_attributes_from_name('char_field') with connection.schema_editor() as editor: editor.alter_field(AuthorCharFieldWithIndex, old_field, new_field, strict=True) self.assertForeignKeyExists(AuthorCharFieldWithIndex, 'char_field_id', 'schema_author') @skipUnlessDBFeature('supports_foreign_keys') @skipUnlessDBFeature('supports_index_on_text_field') def test_text_field_with_db_index_to_fk(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(AuthorTextFieldWithIndex) # Change TextField to FK old_field = AuthorTextFieldWithIndex._meta.get_field('text_field') new_field = ForeignKey(Author, CASCADE, blank=True) new_field.set_attributes_from_name('text_field') with connection.schema_editor() as editor: editor.alter_field(AuthorTextFieldWithIndex, old_field, new_field, strict=True) self.assertForeignKeyExists(AuthorTextFieldWithIndex, 'text_field_id', 'schema_author') @isolate_apps('schema') def test_char_field_pk_to_auto_field(self): class Foo(Model): id = CharField(max_length=255, primary_key=True) class Meta: app_label = 'schema' with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field('id') new_field = AutoField(primary_key=True) new_field.set_attributes_from_name('id') new_field.model = Foo with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) @skipUnlessDBFeature('supports_foreign_keys') def test_fk_to_proxy(self): "Creating a FK to a proxy model creates database constraints." class AuthorProxy(Author): class Meta: app_label = 'schema' apps = new_apps proxy = True class AuthorRef(Model): author = ForeignKey(AuthorProxy, on_delete=CASCADE) class Meta: app_label = 'schema' apps = new_apps self.local_models = [AuthorProxy, AuthorRef] # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(AuthorRef) self.assertForeignKeyExists(AuthorRef, 'author_id', 'schema_author') @skipUnlessDBFeature('supports_foreign_keys') def test_fk_db_constraint(self): "The db_constraint parameter is respected" # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(Author) editor.create_model(BookWeak) # Initial tables are there list(Author.objects.all()) list(Tag.objects.all()) list(BookWeak.objects.all()) self.assertForeignKeyNotExists(BookWeak, 'author_id', 'schema_author') # Make a db_constraint=False FK new_field = ForeignKey(Tag, CASCADE, db_constraint=False) new_field.set_attributes_from_name("tag") with connection.schema_editor() as editor: editor.add_field(Author, new_field) self.assertForeignKeyNotExists(Author, 'tag_id', 'schema_tag') # Alter to one with a constraint new_field2 = ForeignKey(Tag, CASCADE) new_field2.set_attributes_from_name("tag") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) self.assertForeignKeyExists(Author, 'tag_id', 'schema_tag') # Alter to one without a constraint again new_field2 = ForeignKey(Tag, CASCADE) new_field2.set_attributes_from_name("tag") with connection.schema_editor() as editor: editor.alter_field(Author, new_field2, new_field, strict=True) self.assertForeignKeyNotExists(Author, 'tag_id', 'schema_tag') @isolate_apps('schema') def test_no_db_constraint_added_during_primary_key_change(self): """ When a primary key that's pointed to by a ForeignKey with db_constraint=False is altered, a foreign key constraint isn't added. """ class Author(Model): class Meta: app_label = 'schema' class BookWeak(Model): author = ForeignKey(Author, CASCADE, db_constraint=False) class Meta: app_label = 'schema' with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWeak) self.assertForeignKeyNotExists(BookWeak, 'author_id', 'schema_author') old_field = Author._meta.get_field('id') new_field = BigAutoField(primary_key=True) new_field.model = Author new_field.set_attributes_from_name('id') # @isolate_apps() and inner models are needed to have the model # relations populated, otherwise this doesn't act as a regression test. self.assertEqual(len(new_field.model._meta.related_objects), 1) with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertForeignKeyNotExists(BookWeak, 'author_id', 'schema_author') def _test_m2m_db_constraint(self, M2MFieldClass): class LocalAuthorWithM2M(Model): name = CharField(max_length=255) class Meta: app_label = 'schema' apps = new_apps self.local_models = [LocalAuthorWithM2M] # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(LocalAuthorWithM2M) # Initial tables are there list(LocalAuthorWithM2M.objects.all()) list(Tag.objects.all()) # Make a db_constraint=False FK new_field = M2MFieldClass(Tag, related_name="authors", db_constraint=False) new_field.contribute_to_class(LocalAuthorWithM2M, "tags") # Add the field with connection.schema_editor() as editor: editor.add_field(LocalAuthorWithM2M, new_field) self.assertForeignKeyNotExists(new_field.remote_field.through, 'tag_id', 'schema_tag') @skipUnlessDBFeature('supports_foreign_keys') def test_m2m_db_constraint(self): self._test_m2m_db_constraint(ManyToManyField) @skipUnlessDBFeature('supports_foreign_keys') def test_m2m_db_constraint_custom(self): self._test_m2m_db_constraint(CustomManyToManyField) @skipUnlessDBFeature('supports_foreign_keys') def test_m2m_db_constraint_inherited(self): self._test_m2m_db_constraint(InheritedManyToManyField) def test_add_field(self): """ Tests adding fields to models """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add the new field new_field = IntegerField(null=True) new_field.set_attributes_from_name("age") with CaptureQueriesContext(connection) as ctx, connection.schema_editor() as editor: editor.add_field(Author, new_field) drop_default_sql = editor.sql_alter_column_no_default % { 'column': editor.quote_name(new_field.name), } self.assertFalse(any(drop_default_sql in query['sql'] for query in ctx.captured_queries)) # Ensure the field is right afterwards columns = self.column_classes(Author) self.assertEqual(columns['age'][0], "IntegerField") self.assertEqual(columns['age'][1][6], True) def test_add_field_remove_field(self): """ Adding a field and removing it removes all deferred sql referring to it. """ with connection.schema_editor() as editor: # Create a table with a unique constraint on the slug field. editor.create_model(Tag) # Remove the slug column. editor.remove_field(Tag, Tag._meta.get_field('slug')) self.assertEqual(editor.deferred_sql, []) def test_add_field_temp_default(self): """ Tests adding fields to models with a temporary default """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add a not-null field new_field = CharField(max_length=30, default="Godwin") new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure the field is right afterwards columns = self.column_classes(Author) self.assertEqual(columns['surname'][0], "CharField") self.assertEqual(columns['surname'][1][6], connection.features.interprets_empty_strings_as_nulls) def test_add_field_temp_default_boolean(self): """ Tests adding fields to models with a temporary default where the default is False. (#21783) """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add a not-null field new_field = BooleanField(default=False) new_field.set_attributes_from_name("awesome") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure the field is right afterwards columns = self.column_classes(Author) # BooleanField are stored as TINYINT(1) on MySQL. field_type = columns['awesome'][0] self.assertEqual(field_type, connection.features.introspected_boolean_field_type) def test_add_field_default_transform(self): """ Tests adding fields to models with a default that is not directly valid in the database (#22581) """ class TestTransformField(IntegerField): # Weird field that saves the count of items in its value def get_default(self): return self.default def get_prep_value(self, value): if value is None: return 0 return len(value) # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add the field with a default it needs to cast (to string in this case) new_field = TestTransformField(default={1: 2}) new_field.set_attributes_from_name("thing") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure the field is there columns = self.column_classes(Author) field_type, field_info = columns['thing'] self.assertEqual(field_type, 'IntegerField') # Make sure the values were transformed correctly self.assertEqual(Author.objects.extra(where=["thing = 1"]).count(), 2) def test_add_field_binary(self): """ Tests binary fields get a sane default (#22851) """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Add the new field new_field = BinaryField(blank=True) new_field.set_attributes_from_name("bits") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure the field is right afterwards columns = self.column_classes(Author) # MySQL annoyingly uses the same backend, so it'll come back as one of # these two types. self.assertIn(columns['bits'][0], ("BinaryField", "TextField")) @unittest.skipUnless(connection.vendor == 'mysql', "MySQL specific") def test_add_binaryfield_mediumblob(self): """ Test adding a custom-sized binary field on MySQL (#24846). """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Add the new field with default new_field = MediumBlobField(blank=True, default=b'123') new_field.set_attributes_from_name('bits') with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) # Introspection treats BLOBs as TextFields self.assertEqual(columns['bits'][0], "TextField") def test_alter(self): """ Tests simple altering of fields """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertEqual(columns['name'][0], "CharField") self.assertEqual(bool(columns['name'][1][6]), bool(connection.features.interprets_empty_strings_as_nulls)) # Alter the name field to a TextField old_field = Author._meta.get_field("name") new_field = TextField(null=True) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) # Ensure the field is right afterwards columns = self.column_classes(Author) self.assertEqual(columns['name'][0], "TextField") self.assertEqual(columns['name'][1][6], True) # Change nullability again new_field2 = TextField(null=False) new_field2.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) # Ensure the field is right afterwards columns = self.column_classes(Author) self.assertEqual(columns['name'][0], "TextField") self.assertEqual(bool(columns['name'][1][6]), bool(connection.features.interprets_empty_strings_as_nulls)) def test_alter_auto_field_to_integer_field(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Change AutoField to IntegerField old_field = Author._meta.get_field('id') new_field = IntegerField(primary_key=True) new_field.set_attributes_from_name('id') new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) def test_alter_auto_field_to_char_field(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Change AutoField to CharField old_field = Author._meta.get_field('id') new_field = CharField(primary_key=True, max_length=50) new_field.set_attributes_from_name('id') new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) @isolate_apps('schema') def test_alter_auto_field_quoted_db_column(self): class Foo(Model): id = AutoField(primary_key=True, db_column='"quoted_id"') class Meta: app_label = 'schema' with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field('id') new_field = BigAutoField(primary_key=True) new_field.model = Foo new_field.db_column = '"quoted_id"' new_field.set_attributes_from_name('id') with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) Foo.objects.create() def test_alter_not_unique_field_to_primary_key(self): # Create the table. with connection.schema_editor() as editor: editor.create_model(Author) # Change UUIDField to primary key. old_field = Author._meta.get_field('uuid') new_field = UUIDField(primary_key=True) new_field.set_attributes_from_name('uuid') new_field.model = Author with connection.schema_editor() as editor: editor.remove_field(Author, Author._meta.get_field('id')) editor.alter_field(Author, old_field, new_field, strict=True) @isolate_apps('schema') def test_alter_primary_key_quoted_db_table(self): class Foo(Model): class Meta: app_label = 'schema' db_table = '"foo"' with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field('id') new_field = BigAutoField(primary_key=True) new_field.model = Foo new_field.set_attributes_from_name('id') with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) Foo.objects.create() def test_alter_text_field(self): # Regression for "BLOB/TEXT column 'info' can't have a default value") # on MySQL. # Create the table with connection.schema_editor() as editor: editor.create_model(Note) old_field = Note._meta.get_field("info") new_field = TextField(blank=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) @skipUnlessDBFeature('can_defer_constraint_checks', 'can_rollback_ddl') def test_alter_fk_checks_deferred_constraints(self): """ #25492 - Altering a foreign key's structure and data in the same transaction. """ with connection.schema_editor() as editor: editor.create_model(Node) old_field = Node._meta.get_field('parent') new_field = ForeignKey(Node, CASCADE) new_field.set_attributes_from_name('parent') parent = Node.objects.create() with connection.schema_editor() as editor: # Update the parent FK to create a deferred constraint check. Node.objects.update(parent=parent) editor.alter_field(Node, old_field, new_field, strict=True) def test_alter_text_field_to_date_field(self): """ #25002 - Test conversion of text field to date field. """ with connection.schema_editor() as editor: editor.create_model(Note) Note.objects.create(info='1988-05-05') old_field = Note._meta.get_field('info') new_field = DateField(blank=True) new_field.set_attributes_from_name('info') with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) # Make sure the field isn't nullable columns = self.column_classes(Note) self.assertFalse(columns['info'][1][6]) def test_alter_text_field_to_datetime_field(self): """ #25002 - Test conversion of text field to datetime field. """ with connection.schema_editor() as editor: editor.create_model(Note) Note.objects.create(info='1988-05-05 3:16:17.4567') old_field = Note._meta.get_field('info') new_field = DateTimeField(blank=True) new_field.set_attributes_from_name('info') with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) # Make sure the field isn't nullable columns = self.column_classes(Note) self.assertFalse(columns['info'][1][6]) def test_alter_text_field_to_time_field(self): """ #25002 - Test conversion of text field to time field. """ with connection.schema_editor() as editor: editor.create_model(Note) Note.objects.create(info='3:16:17.4567') old_field = Note._meta.get_field('info') new_field = TimeField(blank=True) new_field.set_attributes_from_name('info') with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) # Make sure the field isn't nullable columns = self.column_classes(Note) self.assertFalse(columns['info'][1][6]) @skipIfDBFeature('interprets_empty_strings_as_nulls') def test_alter_textual_field_keep_null_status(self): """ Changing a field type shouldn't affect the not null status. """ with connection.schema_editor() as editor: editor.create_model(Note) with self.assertRaises(IntegrityError): Note.objects.create(info=None) old_field = Note._meta.get_field("info") new_field = CharField(max_length=50) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) with self.assertRaises(IntegrityError): Note.objects.create(info=None) def test_alter_numeric_field_keep_null_status(self): """ Changing a field type shouldn't affect the not null status. """ with connection.schema_editor() as editor: editor.create_model(UniqueTest) with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=None, slug='aaa') old_field = UniqueTest._meta.get_field("year") new_field = BigIntegerField() new_field.set_attributes_from_name("year") with connection.schema_editor() as editor: editor.alter_field(UniqueTest, old_field, new_field, strict=True) with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=None, slug='bbb') def test_alter_null_to_not_null(self): """ #23609 - Tests handling of default values when altering from NULL to NOT NULL. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertTrue(columns['height'][1][6]) # Create some test data Author.objects.create(name='Not null author', height=12) Author.objects.create(name='Null author') # Verify null value self.assertEqual(Author.objects.get(name='Not null author').height, 12) self.assertIsNone(Author.objects.get(name='Null author').height) # Alter the height field to NOT NULL with default old_field = Author._meta.get_field("height") new_field = PositiveIntegerField(default=42) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) # Ensure the field is right afterwards columns = self.column_classes(Author) self.assertFalse(columns['height'][1][6]) # Verify default value self.assertEqual(Author.objects.get(name='Not null author').height, 12) self.assertEqual(Author.objects.get(name='Null author').height, 42) def test_alter_charfield_to_null(self): """ #24307 - Should skip an alter statement on databases with interprets_empty_strings_as_null when changing a CharField to null. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Change the CharField to null old_field = Author._meta.get_field('name') new_field = copy(old_field) new_field.null = True with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) @unittest.skipUnless(connection.vendor == 'postgresql', 'PostgreSQL specific') def test_alter_char_field_decrease_length(self): # Create the table. with connection.schema_editor() as editor: editor.create_model(Author) Author.objects.create(name='x' * 255) # Change max_length of CharField. old_field = Author._meta.get_field('name') new_field = CharField(max_length=254) new_field.set_attributes_from_name('name') with connection.schema_editor() as editor: msg = 'value too long for type character varying(254)' with self.assertRaisesMessage(DataError, msg): editor.alter_field(Author, old_field, new_field, strict=True) @unittest.skipUnless(connection.vendor == 'postgresql', 'PostgreSQL specific') def test_alter_field_with_custom_db_type(self): from django.contrib.postgres.fields import ArrayField class Foo(Model): field = ArrayField(CharField(max_length=255)) class Meta: app_label = 'schema' with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field('field') new_field = ArrayField(CharField(max_length=16)) new_field.set_attributes_from_name('field') new_field.model = Foo with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) def test_alter_textfield_to_null(self): """ #24307 - Should skip an alter statement on databases with interprets_empty_strings_as_null when changing a TextField to null. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Note) # Change the TextField to null old_field = Note._meta.get_field('info') new_field = copy(old_field) new_field.null = True with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) @skipUnlessDBFeature('supports_combined_alters') def test_alter_null_to_not_null_keeping_default(self): """ #23738 - Can change a nullable field with default to non-nullable with the same default. """ # Create the table with connection.schema_editor() as editor: editor.create_model(AuthorWithDefaultHeight) # Ensure the field is right to begin with columns = self.column_classes(AuthorWithDefaultHeight) self.assertTrue(columns['height'][1][6]) # Alter the height field to NOT NULL keeping the previous default old_field = AuthorWithDefaultHeight._meta.get_field("height") new_field = PositiveIntegerField(default=42) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(AuthorWithDefaultHeight, old_field, new_field, strict=True) # Ensure the field is right afterwards columns = self.column_classes(AuthorWithDefaultHeight) self.assertFalse(columns['height'][1][6]) @skipUnlessDBFeature('supports_foreign_keys') def test_alter_fk(self): """ Tests altering of FKs """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the field is right to begin with columns = self.column_classes(Book) self.assertEqual(columns['author_id'][0], "IntegerField") self.assertForeignKeyExists(Book, 'author_id', 'schema_author') # Alter the FK old_field = Book._meta.get_field("author") new_field = ForeignKey(Author, CASCADE, editable=False) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) # Ensure the field is right afterwards columns = self.column_classes(Book) self.assertEqual(columns['author_id'][0], "IntegerField") self.assertForeignKeyExists(Book, 'author_id', 'schema_author') @skipUnlessDBFeature('supports_foreign_keys') def test_alter_to_fk(self): """ #24447 - Tests adding a FK constraint for an existing column """ class LocalBook(Model): author = IntegerField() title = CharField(max_length=100, db_index=True) pub_date = DateTimeField() class Meta: app_label = 'schema' apps = new_apps self.local_models = [LocalBook] # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(LocalBook) # Ensure no FK constraint exists constraints = self.get_constraints(LocalBook._meta.db_table) for details in constraints.values(): if details['foreign_key']: self.fail('Found an unexpected FK constraint to %s' % details['columns']) old_field = LocalBook._meta.get_field("author") new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(LocalBook, old_field, new_field, strict=True) self.assertForeignKeyExists(LocalBook, 'author_id', 'schema_author') @skipUnlessDBFeature('supports_foreign_keys') def test_alter_o2o_to_fk(self): """ #24163 - Tests altering of OneToOneField to ForeignKey """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithO2O) # Ensure the field is right to begin with columns = self.column_classes(BookWithO2O) self.assertEqual(columns['author_id'][0], "IntegerField") # Ensure the field is unique author = Author.objects.create(name="Joe") BookWithO2O.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now()) with self.assertRaises(IntegrityError): BookWithO2O.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now()) BookWithO2O.objects.all().delete() self.assertForeignKeyExists(BookWithO2O, 'author_id', 'schema_author') # Alter the OneToOneField to ForeignKey old_field = BookWithO2O._meta.get_field("author") new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(BookWithO2O, old_field, new_field, strict=True) # Ensure the field is right afterwards columns = self.column_classes(Book) self.assertEqual(columns['author_id'][0], "IntegerField") # Ensure the field is not unique anymore Book.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now()) Book.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now()) self.assertForeignKeyExists(Book, 'author_id', 'schema_author') @skipUnlessDBFeature('supports_foreign_keys') def test_alter_fk_to_o2o(self): """ #24163 - Tests altering of ForeignKey to OneToOneField """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the field is right to begin with columns = self.column_classes(Book) self.assertEqual(columns['author_id'][0], "IntegerField") # Ensure the field is not unique author = Author.objects.create(name="Joe") Book.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now()) Book.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now()) Book.objects.all().delete() self.assertForeignKeyExists(Book, 'author_id', 'schema_author') # Alter the ForeignKey to OneToOneField old_field = Book._meta.get_field("author") new_field = OneToOneField(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) # Ensure the field is right afterwards columns = self.column_classes(BookWithO2O) self.assertEqual(columns['author_id'][0], "IntegerField") # Ensure the field is unique now BookWithO2O.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now()) with self.assertRaises(IntegrityError): BookWithO2O.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now()) self.assertForeignKeyExists(BookWithO2O, 'author_id', 'schema_author') def test_alter_field_fk_to_o2o(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) expected_fks = 1 if connection.features.supports_foreign_keys else 0 # Check the index is right to begin with. counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual(counts, {'fks': expected_fks, 'uniques': 0, 'indexes': 1}) old_field = Book._meta.get_field('author') new_field = OneToOneField(Author, CASCADE) new_field.set_attributes_from_name('author') with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) # The index on ForeignKey is replaced with a unique constraint for OneToOneField. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 1, 'indexes': 0}) def test_alter_field_fk_keeps_index(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) expected_fks = 1 if connection.features.supports_foreign_keys else 0 # Check the index is right to begin with. counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual(counts, {'fks': expected_fks, 'uniques': 0, 'indexes': 1}) old_field = Book._meta.get_field('author') # on_delete changed from CASCADE. new_field = ForeignKey(Author, PROTECT) new_field.set_attributes_from_name('author') with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) # The index remains. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 0, 'indexes': 1}) def test_alter_field_o2o_to_fk(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithO2O) expected_fks = 1 if connection.features.supports_foreign_keys else 0 # Check the unique constraint is right to begin with. counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual(counts, {'fks': expected_fks, 'uniques': 1, 'indexes': 0}) old_field = BookWithO2O._meta.get_field('author') new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name('author') with connection.schema_editor() as editor: editor.alter_field(BookWithO2O, old_field, new_field, strict=True) counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) # The unique constraint on OneToOneField is replaced with an index for ForeignKey. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 0, 'indexes': 1}) def test_alter_field_o2o_keeps_unique(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithO2O) expected_fks = 1 if connection.features.supports_foreign_keys else 0 # Check the unique constraint is right to begin with. counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual(counts, {'fks': expected_fks, 'uniques': 1, 'indexes': 0}) old_field = BookWithO2O._meta.get_field('author') # on_delete changed from CASCADE. new_field = OneToOneField(Author, PROTECT) new_field.set_attributes_from_name('author') with connection.schema_editor() as editor: editor.alter_field(BookWithO2O, old_field, new_field, strict=True) counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) # The unique constraint remains. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 1, 'indexes': 0}) @skipUnlessDBFeature('ignores_table_name_case') def test_alter_db_table_case(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Alter the case of the table old_table_name = Author._meta.db_table with connection.schema_editor() as editor: editor.alter_db_table(Author, old_table_name, old_table_name.upper()) def test_alter_implicit_id_to_explicit(self): """ Should be able to convert an implicit "id" field to an explicit "id" primary key field. """ with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("id") new_field = AutoField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) # This will fail if DROP DEFAULT is inadvertently executed on this # field which drops the id sequence, at least on PostgreSQL. Author.objects.create(name='Foo') Author.objects.create(name='Bar') def test_alter_autofield_pk_to_bigautofield_pk_sequence_owner(self): """ Converting an implicit PK to BigAutoField(primary_key=True) should keep a sequence owner on PostgreSQL. """ with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field('id') new_field = BigAutoField(primary_key=True) new_field.set_attributes_from_name('id') new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) Author.objects.create(name='Foo', pk=1) with connection.cursor() as cursor: sequence_reset_sqls = connection.ops.sequence_reset_sql(no_style(), [Author]) if sequence_reset_sqls: cursor.execute(sequence_reset_sqls[0]) # Fail on PostgreSQL if sequence is missing an owner. self.assertIsNotNone(Author.objects.create(name='Bar')) def test_alter_autofield_pk_to_smallautofield_pk_sequence_owner(self): """ Converting an implicit PK to SmallAutoField(primary_key=True) should keep a sequence owner on PostgreSQL. """ with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field('id') new_field = SmallAutoField(primary_key=True) new_field.set_attributes_from_name('id') new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) Author.objects.create(name='Foo', pk=1) with connection.cursor() as cursor: sequence_reset_sqls = connection.ops.sequence_reset_sql(no_style(), [Author]) if sequence_reset_sqls: cursor.execute(sequence_reset_sqls[0]) # Fail on PostgreSQL if sequence is missing an owner. self.assertIsNotNone(Author.objects.create(name='Bar')) def test_alter_int_pk_to_autofield_pk(self): """ Should be able to rename an IntegerField(primary_key=True) to AutoField(primary_key=True). """ with connection.schema_editor() as editor: editor.create_model(IntegerPK) old_field = IntegerPK._meta.get_field('i') new_field = AutoField(primary_key=True) new_field.model = IntegerPK new_field.set_attributes_from_name('i') with connection.schema_editor() as editor: editor.alter_field(IntegerPK, old_field, new_field, strict=True) def test_alter_int_pk_to_bigautofield_pk(self): """ Should be able to rename an IntegerField(primary_key=True) to BigAutoField(primary_key=True). """ with connection.schema_editor() as editor: editor.create_model(IntegerPK) old_field = IntegerPK._meta.get_field('i') new_field = BigAutoField(primary_key=True) new_field.model = IntegerPK new_field.set_attributes_from_name('i') with connection.schema_editor() as editor: editor.alter_field(IntegerPK, old_field, new_field, strict=True) @isolate_apps('schema') def test_alter_smallint_pk_to_smallautofield_pk(self): """ Should be able to rename an SmallIntegerField(primary_key=True) to SmallAutoField(primary_key=True). """ class SmallIntegerPK(Model): i = SmallIntegerField(primary_key=True) class Meta: app_label = 'schema' with connection.schema_editor() as editor: editor.create_model(SmallIntegerPK) self.isolated_local_models = [SmallIntegerPK] old_field = SmallIntegerPK._meta.get_field('i') new_field = SmallAutoField(primary_key=True) new_field.model = SmallIntegerPK new_field.set_attributes_from_name('i') with connection.schema_editor() as editor: editor.alter_field(SmallIntegerPK, old_field, new_field, strict=True) def test_alter_int_pk_to_int_unique(self): """ Should be able to rename an IntegerField(primary_key=True) to IntegerField(unique=True). """ with connection.schema_editor() as editor: editor.create_model(IntegerPK) # Delete the old PK old_field = IntegerPK._meta.get_field('i') new_field = IntegerField(unique=True) new_field.model = IntegerPK new_field.set_attributes_from_name('i') with connection.schema_editor() as editor: editor.alter_field(IntegerPK, old_field, new_field, strict=True) # The primary key constraint is gone. Result depends on database: # 'id' for SQLite, None for others (must not be 'i'). self.assertIn(self.get_primary_key(IntegerPK._meta.db_table), ('id', None)) # Set up a model class as it currently stands. The original IntegerPK # class is now out of date and some backends make use of the whole # model class when modifying a field (such as sqlite3 when remaking a # table) so an outdated model class leads to incorrect results. class Transitional(Model): i = IntegerField(unique=True) j = IntegerField(unique=True) class Meta: app_label = 'schema' apps = new_apps db_table = 'INTEGERPK' # model requires a new PK old_field = Transitional._meta.get_field('j') new_field = IntegerField(primary_key=True) new_field.model = Transitional new_field.set_attributes_from_name('j') with connection.schema_editor() as editor: editor.alter_field(Transitional, old_field, new_field, strict=True) # Create a model class representing the updated model. class IntegerUnique(Model): i = IntegerField(unique=True) j = IntegerField(primary_key=True) class Meta: app_label = 'schema' apps = new_apps db_table = 'INTEGERPK' # Ensure unique constraint works. IntegerUnique.objects.create(i=1, j=1) with self.assertRaises(IntegrityError): IntegerUnique.objects.create(i=1, j=2) def test_rename(self): """ Tests simple altering of fields """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertEqual(columns['name'][0], "CharField") self.assertNotIn("display_name", columns) # Alter the name field's name old_field = Author._meta.get_field("name") new_field = CharField(max_length=254) new_field.set_attributes_from_name("display_name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) # Ensure the field is right afterwards columns = self.column_classes(Author) self.assertEqual(columns['display_name'][0], "CharField") self.assertNotIn("name", columns) @isolate_apps('schema') def test_rename_referenced_field(self): class Author(Model): name = CharField(max_length=255, unique=True) class Meta: app_label = 'schema' class Book(Model): author = ForeignKey(Author, CASCADE, to_field='name') class Meta: app_label = 'schema' with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name('renamed') with connection.schema_editor(atomic=connection.features.supports_atomic_references_rename) as editor: editor.alter_field(Author, Author._meta.get_field('name'), new_field) # Ensure the foreign key reference was updated. self.assertForeignKeyExists(Book, 'author_id', 'schema_author', 'renamed') @skipIfDBFeature('interprets_empty_strings_as_nulls') def test_rename_keep_null_status(self): """ Renaming a field shouldn't affect the not null status. """ with connection.schema_editor() as editor: editor.create_model(Note) with self.assertRaises(IntegrityError): Note.objects.create(info=None) old_field = Note._meta.get_field("info") new_field = TextField() new_field.set_attributes_from_name("detail_info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) columns = self.column_classes(Note) self.assertEqual(columns['detail_info'][0], "TextField") self.assertNotIn("info", columns) with self.assertRaises(IntegrityError): NoteRename.objects.create(detail_info=None) def _test_m2m_create(self, M2MFieldClass): """ Tests M2M fields on models during creation """ class LocalBookWithM2M(Model): author = ForeignKey(Author, CASCADE) title = CharField(max_length=100, db_index=True) pub_date = DateTimeField() tags = M2MFieldClass("TagM2MTest", related_name="books") class Meta: app_label = 'schema' apps = new_apps self.local_models = [LocalBookWithM2M] # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(TagM2MTest) editor.create_model(LocalBookWithM2M) # Ensure there is now an m2m table there columns = self.column_classes(LocalBookWithM2M._meta.get_field("tags").remote_field.through) self.assertEqual(columns['tagm2mtest_id'][0], "IntegerField") def test_m2m_create(self): self._test_m2m_create(ManyToManyField) def test_m2m_create_custom(self): self._test_m2m_create(CustomManyToManyField) def test_m2m_create_inherited(self): self._test_m2m_create(InheritedManyToManyField) def _test_m2m_create_through(self, M2MFieldClass): """ Tests M2M fields on models during creation with through models """ class LocalTagThrough(Model): book = ForeignKey("schema.LocalBookWithM2MThrough", CASCADE) tag = ForeignKey("schema.TagM2MTest", CASCADE) class Meta: app_label = 'schema' apps = new_apps class LocalBookWithM2MThrough(Model): tags = M2MFieldClass("TagM2MTest", related_name="books", through=LocalTagThrough) class Meta: app_label = 'schema' apps = new_apps self.local_models = [LocalTagThrough, LocalBookWithM2MThrough] # Create the tables with connection.schema_editor() as editor: editor.create_model(LocalTagThrough) editor.create_model(TagM2MTest) editor.create_model(LocalBookWithM2MThrough) # Ensure there is now an m2m table there columns = self.column_classes(LocalTagThrough) self.assertEqual(columns['book_id'][0], "IntegerField") self.assertEqual(columns['tag_id'][0], "IntegerField") def test_m2m_create_through(self): self._test_m2m_create_through(ManyToManyField) def test_m2m_create_through_custom(self): self._test_m2m_create_through(CustomManyToManyField) def test_m2m_create_through_inherited(self): self._test_m2m_create_through(InheritedManyToManyField) def _test_m2m(self, M2MFieldClass): """ Tests adding/removing M2M fields on models """ class LocalAuthorWithM2M(Model): name = CharField(max_length=255) class Meta: app_label = 'schema' apps = new_apps self.local_models = [LocalAuthorWithM2M] # Create the tables with connection.schema_editor() as editor: editor.create_model(LocalAuthorWithM2M) editor.create_model(TagM2MTest) # Create an M2M field new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors") new_field.contribute_to_class(LocalAuthorWithM2M, "tags") # Ensure there's no m2m table there with self.assertRaises(DatabaseError): self.column_classes(new_field.remote_field.through) # Add the field with connection.schema_editor() as editor: editor.add_field(LocalAuthorWithM2M, new_field) # Ensure there is now an m2m table there columns = self.column_classes(new_field.remote_field.through) self.assertEqual(columns['tagm2mtest_id'][0], "IntegerField") # "Alter" the field. This should not rename the DB table to itself. with connection.schema_editor() as editor: editor.alter_field(LocalAuthorWithM2M, new_field, new_field, strict=True) # Remove the M2M table again with connection.schema_editor() as editor: editor.remove_field(LocalAuthorWithM2M, new_field) # Ensure there's no m2m table there with self.assertRaises(DatabaseError): self.column_classes(new_field.remote_field.through) # Make sure the model state is coherent with the table one now that # we've removed the tags field. opts = LocalAuthorWithM2M._meta opts.local_many_to_many.remove(new_field) del new_apps.all_models['schema'][new_field.remote_field.through._meta.model_name] opts._expire_cache() def test_m2m(self): self._test_m2m(ManyToManyField) def test_m2m_custom(self): self._test_m2m(CustomManyToManyField) def test_m2m_inherited(self): self._test_m2m(InheritedManyToManyField) def _test_m2m_through_alter(self, M2MFieldClass): """ Tests altering M2Ms with explicit through models (should no-op) """ class LocalAuthorTag(Model): author = ForeignKey("schema.LocalAuthorWithM2MThrough", CASCADE) tag = ForeignKey("schema.TagM2MTest", CASCADE) class Meta: app_label = 'schema' apps = new_apps class LocalAuthorWithM2MThrough(Model): name = CharField(max_length=255) tags = M2MFieldClass("schema.TagM2MTest", related_name="authors", through=LocalAuthorTag) class Meta: app_label = 'schema' apps = new_apps self.local_models = [LocalAuthorTag, LocalAuthorWithM2MThrough] # Create the tables with connection.schema_editor() as editor: editor.create_model(LocalAuthorTag) editor.create_model(LocalAuthorWithM2MThrough) editor.create_model(TagM2MTest) # Ensure the m2m table is there self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3) # "Alter" the field's blankness. This should not actually do anything. old_field = LocalAuthorWithM2MThrough._meta.get_field("tags") new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors", through=LocalAuthorTag) new_field.contribute_to_class(LocalAuthorWithM2MThrough, "tags") with connection.schema_editor() as editor: editor.alter_field(LocalAuthorWithM2MThrough, old_field, new_field, strict=True) # Ensure the m2m table is still there self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3) def test_m2m_through_alter(self): self._test_m2m_through_alter(ManyToManyField) def test_m2m_through_alter_custom(self): self._test_m2m_through_alter(CustomManyToManyField) def test_m2m_through_alter_inherited(self): self._test_m2m_through_alter(InheritedManyToManyField) def _test_m2m_repoint(self, M2MFieldClass): """ Tests repointing M2M fields """ class LocalBookWithM2M(Model): author = ForeignKey(Author, CASCADE) title = CharField(max_length=100, db_index=True) pub_date = DateTimeField() tags = M2MFieldClass("TagM2MTest", related_name="books") class Meta: app_label = 'schema' apps = new_apps self.local_models = [LocalBookWithM2M] # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(LocalBookWithM2M) editor.create_model(TagM2MTest) editor.create_model(UniqueTest) # Ensure the M2M exists and points to TagM2MTest if connection.features.supports_foreign_keys: self.assertForeignKeyExists( LocalBookWithM2M._meta.get_field("tags").remote_field.through, 'tagm2mtest_id', 'schema_tagm2mtest', ) # Repoint the M2M old_field = LocalBookWithM2M._meta.get_field("tags") new_field = M2MFieldClass(UniqueTest) new_field.contribute_to_class(LocalBookWithM2M, "uniques") with connection.schema_editor() as editor: editor.alter_field(LocalBookWithM2M, old_field, new_field, strict=True) # Ensure old M2M is gone with self.assertRaises(DatabaseError): self.column_classes(LocalBookWithM2M._meta.get_field("tags").remote_field.through) # This model looks like the new model and is used for teardown. opts = LocalBookWithM2M._meta opts.local_many_to_many.remove(old_field) # Ensure the new M2M exists and points to UniqueTest if connection.features.supports_foreign_keys: self.assertForeignKeyExists(new_field.remote_field.through, 'uniquetest_id', 'schema_uniquetest') def test_m2m_repoint(self): self._test_m2m_repoint(ManyToManyField) def test_m2m_repoint_custom(self): self._test_m2m_repoint(CustomManyToManyField) def test_m2m_repoint_inherited(self): self._test_m2m_repoint(InheritedManyToManyField) @isolate_apps('schema') def test_m2m_rename_field_in_target_model(self): class LocalTagM2MTest(Model): title = CharField(max_length=255) class Meta: app_label = 'schema' class LocalM2M(Model): tags = ManyToManyField(LocalTagM2MTest) class Meta: app_label = 'schema' # Create the tables. with connection.schema_editor() as editor: editor.create_model(LocalM2M) editor.create_model(LocalTagM2MTest) self.isolated_local_models = [LocalM2M, LocalTagM2MTest] # Ensure the m2m table is there. self.assertEqual(len(self.column_classes(LocalM2M)), 1) # Alter a field in LocalTagM2MTest. old_field = LocalTagM2MTest._meta.get_field('title') new_field = CharField(max_length=254) new_field.contribute_to_class(LocalTagM2MTest, 'title1') # @isolate_apps() and inner models are needed to have the model # relations populated, otherwise this doesn't act as a regression test. self.assertEqual(len(new_field.model._meta.related_objects), 1) with connection.schema_editor() as editor: editor.alter_field(LocalTagM2MTest, old_field, new_field, strict=True) # Ensure the m2m table is still there. self.assertEqual(len(self.column_classes(LocalM2M)), 1) @skipUnlessDBFeature('supports_column_check_constraints', 'can_introspect_check_constraints') def test_check_constraints(self): """ Tests creating/deleting CHECK constraints """ # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the constraint exists constraints = self.get_constraints(Author._meta.db_table) if not any(details['columns'] == ['height'] and details['check'] for details in constraints.values()): self.fail("No check constraint for height found") # Alter the column to remove it old_field = Author._meta.get_field("height") new_field = IntegerField(null=True, blank=True) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) constraints = self.get_constraints(Author._meta.db_table) for details in constraints.values(): if details['columns'] == ["height"] and details['check']: self.fail("Check constraint for height found") # Alter the column to re-add it new_field2 = Author._meta.get_field("height") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) constraints = self.get_constraints(Author._meta.db_table) if not any(details['columns'] == ['height'] and details['check'] for details in constraints.values()): self.fail("No check constraint for height found") @skipUnlessDBFeature('supports_column_check_constraints', 'can_introspect_check_constraints') def test_remove_field_check_does_not_remove_meta_constraints(self): with connection.schema_editor() as editor: editor.create_model(Author) # Add the custom check constraint constraint = CheckConstraint(check=Q(height__gte=0), name='author_height_gte_0_check') custom_constraint_name = constraint.name Author._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) # Ensure the constraints exist constraints = self.get_constraints(Author._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['height'] and details['check'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Alter the column to remove field check old_field = Author._meta.get_field('height') new_field = IntegerField(null=True, blank=True) new_field.set_attributes_from_name('height') with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) constraints = self.get_constraints(Author._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['height'] and details['check'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 0) # Alter the column to re-add field check new_field2 = Author._meta.get_field('height') with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) constraints = self.get_constraints(Author._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['height'] and details['check'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Drop the check constraint with connection.schema_editor() as editor: Author._meta.constraints = [] editor.remove_constraint(Author, constraint) def test_unique(self): """ Tests removing and adding unique constraints to a single column. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) # Ensure the field is unique to begin with Tag.objects.create(title="foo", slug="foo") with self.assertRaises(IntegrityError): Tag.objects.create(title="bar", slug="foo") Tag.objects.all().delete() # Alter the slug field to be non-unique old_field = Tag._meta.get_field("slug") new_field = SlugField(unique=False) new_field.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, old_field, new_field, strict=True) # Ensure the field is no longer unique Tag.objects.create(title="foo", slug="foo") Tag.objects.create(title="bar", slug="foo") Tag.objects.all().delete() # Alter the slug field to be unique new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, new_field, new_field2, strict=True) # Ensure the field is unique again Tag.objects.create(title="foo", slug="foo") with self.assertRaises(IntegrityError): Tag.objects.create(title="bar", slug="foo") Tag.objects.all().delete() # Rename the field new_field3 = SlugField(unique=True) new_field3.set_attributes_from_name("slug2") with connection.schema_editor() as editor: editor.alter_field(Tag, new_field2, new_field3, strict=True) # Ensure the field is still unique TagUniqueRename.objects.create(title="foo", slug2="foo") with self.assertRaises(IntegrityError): TagUniqueRename.objects.create(title="bar", slug2="foo") Tag.objects.all().delete() def test_unique_name_quoting(self): old_table_name = TagUniqueRename._meta.db_table try: with connection.schema_editor() as editor: editor.create_model(TagUniqueRename) editor.alter_db_table(TagUniqueRename, old_table_name, 'unique-table') TagUniqueRename._meta.db_table = 'unique-table' # This fails if the unique index name isn't quoted. editor.alter_unique_together(TagUniqueRename, [], (('title', 'slug2'),)) finally: TagUniqueRename._meta.db_table = old_table_name @isolate_apps('schema') @unittest.skipIf(connection.vendor == 'sqlite', 'SQLite naively remakes the table on field alteration.') @skipUnlessDBFeature('supports_foreign_keys') def test_unique_no_unnecessary_fk_drops(self): """ If AlterField isn't selective about dropping foreign key constraints when modifying a field with a unique constraint, the AlterField incorrectly drops and recreates the Book.author foreign key even though it doesn't restrict the field being changed (#29193). """ class Author(Model): name = CharField(max_length=254, unique=True) class Meta: app_label = 'schema' class Book(Model): author = ForeignKey(Author, CASCADE) class Meta: app_label = 'schema' with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) new_field = CharField(max_length=255, unique=True) new_field.model = Author new_field.set_attributes_from_name('name') with self.assertLogs('django.db.backends.schema', 'DEBUG') as cm: with connection.schema_editor() as editor: editor.alter_field(Author, Author._meta.get_field('name'), new_field) # One SQL statement is executed to alter the field. self.assertEqual(len(cm.records), 1) @isolate_apps('schema') @unittest.skipIf(connection.vendor == 'sqlite', 'SQLite remakes the table on field alteration.') def test_unique_and_reverse_m2m(self): """ AlterField can modify a unique field when there's a reverse M2M relation on the model. """ class Tag(Model): title = CharField(max_length=255) slug = SlugField(unique=True) class Meta: app_label = 'schema' class Book(Model): tags = ManyToManyField(Tag, related_name='books') class Meta: app_label = 'schema' self.isolated_local_models = [Book._meta.get_field('tags').remote_field.through] with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(Book) new_field = SlugField(max_length=75, unique=True) new_field.model = Tag new_field.set_attributes_from_name('slug') with self.assertLogs('django.db.backends.schema', 'DEBUG') as cm: with connection.schema_editor() as editor: editor.alter_field(Tag, Tag._meta.get_field('slug'), new_field) # One SQL statement is executed to alter the field. self.assertEqual(len(cm.records), 1) # Ensure that the field is still unique. Tag.objects.create(title='foo', slug='foo') with self.assertRaises(IntegrityError): Tag.objects.create(title='bar', slug='foo') @skipUnlessDBFeature('allows_multiple_constraints_on_same_fields') def test_remove_field_unique_does_not_remove_meta_constraints(self): with connection.schema_editor() as editor: editor.create_model(AuthorWithUniqueName) # Add the custom unique constraint constraint = UniqueConstraint(fields=['name'], name='author_name_uniq') custom_constraint_name = constraint.name AuthorWithUniqueName._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(AuthorWithUniqueName, constraint) # Ensure the constraints exist constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name'] and details['unique'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Alter the column to remove field uniqueness old_field = AuthorWithUniqueName._meta.get_field('name') new_field = CharField(max_length=255) new_field.set_attributes_from_name('name') with connection.schema_editor() as editor: editor.alter_field(AuthorWithUniqueName, old_field, new_field, strict=True) constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name'] and details['unique'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 0) # Alter the column to re-add field uniqueness new_field2 = AuthorWithUniqueName._meta.get_field('name') with connection.schema_editor() as editor: editor.alter_field(AuthorWithUniqueName, new_field, new_field2, strict=True) constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name'] and details['unique'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Drop the unique constraint with connection.schema_editor() as editor: AuthorWithUniqueName._meta.constraints = [] editor.remove_constraint(AuthorWithUniqueName, constraint) def test_unique_together(self): """ Tests removing and adding unique_together constraints on a model. """ # Create the table with connection.schema_editor() as editor: editor.create_model(UniqueTest) # Ensure the fields are unique to begin with UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.create(year=2011, slug="foo") UniqueTest.objects.create(year=2011, slug="bar") with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.all().delete() # Alter the model to its non-unique-together companion with connection.schema_editor() as editor: editor.alter_unique_together(UniqueTest, UniqueTest._meta.unique_together, []) # Ensure the fields are no longer unique UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.all().delete() # Alter it back new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_unique_together(UniqueTest, [], UniqueTest._meta.unique_together) # Ensure the fields are unique again UniqueTest.objects.create(year=2012, slug="foo") with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.all().delete() def test_unique_together_with_fk(self): """ Tests removing and adding unique_together constraints that include a foreign key. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the fields are unique to begin with self.assertEqual(Book._meta.unique_together, ()) # Add the unique_together constraint with connection.schema_editor() as editor: editor.alter_unique_together(Book, [], [['author', 'title']]) # Alter it back with connection.schema_editor() as editor: editor.alter_unique_together(Book, [['author', 'title']], []) def test_unique_together_with_fk_with_existing_index(self): """ Tests removing and adding unique_together constraints that include a foreign key, where the foreign key is added after the model is created. """ # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithoutAuthor) new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name('author') editor.add_field(BookWithoutAuthor, new_field) # Ensure the fields aren't unique to begin with self.assertEqual(Book._meta.unique_together, ()) # Add the unique_together constraint with connection.schema_editor() as editor: editor.alter_unique_together(Book, [], [['author', 'title']]) # Alter it back with connection.schema_editor() as editor: editor.alter_unique_together(Book, [['author', 'title']], []) @skipUnlessDBFeature('allows_multiple_constraints_on_same_fields') def test_remove_unique_together_does_not_remove_meta_constraints(self): with connection.schema_editor() as editor: editor.create_model(AuthorWithUniqueNameAndBirthday) # Add the custom unique constraint constraint = UniqueConstraint(fields=['name', 'birthday'], name='author_name_birthday_uniq') custom_constraint_name = constraint.name AuthorWithUniqueNameAndBirthday._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(AuthorWithUniqueNameAndBirthday, constraint) # Ensure the constraints exist constraints = self.get_constraints(AuthorWithUniqueNameAndBirthday._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name', 'birthday'] and details['unique'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Remove unique together unique_together = AuthorWithUniqueNameAndBirthday._meta.unique_together with connection.schema_editor() as editor: editor.alter_unique_together(AuthorWithUniqueNameAndBirthday, unique_together, []) constraints = self.get_constraints(AuthorWithUniqueNameAndBirthday._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name', 'birthday'] and details['unique'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 0) # Re-add unique together with connection.schema_editor() as editor: editor.alter_unique_together(AuthorWithUniqueNameAndBirthday, [], unique_together) constraints = self.get_constraints(AuthorWithUniqueNameAndBirthday._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name', 'birthday'] and details['unique'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Drop the unique constraint with connection.schema_editor() as editor: AuthorWithUniqueNameAndBirthday._meta.constraints = [] editor.remove_constraint(AuthorWithUniqueNameAndBirthday, constraint) def test_index_together(self): """ Tests removing and adding index_together constraints on a model. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) # Ensure there's no index on the year/slug columns first self.assertEqual( False, any( c["index"] for c in self.get_constraints("schema_tag").values() if c['columns'] == ["slug", "title"] ), ) # Alter the model to add an index with connection.schema_editor() as editor: editor.alter_index_together(Tag, [], [("slug", "title")]) # Ensure there is now an index self.assertEqual( True, any( c["index"] for c in self.get_constraints("schema_tag").values() if c['columns'] == ["slug", "title"] ), ) # Alter it back new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_index_together(Tag, [("slug", "title")], []) # Ensure there's no index self.assertEqual( False, any( c["index"] for c in self.get_constraints("schema_tag").values() if c['columns'] == ["slug", "title"] ), ) def test_index_together_with_fk(self): """ Tests removing and adding index_together constraints that include a foreign key. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the fields are unique to begin with self.assertEqual(Book._meta.index_together, ()) # Add the unique_together constraint with connection.schema_editor() as editor: editor.alter_index_together(Book, [], [['author', 'title']]) # Alter it back with connection.schema_editor() as editor: editor.alter_index_together(Book, [['author', 'title']], []) def test_create_index_together(self): """ Tests creating models with index_together already defined """ # Create the table with connection.schema_editor() as editor: editor.create_model(TagIndexed) # Ensure there is an index self.assertEqual( True, any( c["index"] for c in self.get_constraints("schema_tagindexed").values() if c['columns'] == ["slug", "title"] ), ) @skipUnlessDBFeature('allows_multiple_constraints_on_same_fields') def test_remove_index_together_does_not_remove_meta_indexes(self): with connection.schema_editor() as editor: editor.create_model(AuthorWithIndexedNameAndBirthday) # Add the custom index index = Index(fields=['name', 'birthday'], name='author_name_birthday_idx') custom_index_name = index.name AuthorWithIndexedNameAndBirthday._meta.indexes = [index] with connection.schema_editor() as editor: editor.add_index(AuthorWithIndexedNameAndBirthday, index) # Ensure the indexes exist constraints = self.get_constraints(AuthorWithIndexedNameAndBirthday._meta.db_table) self.assertIn(custom_index_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name', 'birthday'] and details['index'] and name != custom_index_name ] self.assertEqual(len(other_constraints), 1) # Remove index together index_together = AuthorWithIndexedNameAndBirthday._meta.index_together with connection.schema_editor() as editor: editor.alter_index_together(AuthorWithIndexedNameAndBirthday, index_together, []) constraints = self.get_constraints(AuthorWithIndexedNameAndBirthday._meta.db_table) self.assertIn(custom_index_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name', 'birthday'] and details['index'] and name != custom_index_name ] self.assertEqual(len(other_constraints), 0) # Re-add index together with connection.schema_editor() as editor: editor.alter_index_together(AuthorWithIndexedNameAndBirthday, [], index_together) constraints = self.get_constraints(AuthorWithIndexedNameAndBirthday._meta.db_table) self.assertIn(custom_index_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name', 'birthday'] and details['index'] and name != custom_index_name ] self.assertEqual(len(other_constraints), 1) # Drop the index with connection.schema_editor() as editor: AuthorWithIndexedNameAndBirthday._meta.indexes = [] editor.remove_index(AuthorWithIndexedNameAndBirthday, index) @isolate_apps('schema') def test_db_table(self): """ Tests renaming of the table """ class Author(Model): name = CharField(max_length=255) class Meta: app_label = 'schema' class Book(Model): author = ForeignKey(Author, CASCADE) class Meta: app_label = 'schema' # Create the table and one referring it. with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the table is there to begin with columns = self.column_classes(Author) self.assertEqual(columns['name'][0], "CharField") # Alter the table with connection.schema_editor(atomic=connection.features.supports_atomic_references_rename) as editor: editor.alter_db_table(Author, "schema_author", "schema_otherauthor") # Ensure the table is there afterwards Author._meta.db_table = "schema_otherauthor" columns = self.column_classes(Author) self.assertEqual(columns['name'][0], "CharField") # Ensure the foreign key reference was updated self.assertForeignKeyExists(Book, "author_id", "schema_otherauthor") # Alter the table again with connection.schema_editor(atomic=connection.features.supports_atomic_references_rename) as editor: editor.alter_db_table(Author, "schema_otherauthor", "schema_author") # Ensure the table is still there Author._meta.db_table = "schema_author" columns = self.column_classes(Author) self.assertEqual(columns['name'][0], "CharField") def test_add_remove_index(self): """ Tests index addition and removal """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the table is there and has no index self.assertNotIn('title', self.get_indexes(Author._meta.db_table)) # Add the index index = Index(fields=['name'], name='author_title_idx') with connection.schema_editor() as editor: editor.add_index(Author, index) self.assertIn('name', self.get_indexes(Author._meta.db_table)) # Drop the index with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn('name', self.get_indexes(Author._meta.db_table)) def test_remove_db_index_doesnt_remove_custom_indexes(self): """ Changing db_index to False doesn't remove indexes from Meta.indexes. """ with connection.schema_editor() as editor: editor.create_model(AuthorWithIndexedName) # Ensure the table has its index self.assertIn('name', self.get_indexes(AuthorWithIndexedName._meta.db_table)) # Add the custom index index = Index(fields=['-name'], name='author_name_idx') author_index_name = index.name with connection.schema_editor() as editor: db_index_name = editor._create_index_name( table_name=AuthorWithIndexedName._meta.db_table, column_names=('name',), ) try: AuthorWithIndexedName._meta.indexes = [index] with connection.schema_editor() as editor: editor.add_index(AuthorWithIndexedName, index) old_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table) self.assertIn(author_index_name, old_constraints) self.assertIn(db_index_name, old_constraints) # Change name field to db_index=False old_field = AuthorWithIndexedName._meta.get_field('name') new_field = CharField(max_length=255) new_field.set_attributes_from_name('name') with connection.schema_editor() as editor: editor.alter_field(AuthorWithIndexedName, old_field, new_field, strict=True) new_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table) self.assertNotIn(db_index_name, new_constraints) # The index from Meta.indexes is still in the database. self.assertIn(author_index_name, new_constraints) # Drop the index with connection.schema_editor() as editor: editor.remove_index(AuthorWithIndexedName, index) finally: AuthorWithIndexedName._meta.indexes = [] def test_order_index(self): """ Indexes defined with ordering (ASC/DESC) defined on column """ with connection.schema_editor() as editor: editor.create_model(Author) # The table doesn't have an index self.assertNotIn('title', self.get_indexes(Author._meta.db_table)) index_name = 'author_name_idx' # Add the index index = Index(fields=['name', '-weight'], name=index_name) with connection.schema_editor() as editor: editor.add_index(Author, index) if connection.features.supports_index_column_ordering: self.assertIndexOrder(Author._meta.db_table, index_name, ['ASC', 'DESC']) # Drop the index with connection.schema_editor() as editor: editor.remove_index(Author, index) def test_indexes(self): """ Tests creation/altering of indexes """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the table is there and has the right index self.assertIn( "title", self.get_indexes(Book._meta.db_table), ) # Alter to remove the index old_field = Book._meta.get_field("title") new_field = CharField(max_length=100, db_index=False) new_field.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) # Ensure the table is there and has no index self.assertNotIn( "title", self.get_indexes(Book._meta.db_table), ) # Alter to re-add the index new_field2 = Book._meta.get_field("title") with connection.schema_editor() as editor: editor.alter_field(Book, new_field, new_field2, strict=True) # Ensure the table is there and has the index again self.assertIn( "title", self.get_indexes(Book._meta.db_table), ) # Add a unique column, verify that creates an implicit index new_field3 = BookWithSlug._meta.get_field("slug") with connection.schema_editor() as editor: editor.add_field(Book, new_field3) self.assertIn( "slug", self.get_uniques(Book._meta.db_table), ) # Remove the unique, check the index goes with it new_field4 = CharField(max_length=20, unique=False) new_field4.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(BookWithSlug, new_field3, new_field4, strict=True) self.assertNotIn( "slug", self.get_uniques(Book._meta.db_table), ) def test_text_field_with_db_index(self): with connection.schema_editor() as editor: editor.create_model(AuthorTextFieldWithIndex) # The text_field index is present if the database supports it. assertion = self.assertIn if connection.features.supports_index_on_text_field else self.assertNotIn assertion('text_field', self.get_indexes(AuthorTextFieldWithIndex._meta.db_table)) def test_primary_key(self): """ Tests altering of the primary key """ # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) # Ensure the table is there and has the right PK self.assertEqual(self.get_primary_key(Tag._meta.db_table), 'id') # Alter to change the PK id_field = Tag._meta.get_field("id") old_field = Tag._meta.get_field("slug") new_field = SlugField(primary_key=True) new_field.set_attributes_from_name("slug") new_field.model = Tag with connection.schema_editor() as editor: editor.remove_field(Tag, id_field) editor.alter_field(Tag, old_field, new_field) # Ensure the PK changed self.assertNotIn( 'id', self.get_indexes(Tag._meta.db_table), ) self.assertEqual(self.get_primary_key(Tag._meta.db_table), 'slug') def test_context_manager_exit(self): """ Ensures transaction is correctly closed when an error occurs inside a SchemaEditor context. """ class SomeError(Exception): pass try: with connection.schema_editor(): raise SomeError except SomeError: self.assertFalse(connection.in_atomic_block) @skipIfDBFeature('can_rollback_ddl') def test_unsupported_transactional_ddl_disallowed(self): message = ( "Executing DDL statements while in a transaction on databases " "that can't perform a rollback is prohibited." ) with atomic(), connection.schema_editor() as editor: with self.assertRaisesMessage(TransactionManagementError, message): editor.execute(editor.sql_create_table % {'table': 'foo', 'definition': ''}) @skipUnlessDBFeature('supports_foreign_keys') def test_foreign_key_index_long_names_regression(self): """ Regression test for #21497. Only affects databases that supports foreign keys. """ # Create the table with connection.schema_editor() as editor: editor.create_model(AuthorWithEvenLongerName) editor.create_model(BookWithLongName) # Find the properly shortened column name column_name = connection.ops.quote_name("author_foreign_key_with_really_long_field_name_id") column_name = column_name[1:-1].lower() # unquote, and, for Oracle, un-upcase # Ensure the table is there and has an index on the column self.assertIn( column_name, self.get_indexes(BookWithLongName._meta.db_table), ) @skipUnlessDBFeature('supports_foreign_keys') def test_add_foreign_key_long_names(self): """ Regression test for #23009. Only affects databases that supports foreign keys. """ # Create the initial tables with connection.schema_editor() as editor: editor.create_model(AuthorWithEvenLongerName) editor.create_model(BookWithLongName) # Add a second FK, this would fail due to long ref name before the fix new_field = ForeignKey(AuthorWithEvenLongerName, CASCADE, related_name="something") new_field.set_attributes_from_name("author_other_really_long_named_i_mean_so_long_fk") with connection.schema_editor() as editor: editor.add_field(BookWithLongName, new_field) @isolate_apps('schema') @skipUnlessDBFeature('supports_foreign_keys') def test_add_foreign_key_quoted_db_table(self): class Author(Model): class Meta: db_table = '"table_author_double_quoted"' app_label = 'schema' class Book(Model): author = ForeignKey(Author, CASCADE) class Meta: app_label = 'schema' with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) if connection.vendor == 'mysql': self.assertForeignKeyExists(Book, 'author_id', '"table_author_double_quoted"') else: self.assertForeignKeyExists(Book, 'author_id', 'table_author_double_quoted') def test_add_foreign_object(self): with connection.schema_editor() as editor: editor.create_model(BookForeignObj) new_field = ForeignObject(Author, on_delete=CASCADE, from_fields=['author_id'], to_fields=['id']) new_field.set_attributes_from_name('author') with connection.schema_editor() as editor: editor.add_field(BookForeignObj, new_field) def test_creation_deletion_reserved_names(self): """ Tries creating a model's table, and then deleting it when it has a SQL reserved name. """ # Create the table with connection.schema_editor() as editor: try: editor.create_model(Thing) except OperationalError as e: self.fail("Errors when applying initial migration for a model " "with a table named after an SQL reserved word: %s" % e) # The table is there list(Thing.objects.all()) # Clean up that table with connection.schema_editor() as editor: editor.delete_model(Thing) # The table is gone with self.assertRaises(DatabaseError): list(Thing.objects.all()) def test_remove_constraints_capital_letters(self): """ #23065 - Constraint names must be quoted if they contain capital letters. """ def get_field(*args, field_class=IntegerField, **kwargs): kwargs['db_column'] = "CamelCase" field = field_class(*args, **kwargs) field.set_attributes_from_name("CamelCase") return field model = Author field = get_field() table = model._meta.db_table column = field.column identifier_converter = connection.introspection.identifier_converter with connection.schema_editor() as editor: editor.create_model(model) editor.add_field(model, field) constraint_name = 'CamelCaseIndex' expected_constraint_name = identifier_converter(constraint_name) editor.execute( editor.sql_create_index % { "table": editor.quote_name(table), "name": editor.quote_name(constraint_name), "using": "", "columns": editor.quote_name(column), "extra": "", "condition": "", } ) self.assertIn(expected_constraint_name, self.get_constraints(model._meta.db_table)) editor.alter_field(model, get_field(db_index=True), field, strict=True) self.assertNotIn(expected_constraint_name, self.get_constraints(model._meta.db_table)) constraint_name = 'CamelCaseUniqConstraint' expected_constraint_name = identifier_converter(constraint_name) editor.execute(editor._create_unique_sql(model, [field.column], constraint_name)) self.assertIn(expected_constraint_name, self.get_constraints(model._meta.db_table)) editor.alter_field(model, get_field(unique=True), field, strict=True) self.assertNotIn(expected_constraint_name, self.get_constraints(model._meta.db_table)) if editor.sql_create_fk: constraint_name = 'CamelCaseFKConstraint' expected_constraint_name = identifier_converter(constraint_name) editor.execute( editor.sql_create_fk % { "table": editor.quote_name(table), "name": editor.quote_name(constraint_name), "column": editor.quote_name(column), "to_table": editor.quote_name(table), "to_column": editor.quote_name(model._meta.auto_field.column), "deferrable": connection.ops.deferrable_sql(), } ) self.assertIn(expected_constraint_name, self.get_constraints(model._meta.db_table)) editor.alter_field(model, get_field(Author, CASCADE, field_class=ForeignKey), field, strict=True) self.assertNotIn(expected_constraint_name, self.get_constraints(model._meta.db_table)) def test_add_field_use_effective_default(self): """ #23987 - effective_default() should be used as the field default when adding a new field. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no surname field columns = self.column_classes(Author) self.assertNotIn("surname", columns) # Create a row Author.objects.create(name='Anonymous1') # Add new CharField to ensure default will be used from effective_default new_field = CharField(max_length=15, blank=True) new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure field was added with the right default with connection.cursor() as cursor: cursor.execute("SELECT surname FROM schema_author;") item = cursor.fetchall()[0] self.assertEqual(item[0], None if connection.features.interprets_empty_strings_as_nulls else '') def test_add_field_default_dropped(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no surname field columns = self.column_classes(Author) self.assertNotIn("surname", columns) # Create a row Author.objects.create(name='Anonymous1') # Add new CharField with a default new_field = CharField(max_length=15, blank=True, default='surname default') new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure field was added with the right default with connection.cursor() as cursor: cursor.execute("SELECT surname FROM schema_author;") item = cursor.fetchall()[0] self.assertEqual(item[0], 'surname default') # And that the default is no longer set in the database. field = next( f for f in connection.introspection.get_table_description(cursor, "schema_author") if f.name == "surname" ) if connection.features.can_introspect_default: self.assertIsNone(field.default) def test_alter_field_default_dropped(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Create a row Author.objects.create(name='Anonymous1') self.assertIsNone(Author.objects.get().height) old_field = Author._meta.get_field('height') # The default from the new field is used in updating existing rows. new_field = IntegerField(blank=True, default=42) new_field.set_attributes_from_name('height') with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual(Author.objects.get().height, 42) # The database default should be removed. with connection.cursor() as cursor: field = next( f for f in connection.introspection.get_table_description(cursor, "schema_author") if f.name == "height" ) if connection.features.can_introspect_default: self.assertIsNone(field.default) @unittest.skipIf(connection.vendor == 'sqlite', 'SQLite naively remakes the table on field alteration.') def test_alter_field_default_doesnt_perform_queries(self): """ No queries are performed if a field default changes and the field's not changing from null to non-null. """ with connection.schema_editor() as editor: editor.create_model(AuthorWithDefaultHeight) old_field = AuthorWithDefaultHeight._meta.get_field('height') new_default = old_field.default * 2 new_field = PositiveIntegerField(null=True, blank=True, default=new_default) new_field.set_attributes_from_name('height') with connection.schema_editor() as editor, self.assertNumQueries(0): editor.alter_field(AuthorWithDefaultHeight, old_field, new_field, strict=True) def test_add_textfield_unhashable_default(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Create a row Author.objects.create(name='Anonymous1') # Create a field that has an unhashable default new_field = TextField(default={}) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.add_field(Author, new_field) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_add_indexed_charfield(self): field = CharField(max_length=255, db_index=True) field.set_attributes_from_name('nom_de_plume') with connection.schema_editor() as editor: editor.create_model(Author) editor.add_field(Author, field) # Should create two indexes; one for like operator. self.assertEqual( self.get_constraints_for_column(Author, 'nom_de_plume'), ['schema_author_nom_de_plume_7570a851', 'schema_author_nom_de_plume_7570a851_like'], ) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_add_unique_charfield(self): field = CharField(max_length=255, unique=True) field.set_attributes_from_name('nom_de_plume') with connection.schema_editor() as editor: editor.create_model(Author) editor.add_field(Author, field) # Should create two indexes; one for like operator. self.assertEqual( self.get_constraints_for_column(Author, 'nom_de_plume'), ['schema_author_nom_de_plume_7570a851_like', 'schema_author_nom_de_plume_key'] ) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_alter_field_add_index_to_charfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Author) self.assertEqual(self.get_constraints_for_column(Author, 'name'), []) # Alter to add db_index=True and create 2 indexes. old_field = Author._meta.get_field('name') new_field = CharField(max_length=255, db_index=True) new_field.set_attributes_from_name('name') with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Author, 'name'), ['schema_author_name_1fbc5617', 'schema_author_name_1fbc5617_like'] ) # Remove db_index=True to drop both indexes. with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, 'name'), []) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_alter_field_add_unique_to_charfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Author) self.assertEqual(self.get_constraints_for_column(Author, 'name'), []) # Alter to add unique=True and create 2 indexes. old_field = Author._meta.get_field('name') new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name('name') with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Author, 'name'), ['schema_author_name_1fbc5617_like', 'schema_author_name_1fbc5617_uniq'] ) # Remove unique=True to drop both indexes. with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, 'name'), []) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_alter_field_add_index_to_textfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Note) self.assertEqual(self.get_constraints_for_column(Note, 'info'), []) # Alter to add db_index=True and create 2 indexes. old_field = Note._meta.get_field('info') new_field = TextField(db_index=True) new_field.set_attributes_from_name('info') with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Note, 'info'), ['schema_note_info_4b0ea695', 'schema_note_info_4b0ea695_like'] ) # Remove db_index=True to drop both indexes. with connection.schema_editor() as editor: editor.alter_field(Note, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Note, 'info'), []) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_alter_field_add_unique_to_charfield_with_db_index(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(BookWithoutAuthor) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff', 'schema_book_title_2dfb2dff_like'] ) # Alter to add unique=True (should replace the index) old_field = BookWithoutAuthor._meta.get_field('title') new_field = CharField(max_length=100, db_index=True, unique=True) new_field.set_attributes_from_name('title') with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff_like', 'schema_book_title_2dfb2dff_uniq'] ) # Alter to remove unique=True (should drop unique index) new_field2 = CharField(max_length=100, db_index=True) new_field2.set_attributes_from_name('title') with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff', 'schema_book_title_2dfb2dff_like'] ) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_alter_field_remove_unique_and_db_index_from_charfield(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(BookWithoutAuthor) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff', 'schema_book_title_2dfb2dff_like'] ) # Alter to add unique=True (should replace the index) old_field = BookWithoutAuthor._meta.get_field('title') new_field = CharField(max_length=100, db_index=True, unique=True) new_field.set_attributes_from_name('title') with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff_like', 'schema_book_title_2dfb2dff_uniq'] ) # Alter to remove both unique=True and db_index=True (should drop all indexes) new_field2 = CharField(max_length=100) new_field2.set_attributes_from_name('title') with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True) self.assertEqual(self.get_constraints_for_column(BookWithoutAuthor, 'title'), []) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_alter_field_swap_unique_and_db_index_with_charfield(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(BookWithoutAuthor) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff', 'schema_book_title_2dfb2dff_like'] ) # Alter to set unique=True and remove db_index=True (should replace the index) old_field = BookWithoutAuthor._meta.get_field('title') new_field = CharField(max_length=100, unique=True) new_field.set_attributes_from_name('title') with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff_like', 'schema_book_title_2dfb2dff_uniq'] ) # Alter to set db_index=True and remove unique=True (should restore index) new_field2 = CharField(max_length=100, db_index=True) new_field2.set_attributes_from_name('title') with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff', 'schema_book_title_2dfb2dff_like'] ) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_alter_field_add_db_index_to_charfield_with_unique(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(Tag) self.assertEqual( self.get_constraints_for_column(Tag, 'slug'), ['schema_tag_slug_2c418ba3_like', 'schema_tag_slug_key'] ) # Alter to add db_index=True old_field = Tag._meta.get_field('slug') new_field = SlugField(db_index=True, unique=True) new_field.set_attributes_from_name('slug') with connection.schema_editor() as editor: editor.alter_field(Tag, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Tag, 'slug'), ['schema_tag_slug_2c418ba3_like', 'schema_tag_slug_key'] ) # Alter to remove db_index=True new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name('slug') with connection.schema_editor() as editor: editor.alter_field(Tag, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(Tag, 'slug'), ['schema_tag_slug_2c418ba3_like', 'schema_tag_slug_key'] ) def test_alter_field_add_index_to_integerfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Author) self.assertEqual(self.get_constraints_for_column(Author, 'weight'), []) # Alter to add db_index=True and create index. old_field = Author._meta.get_field('weight') new_field = IntegerField(null=True, db_index=True) new_field.set_attributes_from_name('weight') with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, 'weight'), ['schema_author_weight_587740f9']) # Remove db_index=True to drop index. with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, 'weight'), []) def test_alter_pk_with_self_referential_field(self): """ Changing the primary key field name of a model with a self-referential foreign key (#26384). """ with connection.schema_editor() as editor: editor.create_model(Node) old_field = Node._meta.get_field('node_id') new_field = AutoField(primary_key=True) new_field.set_attributes_from_name('id') with connection.schema_editor() as editor: editor.alter_field(Node, old_field, new_field, strict=True) self.assertForeignKeyExists(Node, 'parent_id', Node._meta.db_table) @mock.patch('django.db.backends.base.schema.datetime') @mock.patch('django.db.backends.base.schema.timezone') def test_add_datefield_and_datetimefield_use_effective_default(self, mocked_datetime, mocked_tz): """ effective_default() should be used for DateField, DateTimeField, and TimeField if auto_now or auto_add_now is set (#25005). """ now = datetime.datetime(month=1, day=1, year=2000, hour=1, minute=1) now_tz = datetime.datetime(month=1, day=1, year=2000, hour=1, minute=1, tzinfo=timezone.utc) mocked_datetime.now = mock.MagicMock(return_value=now) mocked_tz.now = mock.MagicMock(return_value=now_tz) # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Check auto_now/auto_now_add attributes are not defined columns = self.column_classes(Author) self.assertNotIn("dob_auto_now", columns) self.assertNotIn("dob_auto_now_add", columns) self.assertNotIn("dtob_auto_now", columns) self.assertNotIn("dtob_auto_now_add", columns) self.assertNotIn("tob_auto_now", columns) self.assertNotIn("tob_auto_now_add", columns) # Create a row Author.objects.create(name='Anonymous1') # Ensure fields were added with the correct defaults dob_auto_now = DateField(auto_now=True) dob_auto_now.set_attributes_from_name('dob_auto_now') self.check_added_field_default( editor, Author, dob_auto_now, 'dob_auto_now', now.date(), cast_function=lambda x: x.date(), ) dob_auto_now_add = DateField(auto_now_add=True) dob_auto_now_add.set_attributes_from_name('dob_auto_now_add') self.check_added_field_default( editor, Author, dob_auto_now_add, 'dob_auto_now_add', now.date(), cast_function=lambda x: x.date(), ) dtob_auto_now = DateTimeField(auto_now=True) dtob_auto_now.set_attributes_from_name('dtob_auto_now') self.check_added_field_default( editor, Author, dtob_auto_now, 'dtob_auto_now', now, ) dt_tm_of_birth_auto_now_add = DateTimeField(auto_now_add=True) dt_tm_of_birth_auto_now_add.set_attributes_from_name('dtob_auto_now_add') self.check_added_field_default( editor, Author, dt_tm_of_birth_auto_now_add, 'dtob_auto_now_add', now, ) tob_auto_now = TimeField(auto_now=True) tob_auto_now.set_attributes_from_name('tob_auto_now') self.check_added_field_default( editor, Author, tob_auto_now, 'tob_auto_now', now.time(), cast_function=lambda x: x.time(), ) tob_auto_now_add = TimeField(auto_now_add=True) tob_auto_now_add.set_attributes_from_name('tob_auto_now_add') self.check_added_field_default( editor, Author, tob_auto_now_add, 'tob_auto_now_add', now.time(), cast_function=lambda x: x.time(), ) def test_namespaced_db_table_create_index_name(self): """ Table names are stripped of their namespace/schema before being used to generate index names. """ with connection.schema_editor() as editor: max_name_length = connection.ops.max_name_length() or 200 namespace = 'n' * max_name_length table_name = 't' * max_name_length namespaced_table_name = '"%s"."%s"' % (namespace, table_name) self.assertEqual( editor._create_index_name(table_name, []), editor._create_index_name(namespaced_table_name, []), ) @unittest.skipUnless(connection.vendor == 'oracle', 'Oracle specific db_table syntax') def test_creation_with_db_table_double_quotes(self): oracle_user = connection.creation._test_database_user() class Student(Model): name = CharField(max_length=30) class Meta: app_label = 'schema' apps = new_apps db_table = '"%s"."DJANGO_STUDENT_TABLE"' % oracle_user class Document(Model): name = CharField(max_length=30) students = ManyToManyField(Student) class Meta: app_label = 'schema' apps = new_apps db_table = '"%s"."DJANGO_DOCUMENT_TABLE"' % oracle_user self.local_models = [Student, Document] with connection.schema_editor() as editor: editor.create_model(Student) editor.create_model(Document) doc = Document.objects.create(name='Test Name') student = Student.objects.create(name='Some man') doc.students.add(student) def test_rename_table_renames_deferred_sql_references(self): atomic_rename = connection.features.supports_atomic_references_rename with connection.schema_editor(atomic=atomic_rename) as editor: editor.create_model(Author) editor.create_model(Book) editor.alter_db_table(Author, 'schema_author', 'schema_renamed_author') editor.alter_db_table(Author, 'schema_book', 'schema_renamed_book') self.assertGreater(len(editor.deferred_sql), 0) for statement in editor.deferred_sql: self.assertIs(statement.references_table('schema_author'), False) self.assertIs(statement.references_table('schema_book'), False) @unittest.skipIf(connection.vendor == 'sqlite', 'SQLite naively remakes the table on field alteration.') def test_rename_column_renames_deferred_sql_references(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) old_title = Book._meta.get_field('title') new_title = CharField(max_length=100, db_index=True) new_title.set_attributes_from_name('renamed_title') editor.alter_field(Book, old_title, new_title) old_author = Book._meta.get_field('author') new_author = ForeignKey(Author, CASCADE) new_author.set_attributes_from_name('renamed_author') editor.alter_field(Book, old_author, new_author) self.assertGreater(len(editor.deferred_sql), 0) for statement in editor.deferred_sql: self.assertIs(statement.references_column('book', 'title'), False) self.assertIs(statement.references_column('book', 'author_id'), False) @isolate_apps('schema') def test_referenced_field_without_constraint_rename_inside_atomic_block(self): """ Foreign keys without database level constraint don't prevent the field they reference from being renamed in an atomic block. """ class Foo(Model): field = CharField(max_length=255, unique=True) class Meta: app_label = 'schema' class Bar(Model): foo = ForeignKey(Foo, CASCADE, to_field='field', db_constraint=False) class Meta: app_label = 'schema' self.isolated_local_models = [Foo, Bar] with connection.schema_editor() as editor: editor.create_model(Foo) editor.create_model(Bar) new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name('renamed') with connection.schema_editor(atomic=True) as editor: editor.alter_field(Foo, Foo._meta.get_field('field'), new_field) @isolate_apps('schema') def test_referenced_table_without_constraint_rename_inside_atomic_block(self): """ Foreign keys without database level constraint don't prevent the table they reference from being renamed in an atomic block. """ class Foo(Model): field = CharField(max_length=255, unique=True) class Meta: app_label = 'schema' class Bar(Model): foo = ForeignKey(Foo, CASCADE, to_field='field', db_constraint=False) class Meta: app_label = 'schema' self.isolated_local_models = [Foo, Bar] with connection.schema_editor() as editor: editor.create_model(Foo) editor.create_model(Bar) new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name('renamed') with connection.schema_editor(atomic=True) as editor: editor.alter_db_table(Foo, Foo._meta.db_table, 'renamed_table') Foo._meta.db_table = 'renamed_table'
6f5c5d39d26026468f1e9d5656652dcdfd5c0a0ece4dbcebc47d3b173ae481c4
from django.core import checks from django.core.checks import Error, Warning from django.db import models from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import ( isolate_apps, modify_settings, override_settings, override_system_checks, ) class EmptyRouter: pass @isolate_apps('check_framework', attr_name='apps') @override_system_checks([checks.model_checks.check_all_models]) class DuplicateDBTableTests(SimpleTestCase): def test_collision_in_same_app(self): class Model1(models.Model): class Meta: db_table = 'test_table' class Model2(models.Model): class Meta: db_table = 'test_table' self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "db_table 'test_table' is used by multiple models: " "check_framework.Model1, check_framework.Model2.", obj='test_table', id='models.E028', ) ]) @override_settings(DATABASE_ROUTERS=['check_framework.test_model_checks.EmptyRouter']) def test_collision_in_same_app_database_routers_installed(self): class Model1(models.Model): class Meta: db_table = 'test_table' class Model2(models.Model): class Meta: db_table = 'test_table' self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ Warning( "db_table 'test_table' is used by multiple models: " "check_framework.Model1, check_framework.Model2.", hint=( 'You have configured settings.DATABASE_ROUTERS. Verify ' 'that check_framework.Model1, check_framework.Model2 are ' 'correctly routed to separate databases.' ), obj='test_table', id='models.W035', ) ]) @modify_settings(INSTALLED_APPS={'append': 'basic'}) @isolate_apps('basic', 'check_framework', kwarg_name='apps') def test_collision_across_apps(self, apps): class Model1(models.Model): class Meta: app_label = 'basic' db_table = 'test_table' class Model2(models.Model): class Meta: app_label = 'check_framework' db_table = 'test_table' self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [ Error( "db_table 'test_table' is used by multiple models: " "basic.Model1, check_framework.Model2.", obj='test_table', id='models.E028', ) ]) @modify_settings(INSTALLED_APPS={'append': 'basic'}) @override_settings(DATABASE_ROUTERS=['check_framework.test_model_checks.EmptyRouter']) @isolate_apps('basic', 'check_framework', kwarg_name='apps') def test_collision_across_apps_database_routers_installed(self, apps): class Model1(models.Model): class Meta: app_label = 'basic' db_table = 'test_table' class Model2(models.Model): class Meta: app_label = 'check_framework' db_table = 'test_table' self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [ Warning( "db_table 'test_table' is used by multiple models: " "basic.Model1, check_framework.Model2.", hint=( 'You have configured settings.DATABASE_ROUTERS. Verify ' 'that basic.Model1, check_framework.Model2 are correctly ' 'routed to separate databases.' ), obj='test_table', id='models.W035', ) ]) def test_no_collision_for_unmanaged_models(self): class Unmanaged(models.Model): class Meta: db_table = 'test_table' managed = False class Managed(models.Model): class Meta: db_table = 'test_table' self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) def test_no_collision_for_proxy_models(self): class Model(models.Model): class Meta: db_table = 'test_table' class ProxyModel(Model): class Meta: proxy = True self.assertEqual(Model._meta.db_table, ProxyModel._meta.db_table) self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) @isolate_apps('check_framework', attr_name='apps') @override_system_checks([checks.model_checks.check_all_models]) class IndexNameTests(SimpleTestCase): def test_collision_in_same_model(self): index = models.Index(fields=['id'], name='foo') class Model(models.Model): class Meta: indexes = [index, index] self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "index name 'foo' is not unique for model check_framework.Model.", id='models.E029', ), ]) def test_collision_in_different_models(self): index = models.Index(fields=['id'], name='foo') class Model1(models.Model): class Meta: indexes = [index] class Model2(models.Model): class Meta: indexes = [index] self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "index name 'foo' is not unique amongst models: " "check_framework.Model1, check_framework.Model2.", id='models.E030', ), ]) def test_collision_abstract_model(self): class AbstractModel(models.Model): class Meta: indexes = [models.Index(fields=['id'], name='foo')] abstract = True class Model1(AbstractModel): pass class Model2(AbstractModel): pass self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "index name 'foo' is not unique amongst models: " "check_framework.Model1, check_framework.Model2.", id='models.E030', ), ]) def test_no_collision_abstract_model_interpolation(self): class AbstractModel(models.Model): name = models.CharField(max_length=20) class Meta: indexes = [models.Index(fields=['name'], name='%(app_label)s_%(class)s_foo')] abstract = True class Model1(AbstractModel): pass class Model2(AbstractModel): pass self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) @modify_settings(INSTALLED_APPS={'append': 'basic'}) @isolate_apps('basic', 'check_framework', kwarg_name='apps') def test_collision_across_apps(self, apps): index = models.Index(fields=['id'], name='foo') class Model1(models.Model): class Meta: app_label = 'basic' indexes = [index] class Model2(models.Model): class Meta: app_label = 'check_framework' indexes = [index] self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [ Error( "index name 'foo' is not unique amongst models: basic.Model1, " "check_framework.Model2.", id='models.E030', ), ]) @modify_settings(INSTALLED_APPS={'append': 'basic'}) @isolate_apps('basic', 'check_framework', kwarg_name='apps') def test_no_collision_across_apps_interpolation(self, apps): index = models.Index(fields=['id'], name='%(app_label)s_%(class)s_foo') class Model1(models.Model): class Meta: app_label = 'basic' constraints = [index] class Model2(models.Model): class Meta: app_label = 'check_framework' constraints = [index] self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), []) @isolate_apps('check_framework', attr_name='apps') @override_system_checks([checks.model_checks.check_all_models]) @skipUnlessDBFeature('supports_table_check_constraints') class ConstraintNameTests(TestCase): def test_collision_in_same_model(self): class Model(models.Model): class Meta: constraints = [ models.CheckConstraint(check=models.Q(id__gt=0), name='foo'), models.CheckConstraint(check=models.Q(id__lt=100), name='foo'), ] self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique for model " "check_framework.Model.", id='models.E031', ), ]) def test_collision_in_different_models(self): constraint = models.CheckConstraint(check=models.Q(id__gt=0), name='foo') class Model1(models.Model): class Meta: constraints = [constraint] class Model2(models.Model): class Meta: constraints = [constraint] self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique amongst models: " "check_framework.Model1, check_framework.Model2.", id='models.E032', ), ]) def test_collision_abstract_model(self): class AbstractModel(models.Model): class Meta: constraints = [models.CheckConstraint(check=models.Q(id__gt=0), name='foo')] abstract = True class Model1(AbstractModel): pass class Model2(AbstractModel): pass self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique amongst models: " "check_framework.Model1, check_framework.Model2.", id='models.E032', ), ]) def test_no_collision_abstract_model_interpolation(self): class AbstractModel(models.Model): class Meta: constraints = [ models.CheckConstraint(check=models.Q(id__gt=0), name='%(app_label)s_%(class)s_foo'), ] abstract = True class Model1(AbstractModel): pass class Model2(AbstractModel): pass self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) @modify_settings(INSTALLED_APPS={'append': 'basic'}) @isolate_apps('basic', 'check_framework', kwarg_name='apps') def test_collision_across_apps(self, apps): constraint = models.CheckConstraint(check=models.Q(id__gt=0), name='foo') class Model1(models.Model): class Meta: app_label = 'basic' constraints = [constraint] class Model2(models.Model): class Meta: app_label = 'check_framework' constraints = [constraint] self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique amongst models: " "basic.Model1, check_framework.Model2.", id='models.E032', ), ]) @modify_settings(INSTALLED_APPS={'append': 'basic'}) @isolate_apps('basic', 'check_framework', kwarg_name='apps') def test_no_collision_across_apps_interpolation(self, apps): constraint = models.CheckConstraint(check=models.Q(id__gt=0), name='%(app_label)s_%(class)s_foo') class Model1(models.Model): class Meta: app_label = 'basic' constraints = [constraint] class Model2(models.Model): class Meta: app_label = 'check_framework' constraints = [constraint] self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [])
aee799a59cafcec31fd050440b46b27a7b8f07009ac5e355e8311ade3a4db5e3
from django.conf import settings from django.core.checks.security import base, csrf, sessions from django.test import SimpleTestCase from django.test.utils import override_settings class CheckSessionCookieSecureTest(SimpleTestCase): @property def func(self): from django.core.checks.security.sessions import check_session_cookie_secure return check_session_cookie_secure @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_secure_with_installed_app(self): """ Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions" is in INSTALLED_APPS. """ self.assertEqual(self.func(None), [sessions.W010]) @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=[], MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], ) def test_session_cookie_secure_with_middleware(self): """ Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE. """ self.assertEqual(self.func(None), [sessions.W011]) @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], ) def test_session_cookie_secure_both(self): """ If SESSION_COOKIE_SECURE is off and we find both the session app and the middleware, provide one common warning. """ self.assertEqual(self.func(None), [sessions.W012]) @override_settings( SESSION_COOKIE_SECURE=True, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], ) def test_session_cookie_secure_true(self): """ If SESSION_COOKIE_SECURE is on, there's no warning about it. """ self.assertEqual(self.func(None), []) class CheckSessionCookieHttpOnlyTest(SimpleTestCase): @property def func(self): from django.core.checks.security.sessions import check_session_cookie_httponly return check_session_cookie_httponly @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_httponly_with_installed_app(self): """ Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions" is in INSTALLED_APPS. """ self.assertEqual(self.func(None), [sessions.W013]) @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=[], MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], ) def test_session_cookie_httponly_with_middleware(self): """ Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE. """ self.assertEqual(self.func(None), [sessions.W014]) @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], ) def test_session_cookie_httponly_both(self): """ If SESSION_COOKIE_HTTPONLY is off and we find both the session app and the middleware, provide one common warning. """ self.assertEqual(self.func(None), [sessions.W015]) @override_settings( SESSION_COOKIE_HTTPONLY=True, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], ) def test_session_cookie_httponly_true(self): """ If SESSION_COOKIE_HTTPONLY is on, there's no warning about it. """ self.assertEqual(self.func(None), []) class CheckCSRFMiddlewareTest(SimpleTestCase): @property def func(self): from django.core.checks.security.csrf import check_csrf_middleware return check_csrf_middleware @override_settings(MIDDLEWARE=[]) def test_no_csrf_middleware(self): """ Warn if CsrfViewMiddleware isn't in MIDDLEWARE. """ self.assertEqual(self.func(None), [csrf.W003]) @override_settings(MIDDLEWARE=['django.middleware.csrf.CsrfViewMiddleware']) def test_with_csrf_middleware(self): self.assertEqual(self.func(None), []) class CheckCSRFCookieSecureTest(SimpleTestCase): @property def func(self): from django.core.checks.security.csrf import check_csrf_cookie_secure return check_csrf_cookie_secure @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_COOKIE_SECURE=False, ) def test_with_csrf_cookie_secure_false(self): """ Warn if CsrfViewMiddleware is in MIDDLEWARE but CSRF_COOKIE_SECURE isn't True. """ self.assertEqual(self.func(None), [csrf.W016]) @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_USE_SESSIONS=True, CSRF_COOKIE_SECURE=False, ) def test_use_sessions_with_csrf_cookie_secure_false(self): """ No warning if CSRF_COOKIE_SECURE isn't True while CSRF_USE_SESSIONS is True. """ self.assertEqual(self.func(None), []) @override_settings(MIDDLEWARE=[], CSRF_COOKIE_SECURE=False) def test_with_csrf_cookie_secure_false_no_middleware(self): """ No warning if CsrfViewMiddleware isn't in MIDDLEWARE, even if CSRF_COOKIE_SECURE is False. """ self.assertEqual(self.func(None), []) @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_COOKIE_SECURE=True, ) def test_with_csrf_cookie_secure_true(self): self.assertEqual(self.func(None), []) class CheckSecurityMiddlewareTest(SimpleTestCase): @property def func(self): from django.core.checks.security.base import check_security_middleware return check_security_middleware @override_settings(MIDDLEWARE=[]) def test_no_security_middleware(self): """ Warn if SecurityMiddleware isn't in MIDDLEWARE. """ self.assertEqual(self.func(None), [base.W001]) @override_settings(MIDDLEWARE=['django.middleware.security.SecurityMiddleware']) def test_with_security_middleware(self): self.assertEqual(self.func(None), []) class CheckStrictTransportSecurityTest(SimpleTestCase): @property def func(self): from django.core.checks.security.base import check_sts return check_sts @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_SECONDS=0, ) def test_no_sts(self): """ Warn if SECURE_HSTS_SECONDS isn't > 0. """ self.assertEqual(self.func(None), [base.W004]) @override_settings(MIDDLEWARE=[], SECURE_HSTS_SECONDS=0) def test_no_sts_no_middleware(self): """ Don't warn if SECURE_HSTS_SECONDS isn't > 0 and SecurityMiddleware isn't installed. """ self.assertEqual(self.func(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_SECONDS=3600, ) def test_with_sts(self): self.assertEqual(self.func(None), []) class CheckStrictTransportSecuritySubdomainsTest(SimpleTestCase): @property def func(self): from django.core.checks.security.base import check_sts_include_subdomains return check_sts_include_subdomains @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_INCLUDE_SUBDOMAINS=False, SECURE_HSTS_SECONDS=3600, ) def test_no_sts_subdomains(self): """ Warn if SECURE_HSTS_INCLUDE_SUBDOMAINS isn't True. """ self.assertEqual(self.func(None), [base.W005]) @override_settings( MIDDLEWARE=[], SECURE_HSTS_INCLUDE_SUBDOMAINS=False, SECURE_HSTS_SECONDS=3600, ) def test_no_sts_subdomains_no_middleware(self): """ Don't warn if SecurityMiddleware isn't installed. """ self.assertEqual(self.func(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, SECURE_HSTS_SECONDS=None, ) def test_no_sts_subdomains_no_seconds(self): """ Don't warn if SECURE_HSTS_SECONDS isn't set. """ self.assertEqual(self.func(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_INCLUDE_SUBDOMAINS=True, SECURE_HSTS_SECONDS=3600, ) def test_with_sts_subdomains(self): self.assertEqual(self.func(None), []) class CheckStrictTransportSecurityPreloadTest(SimpleTestCase): @property def func(self): from django.core.checks.security.base import check_sts_preload return check_sts_preload @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_PRELOAD=False, SECURE_HSTS_SECONDS=3600, ) def test_no_sts_preload(self): """ Warn if SECURE_HSTS_PRELOAD isn't True. """ self.assertEqual(self.func(None), [base.W021]) @override_settings(MIDDLEWARE=[], SECURE_HSTS_PRELOAD=False, SECURE_HSTS_SECONDS=3600) def test_no_sts_preload_no_middleware(self): """ Don't warn if SecurityMiddleware isn't installed. """ self.assertEqual(self.func(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, SECURE_HSTS_SECONDS=None, ) def test_no_sts_preload_no_seconds(self): """ Don't warn if SECURE_HSTS_SECONDS isn't set. """ self.assertEqual(self.func(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_PRELOAD=True, SECURE_HSTS_SECONDS=3600, ) def test_with_sts_preload(self): self.assertEqual(self.func(None), []) class CheckXFrameOptionsMiddlewareTest(SimpleTestCase): @property def func(self): from django.core.checks.security.base import check_xframe_options_middleware return check_xframe_options_middleware @override_settings(MIDDLEWARE=[]) def test_middleware_not_installed(self): """ Warn if XFrameOptionsMiddleware isn't in MIDDLEWARE. """ self.assertEqual(self.func(None), [base.W002]) @override_settings(MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"]) def test_middleware_installed(self): self.assertEqual(self.func(None), []) class CheckXFrameOptionsDenyTest(SimpleTestCase): @property def func(self): from django.core.checks.security.base import check_xframe_deny return check_xframe_deny @override_settings( MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"], X_FRAME_OPTIONS='SAMEORIGIN', ) def test_x_frame_options_not_deny(self): """ Warn if XFrameOptionsMiddleware is in MIDDLEWARE but X_FRAME_OPTIONS isn't 'DENY'. """ self.assertEqual(self.func(None), [base.W019]) @override_settings(MIDDLEWARE=[], X_FRAME_OPTIONS='SAMEORIGIN') def test_middleware_not_installed(self): """ No error if XFrameOptionsMiddleware isn't in MIDDLEWARE even if X_FRAME_OPTIONS isn't 'DENY'. """ self.assertEqual(self.func(None), []) @override_settings( MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"], X_FRAME_OPTIONS='DENY', ) def test_xframe_deny(self): self.assertEqual(self.func(None), []) class CheckContentTypeNosniffTest(SimpleTestCase): @property def func(self): from django.core.checks.security.base import check_content_type_nosniff return check_content_type_nosniff @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CONTENT_TYPE_NOSNIFF=False, ) def test_no_content_type_nosniff(self): """ Warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True. """ self.assertEqual(self.func(None), [base.W006]) @override_settings(MIDDLEWARE=[], SECURE_CONTENT_TYPE_NOSNIFF=False) def test_no_content_type_nosniff_no_middleware(self): """ Don't warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True and SecurityMiddleware isn't in MIDDLEWARE. """ self.assertEqual(self.func(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CONTENT_TYPE_NOSNIFF=True, ) def test_with_content_type_nosniff(self): self.assertEqual(self.func(None), []) class CheckSSLRedirectTest(SimpleTestCase): @property def func(self): from django.core.checks.security.base import check_ssl_redirect return check_ssl_redirect @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, ) def test_no_ssl_redirect(self): """ Warn if SECURE_SSL_REDIRECT isn't True. """ self.assertEqual(self.func(None), [base.W008]) @override_settings(MIDDLEWARE=[], SECURE_SSL_REDIRECT=False) def test_no_ssl_redirect_no_middleware(self): """ Don't warn if SECURE_SSL_REDIRECT is False and SecurityMiddleware isn't installed. """ self.assertEqual(self.func(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=True, ) def test_with_ssl_redirect(self): self.assertEqual(self.func(None), []) class CheckSecretKeyTest(SimpleTestCase): @property def func(self): from django.core.checks.security.base import check_secret_key return check_secret_key @override_settings(SECRET_KEY=('abcdefghijklmnopqrstuvwx' * 2) + 'ab') def test_okay_secret_key(self): self.assertEqual(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH) self.assertGreater(len(set(settings.SECRET_KEY)), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS) self.assertEqual(self.func(None), []) @override_settings(SECRET_KEY='') def test_empty_secret_key(self): self.assertEqual(self.func(None), [base.W009]) @override_settings(SECRET_KEY=None) def test_missing_secret_key(self): del settings.SECRET_KEY self.assertEqual(self.func(None), [base.W009]) @override_settings(SECRET_KEY=None) def test_none_secret_key(self): self.assertEqual(self.func(None), [base.W009]) @override_settings(SECRET_KEY=('abcdefghijklmnopqrstuvwx' * 2) + 'a') def test_low_length_secret_key(self): self.assertEqual(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH - 1) self.assertEqual(self.func(None), [base.W009]) @override_settings(SECRET_KEY='abcd' * 20) def test_low_entropy_secret_key(self): self.assertGreater(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH) self.assertLess(len(set(settings.SECRET_KEY)), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS) self.assertEqual(self.func(None), [base.W009]) class CheckDebugTest(SimpleTestCase): @property def func(self): from django.core.checks.security.base import check_debug return check_debug @override_settings(DEBUG=True) def test_debug_true(self): """ Warn if DEBUG is True. """ self.assertEqual(self.func(None), [base.W018]) @override_settings(DEBUG=False) def test_debug_false(self): self.assertEqual(self.func(None), []) class CheckAllowedHostsTest(SimpleTestCase): @property def func(self): from django.core.checks.security.base import check_allowed_hosts return check_allowed_hosts @override_settings(ALLOWED_HOSTS=[]) def test_allowed_hosts_empty(self): self.assertEqual(self.func(None), [base.W020]) @override_settings(ALLOWED_HOSTS=['.example.com']) def test_allowed_hosts_set(self): self.assertEqual(self.func(None), []) class CheckReferrerPolicyTest(SimpleTestCase): @property def func(self): from django.core.checks.security.base import check_referrer_policy return check_referrer_policy @override_settings( MIDDLEWARE=['django.middleware.security.SecurityMiddleware'], SECURE_REFERRER_POLICY=None, ) def test_no_referrer_policy(self): self.assertEqual(self.func(None), [base.W022]) @override_settings(MIDDLEWARE=[], SECURE_REFERRER_POLICY=None) def test_no_referrer_policy_no_middleware(self): """ Don't warn if SECURE_REFERRER_POLICY is None and SecurityMiddleware isn't in MIDDLEWARE. """ self.assertEqual(self.func(None), []) @override_settings(MIDDLEWARE=['django.middleware.security.SecurityMiddleware']) def test_with_referrer_policy(self): tests = ( 'strict-origin', 'strict-origin,origin', 'strict-origin, origin', ['strict-origin', 'origin'], ('strict-origin', 'origin'), ) for value in tests: with self.subTest(value=value), override_settings(SECURE_REFERRER_POLICY=value): self.assertEqual(self.func(None), []) @override_settings( MIDDLEWARE=['django.middleware.security.SecurityMiddleware'], SECURE_REFERRER_POLICY='invalid-value', ) def test_with_invalid_referrer_policy(self): self.assertEqual(self.func(None), [base.E023])
fdaa47aa4743f14652337c4582fa13b68d016b089dabf3edf94ee2b9d7deaa45
from functools import update_wrapper, wraps from unittest import TestCase from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.decorators import ( login_required, permission_required, user_passes_test, ) from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed from django.middleware.clickjacking import XFrameOptionsMiddleware from django.test import SimpleTestCase from django.utils.decorators import method_decorator from django.utils.functional import keep_lazy, keep_lazy_text, lazy from django.utils.safestring import mark_safe from django.views.decorators.cache import ( cache_control, cache_page, never_cache, ) from django.views.decorators.clickjacking import ( xframe_options_deny, xframe_options_exempt, xframe_options_sameorigin, ) from django.views.decorators.http import ( condition, require_GET, require_http_methods, require_POST, require_safe, ) from django.views.decorators.vary import vary_on_cookie, vary_on_headers def fully_decorated(request): """Expected __doc__""" return HttpResponse('<html><body>dummy</body></html>') fully_decorated.anything = "Expected __dict__" def compose(*functions): # compose(f, g)(*args, **kwargs) == f(g(*args, **kwargs)) functions = list(reversed(functions)) def _inner(*args, **kwargs): result = functions[0](*args, **kwargs) for f in functions[1:]: result = f(result) return result return _inner full_decorator = compose( # django.views.decorators.http require_http_methods(["GET"]), require_GET, require_POST, require_safe, condition(lambda r: None, lambda r: None), # django.views.decorators.vary vary_on_headers('Accept-language'), vary_on_cookie, # django.views.decorators.cache cache_page(60 * 15), cache_control(private=True), never_cache, # django.contrib.auth.decorators # Apply user_passes_test twice to check #9474 user_passes_test(lambda u: True), login_required, permission_required('change_world'), # django.contrib.admin.views.decorators staff_member_required, # django.utils.functional keep_lazy(HttpResponse), keep_lazy_text, lazy, # django.utils.safestring mark_safe, ) fully_decorated = full_decorator(fully_decorated) class DecoratorsTest(TestCase): def test_attributes(self): """ Built-in decorators set certain attributes of the wrapped function. """ self.assertEqual(fully_decorated.__name__, 'fully_decorated') self.assertEqual(fully_decorated.__doc__, 'Expected __doc__') self.assertEqual(fully_decorated.__dict__['anything'], 'Expected __dict__') def test_user_passes_test_composition(self): """ The user_passes_test decorator can be applied multiple times (#9474). """ def test1(user): user.decorators_applied.append('test1') return True def test2(user): user.decorators_applied.append('test2') return True def callback(request): return request.user.decorators_applied callback = user_passes_test(test1)(callback) callback = user_passes_test(test2)(callback) class DummyUser: pass class DummyRequest: pass request = DummyRequest() request.user = DummyUser() request.user.decorators_applied = [] response = callback(request) self.assertEqual(response, ['test2', 'test1']) def test_cache_page(self): def my_view(request): return "response" my_view_cached = cache_page(123)(my_view) self.assertEqual(my_view_cached(HttpRequest()), "response") my_view_cached2 = cache_page(123, key_prefix="test")(my_view) self.assertEqual(my_view_cached2(HttpRequest()), "response") def test_require_safe_accepts_only_safe_methods(self): """ Test for the require_safe decorator. A view returns either a response or an exception. Refs #15637. """ def my_view(request): return HttpResponse("OK") my_safe_view = require_safe(my_view) request = HttpRequest() request.method = 'GET' self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = 'HEAD' self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = 'POST' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = 'PUT' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = 'DELETE' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) # For testing method_decorator, a decorator that assumes a single argument. # We will get type arguments if there is a mismatch in the number of arguments. def simple_dec(func): def wrapper(arg): return func("test:" + arg) return wraps(func)(wrapper) simple_dec_m = method_decorator(simple_dec) # For testing method_decorator, two decorators that add an attribute to the function def myattr_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr = True return wrapper myattr_dec_m = method_decorator(myattr_dec) def myattr2_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr2 = True return wrapper myattr2_dec_m = method_decorator(myattr2_dec) class ClsDec: def __init__(self, myattr): self.myattr = myattr def __call__(self, f): def wrapped(): return f() and self.myattr return update_wrapper(wrapped, f) class MethodDecoratorTests(SimpleTestCase): """ Tests for method_decorator """ def test_preserve_signature(self): class Test: @simple_dec_m def say(self, arg): return arg self.assertEqual("test:hello", Test().say("hello")) def test_preserve_attributes(self): # Sanity check myattr_dec and myattr2_dec @myattr_dec def func(): pass self.assertIs(getattr(func, 'myattr', False), True) @myattr2_dec def func(): pass self.assertIs(getattr(func, 'myattr2', False), True) @myattr_dec @myattr2_dec def func(): pass self.assertIs(getattr(func, 'myattr', False), True) self.assertIs(getattr(func, 'myattr2', False), False) # Decorate using method_decorator() on the method. class TestPlain: @myattr_dec_m @myattr2_dec_m def method(self): "A method" pass # Decorate using method_decorator() on both the class and the method. # The decorators applied to the methods are applied before the ones # applied to the class. @method_decorator(myattr_dec_m, "method") class TestMethodAndClass: @method_decorator(myattr2_dec_m) def method(self): "A method" pass # Decorate using an iterable of function decorators. @method_decorator((myattr_dec, myattr2_dec), 'method') class TestFunctionIterable: def method(self): "A method" pass # Decorate using an iterable of method decorators. decorators = (myattr_dec_m, myattr2_dec_m) @method_decorator(decorators, "method") class TestMethodIterable: def method(self): "A method" pass tests = (TestPlain, TestMethodAndClass, TestFunctionIterable, TestMethodIterable) for Test in tests: with self.subTest(Test=Test): self.assertIs(getattr(Test().method, 'myattr', False), True) self.assertIs(getattr(Test().method, 'myattr2', False), True) self.assertIs(getattr(Test.method, 'myattr', False), True) self.assertIs(getattr(Test.method, 'myattr2', False), True) self.assertEqual(Test.method.__doc__, 'A method') self.assertEqual(Test.method.__name__, 'method') def test_new_attribute(self): """A decorator that sets a new attribute on the method.""" def decorate(func): func.x = 1 return func class MyClass: @method_decorator(decorate) def method(self): return True obj = MyClass() self.assertEqual(obj.method.x, 1) self.assertIs(obj.method(), True) def test_bad_iterable(self): decorators = {myattr_dec_m, myattr2_dec_m} msg = "'set' object is not subscriptable" with self.assertRaisesMessage(TypeError, msg): @method_decorator(decorators, "method") class TestIterable: def method(self): "A method" pass # Test for argumented decorator def test_argumented(self): class Test: @method_decorator(ClsDec(False)) def method(self): return True self.assertIs(Test().method(), False) def test_descriptors(self): def original_dec(wrapped): def _wrapped(arg): return wrapped(arg) return _wrapped method_dec = method_decorator(original_dec) class bound_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __call__(self, arg): return self.wrapped(arg) def __get__(self, instance, cls=None): return self class descriptor_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __get__(self, instance, cls=None): return bound_wrapper(self.wrapped.__get__(instance, cls)) class Test: @method_dec @descriptor_wrapper def method(self, arg): return arg self.assertEqual(Test().method(1), 1) def test_class_decoration(self): """ @method_decorator can be used to decorate a class and its methods. """ def deco(func): def _wrapper(*args, **kwargs): return True return _wrapper @method_decorator(deco, name="method") class Test: def method(self): return False self.assertTrue(Test().method()) def test_tuple_of_decorators(self): """ @method_decorator can accept a tuple of decorators. """ def add_question_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "?" return _wrapper def add_exclamation_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "!" return _wrapper # The order should be consistent with the usual order in which # decorators are applied, e.g. # @add_exclamation_mark # @add_question_mark # def func(): # ... decorators = (add_exclamation_mark, add_question_mark) @method_decorator(decorators, name="method") class TestFirst: def method(self): return "hello world" class TestSecond: @method_decorator(decorators) def method(self): return "hello world" self.assertEqual(TestFirst().method(), "hello world?!") self.assertEqual(TestSecond().method(), "hello world?!") def test_invalid_non_callable_attribute_decoration(self): """ @method_decorator on a non-callable attribute raises an error. """ msg = ( "Cannot decorate 'prop' as it isn't a callable attribute of " "<class 'Test'> (1)" ) with self.assertRaisesMessage(TypeError, msg): @method_decorator(lambda: None, name="prop") class Test: prop = 1 @classmethod def __module__(cls): return "tests" def test_invalid_method_name_to_decorate(self): """ @method_decorator on a nonexistent method raises an error. """ msg = ( "The keyword argument `name` must be the name of a method of the " "decorated class: <class 'Test'>. Got 'nonexistent_method' instead" ) with self.assertRaisesMessage(ValueError, msg): @method_decorator(lambda: None, name='nonexistent_method') class Test: @classmethod def __module__(cls): return "tests" class XFrameOptionsDecoratorsTests(TestCase): """ Tests for the X-Frame-Options decorators. """ def test_deny_decorator(self): """ Ensures @xframe_options_deny properly sets the X-Frame-Options header. """ @xframe_options_deny def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r['X-Frame-Options'], 'DENY') def test_sameorigin_decorator(self): """ Ensures @xframe_options_sameorigin properly sets the X-Frame-Options header. """ @xframe_options_sameorigin def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN') def test_exempt_decorator(self): """ Ensures @xframe_options_exempt properly instructs the XFrameOptionsMiddleware to NOT set the header. """ @xframe_options_exempt def a_view(request): return HttpResponse() req = HttpRequest() resp = a_view(req) self.assertIsNone(resp.get('X-Frame-Options', None)) self.assertTrue(resp.xframe_options_exempt) # Since the real purpose of the exempt decorator is to suppress # the middleware's functionality, let's make sure it actually works... r = XFrameOptionsMiddleware().process_response(req, resp) self.assertIsNone(r.get('X-Frame-Options', None)) class NeverCacheDecoratorTest(TestCase): def test_never_cache_decorator(self): @never_cache def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual( set(r['Cache-Control'].split(', ')), {'max-age=0', 'no-cache', 'no-store', 'must-revalidate', 'private'}, )
c5da17f2fba4251f5ae18b549dcab11973a0633661778455d2702913de3d6bd4
import os import shutil import tempfile from django import conf from django.test import SimpleTestCase from django.test.utils import extend_sys_path class TestStartProjectSettings(SimpleTestCase): def setUp(self): self.temp_dir = tempfile.TemporaryDirectory() self.addCleanup(self.temp_dir.cleanup) template_settings_py = os.path.join( os.path.dirname(conf.__file__), 'project_template', 'project_name', 'settings.py-tpl', ) test_settings_py = os.path.join(self.temp_dir.name, 'test_settings.py') shutil.copyfile(template_settings_py, test_settings_py) def test_middleware_headers(self): """ Ensure headers sent by the default MIDDLEWARE don't inadvertently change. For example, we never want "Vary: Cookie" to appear in the list since it prevents the caching of responses. """ with extend_sys_path(self.temp_dir.name): from test_settings import MIDDLEWARE with self.settings( MIDDLEWARE=MIDDLEWARE, ROOT_URLCONF='project_template.urls', ): response = self.client.get('/empty/') headers = sorted(response.serialize_headers().split(b'\r\n')) self.assertEqual(headers, [ b'Content-Length: 0', b'Content-Type: text/html; charset=utf-8', b'X-Content-Type-Options: nosniff', b'X-Frame-Options: DENY', ])
f68c9d8c559b3bf757d07faf1d0963f74a0b651905c6eea1fe040908301baefd
""" A series of tests to establish that the command-line management tools work as advertised - especially with regards to the handling of the DJANGO_SETTINGS_MODULE and default settings.py files. """ import os import re import shutil import socket import subprocess import sys import tempfile import unittest from io import StringIO from unittest import mock import django from django import conf, get_version from django.conf import settings from django.core.management import ( BaseCommand, CommandError, call_command, color, ) from django.core.management.commands.loaddata import Command as LoaddataCommand from django.core.management.commands.runserver import ( Command as RunserverCommand, ) from django.core.management.commands.testserver import ( Command as TestserverCommand, ) from django.db import ConnectionHandler, connection from django.db.migrations.recorder import MigrationRecorder from django.test import ( LiveServerTestCase, SimpleTestCase, TestCase, override_settings, ) custom_templates_dir = os.path.join(os.path.dirname(__file__), 'custom_templates') SYSTEM_CHECK_MSG = 'System check identified no issues' class AdminScriptTestCase(SimpleTestCase): def setUp(self): tmpdir = tempfile.TemporaryDirectory() self.addCleanup(tmpdir.cleanup) # os.path.realpath() is required for temporary directories on macOS, # where `/var` is a symlink to `/private/var`. self.test_dir = os.path.realpath(os.path.join(tmpdir.name, 'test_project')) os.mkdir(self.test_dir) with open(os.path.join(self.test_dir, '__init__.py'), 'w'): pass def write_settings(self, filename, apps=None, is_dir=False, sdict=None, extra=None): if is_dir: settings_dir = os.path.join(self.test_dir, filename) os.mkdir(settings_dir) settings_file_path = os.path.join(settings_dir, '__init__.py') else: settings_file_path = os.path.join(self.test_dir, filename) with open(settings_file_path, 'w') as settings_file: settings_file.write('# Settings file automatically generated by admin_scripts test case\n') if extra: settings_file.write("%s\n" % extra) exports = [ 'DATABASES', 'ROOT_URLCONF', 'SECRET_KEY', ] for s in exports: if hasattr(settings, s): o = getattr(settings, s) if not isinstance(o, (dict, tuple, list)): o = "'%s'" % o settings_file.write("%s = %s\n" % (s, o)) if apps is None: apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'admin_scripts'] settings_file.write("INSTALLED_APPS = %s\n" % apps) if sdict: for k, v in sdict.items(): settings_file.write("%s = %s\n" % (k, v)) def _ext_backend_paths(self): """ Returns the paths for any external backend packages. """ paths = [] for backend in settings.DATABASES.values(): package = backend['ENGINE'].split('.')[0] if package != 'django': backend_pkg = __import__(package) backend_dir = os.path.dirname(backend_pkg.__file__) paths.append(os.path.dirname(backend_dir)) return paths def run_test(self, script, args, settings_file=None, apps=None): base_dir = os.path.dirname(self.test_dir) # The base dir for Django's tests is one level up. tests_dir = os.path.dirname(os.path.dirname(__file__)) # The base dir for Django is one level above the test dir. We don't use # `import django` to figure that out, so we don't pick up a Django # from site-packages or similar. django_dir = os.path.dirname(tests_dir) ext_backend_base_dirs = self._ext_backend_paths() # Define a temporary environment for the subprocess test_environ = os.environ.copy() # Set the test environment if settings_file: test_environ['DJANGO_SETTINGS_MODULE'] = settings_file elif 'DJANGO_SETTINGS_MODULE' in test_environ: del test_environ['DJANGO_SETTINGS_MODULE'] python_path = [base_dir, django_dir, tests_dir] python_path.extend(ext_backend_base_dirs) test_environ['PYTHONPATH'] = os.pathsep.join(python_path) test_environ['PYTHONWARNINGS'] = '' p = subprocess.run( [sys.executable, script] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.test_dir, env=test_environ, universal_newlines=True, ) return p.stdout, p.stderr def run_django_admin(self, args, settings_file=None): script_dir = os.path.abspath(os.path.join(os.path.dirname(django.__file__), 'bin')) return self.run_test(os.path.join(script_dir, 'django-admin.py'), args, settings_file) def run_manage(self, args, settings_file=None, manage_py=None): template_manage_py = ( os.path.join(os.path.dirname(__file__), manage_py) if manage_py else os.path.join(os.path.dirname(conf.__file__), 'project_template', 'manage.py-tpl') ) test_manage_py = os.path.join(self.test_dir, 'manage.py') shutil.copyfile(template_manage_py, test_manage_py) with open(test_manage_py) as fp: manage_py_contents = fp.read() manage_py_contents = manage_py_contents.replace( "{{ project_name }}", "test_project") with open(test_manage_py, 'w') as fp: fp.write(manage_py_contents) return self.run_test('./manage.py', args, settings_file) def assertNoOutput(self, stream): "Utility assertion: assert that the given stream is empty" self.assertEqual(len(stream), 0, "Stream should be empty: actually contains '%s'" % stream) def assertOutput(self, stream, msg, regex=False): "Utility assertion: assert that the given message exists in the output" if regex: self.assertIsNotNone( re.search(msg, stream), "'%s' does not match actual output text '%s'" % (msg, stream) ) else: self.assertIn(msg, stream, "'%s' does not match actual output text '%s'" % (msg, stream)) def assertNotInOutput(self, stream, msg): "Utility assertion: assert that the given message doesn't exist in the output" self.assertNotIn(msg, stream, "'%s' matches actual output text '%s'" % (msg, stream)) ########################################################################## # DJANGO ADMIN TESTS # This first series of test classes checks the environment processing # of the django-admin.py script ########################################################################## class DjangoAdminNoSettings(AdminScriptTestCase): "A series of tests for django-admin.py when there is no settings.py file." def test_builtin_command(self): "no settings: django-admin builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'settings are not configured') def test_builtin_with_bad_settings(self): "no settings: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "no settings: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_commands_with_invalid_settings(self): """" Commands that don't require settings succeed if the settings file doesn't exist. """ args = ['startproject'] out, err = self.run_django_admin(args, settings_file='bad_settings') self.assertNoOutput(out) self.assertOutput(err, "You must provide a project name", regex=True) class DjangoAdminDefaultSettings(AdminScriptTestCase): """A series of tests for django-admin.py when using a settings.py file that contains the test application. """ def setUp(self): super().setUp() self.write_settings('settings.py') def test_builtin_command(self): "default: django-admin builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'settings are not configured') def test_builtin_with_settings(self): "default: django-admin builtin commands succeed if settings are provided as argument" args = ['check', '--settings=test_project.settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "default: django-admin builtin commands succeed if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "default: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "default: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "default: django-admin can't execute user commands if it isn't provided settings" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "default: django-admin can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=test_project.settings'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "default: django-admin can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase): """A series of tests for django-admin.py when using a settings.py file that contains the test application specified using a full path. """ def setUp(self): super().setUp() self.write_settings('settings.py', ['django.contrib.auth', 'django.contrib.contenttypes', 'admin_scripts', 'admin_scripts.complex_app']) def test_builtin_command(self): "fulldefault: django-admin builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'settings are not configured') def test_builtin_with_settings(self): "fulldefault: django-admin builtin commands succeed if a settings file is provided" args = ['check', '--settings=test_project.settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "fulldefault: django-admin builtin commands succeed if the environment contains settings" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "fulldefault: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "fulldefault: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "fulldefault: django-admin can't execute user commands unless settings are provided" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "fulldefault: django-admin can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=test_project.settings'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "fulldefault: django-admin can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminMinimalSettings(AdminScriptTestCase): """A series of tests for django-admin.py when using a settings.py file that doesn't contain the test application. """ def setUp(self): super().setUp() self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes']) def test_builtin_command(self): "minimal: django-admin builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'settings are not configured') def test_builtin_with_settings(self): "minimal: django-admin builtin commands fail if settings are provided as argument" args = ['check', '--settings=test_project.settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_environment(self): "minimal: django-admin builtin commands fail if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_bad_settings(self): "minimal: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "minimal: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "minimal: django-admin can't execute user commands unless settings are provided" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "minimal: django-admin can't execute user commands, even if settings are provided as argument" args = ['noargs_command', '--settings=test_project.settings'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_environment(self): "minimal: django-admin can't execute user commands, even if settings are provided in environment" args = ['noargs_command'] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") class DjangoAdminAlternateSettings(AdminScriptTestCase): """A series of tests for django-admin.py when using a settings file with a name other than 'settings.py'. """ def setUp(self): super().setUp() self.write_settings('alternate_settings.py') def test_builtin_command(self): "alternate: django-admin builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'settings are not configured') def test_builtin_with_settings(self): "alternate: django-admin builtin commands succeed if settings are provided as argument" args = ['check', '--settings=test_project.alternate_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "alternate: django-admin builtin commands succeed if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'test_project.alternate_settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "alternate: django-admin can't execute user commands unless settings are provided" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "alternate: django-admin can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=test_project.alternate_settings'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "alternate: django-admin can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_django_admin(args, 'test_project.alternate_settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminMultipleSettings(AdminScriptTestCase): """A series of tests for django-admin.py when multiple settings files (including the default 'settings.py') are available. The default settings file is insufficient for performing the operations described, so the alternate settings must be used by the running script. """ def setUp(self): super().setUp() self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes']) self.write_settings('alternate_settings.py') def test_builtin_command(self): "alternate: django-admin builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'settings are not configured') def test_builtin_with_settings(self): "alternate: django-admin builtin commands succeed if settings are provided as argument" args = ['check', '--settings=test_project.alternate_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "alternate: django-admin builtin commands succeed if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'test_project.alternate_settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "alternate: django-admin can't execute user commands unless settings are provided" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "alternate: django-admin can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=test_project.alternate_settings'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "alternate: django-admin can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_django_admin(args, 'test_project.alternate_settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminSettingsDirectory(AdminScriptTestCase): """ A series of tests for django-admin.py when the settings file is in a directory. (see #9751). """ def setUp(self): super().setUp() self.write_settings('settings', is_dir=True) def test_setup_environ(self): "directory: startapp creates the correct directory" args = ['startapp', 'settings_test'] app_path = os.path.join(self.test_dir, 'settings_test') out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) with open(os.path.join(app_path, 'apps.py')) as f: content = f.read() self.assertIn("class SettingsTestConfig(AppConfig)", content) self.assertIn("name = 'settings_test'", content) def test_setup_environ_custom_template(self): "directory: startapp creates the correct directory with a custom template" template_path = os.path.join(custom_templates_dir, 'app_template') args = ['startapp', '--template', template_path, 'custom_settings_test'] app_path = os.path.join(self.test_dir, 'custom_settings_test') out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) self.assertTrue(os.path.exists(os.path.join(app_path, 'api.py'))) def test_startapp_unicode_name(self): "directory: startapp creates the correct directory with unicode characters" args = ['startapp', 'こんにちは'] app_path = os.path.join(self.test_dir, 'こんにちは') out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) with open(os.path.join(app_path, 'apps.py'), encoding='utf8') as f: content = f.read() self.assertIn("class こんにちはConfig(AppConfig)", content) self.assertIn("name = 'こんにちは'", content) def test_builtin_command(self): "directory: django-admin builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'settings are not configured') def test_builtin_with_bad_settings(self): "directory: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "directory: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "directory: django-admin can't execute user commands unless settings are provided" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_builtin_with_settings(self): "directory: django-admin builtin commands succeed if settings are provided as argument" args = ['check', '--settings=test_project.settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "directory: django-admin builtin commands succeed if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) ########################################################################## # MANAGE.PY TESTS # This next series of test classes checks the environment processing # of the generated manage.py script ########################################################################## class ManageNoSettings(AdminScriptTestCase): "A series of tests for manage.py when there is no settings.py file." def test_builtin_command(self): "no settings: manage.py builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, r"No module named '?(test_project\.)?settings'?", regex=True) def test_builtin_with_bad_settings(self): "no settings: manage.py builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "no settings: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) class ManageDefaultSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that contains the test application. """ def setUp(self): super().setUp() self.write_settings('settings.py') def test_builtin_command(self): "default: manage.py builtin commands succeed when default settings are appropriate" args = ['check', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_settings(self): "default: manage.py builtin commands succeed if settings are provided as argument" args = ['check', '--settings=test_project.settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "default: manage.py builtin commands succeed if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "default: manage.py builtin commands succeed if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "default: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "default: manage.py can execute user commands when default settings are appropriate" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_settings(self): "default: manage.py can execute user commands when settings are provided as argument" args = ['noargs_command', '--settings=test_project.settings'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "default: manage.py can execute user commands when settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class ManageFullPathDefaultSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that contains the test application specified using a full path. """ def setUp(self): super().setUp() self.write_settings('settings.py', ['django.contrib.auth', 'django.contrib.contenttypes', 'admin_scripts']) def test_builtin_command(self): "fulldefault: manage.py builtin commands succeed when default settings are appropriate" args = ['check', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_settings(self): "fulldefault: manage.py builtin commands succeed if settings are provided as argument" args = ['check', '--settings=test_project.settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "fulldefault: manage.py builtin commands succeed if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "fulldefault: manage.py builtin commands succeed if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "fulldefault: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "fulldefault: manage.py can execute user commands when default settings are appropriate" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_settings(self): "fulldefault: manage.py can execute user commands when settings are provided as argument" args = ['noargs_command', '--settings=test_project.settings'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "fulldefault: manage.py can execute user commands when settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class ManageMinimalSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that doesn't contain the test application. """ def setUp(self): super().setUp() self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes']) def test_builtin_command(self): "minimal: manage.py builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_settings(self): "minimal: manage.py builtin commands fail if settings are provided as argument" args = ['check', '--settings=test_project.settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_environment(self): "minimal: manage.py builtin commands fail if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'test_project.settings') self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_bad_settings(self): "minimal: manage.py builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "minimal: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "minimal: manage.py can't execute user commands without appropriate settings" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "minimal: manage.py can't execute user commands, even if settings are provided as argument" args = ['noargs_command', '--settings=test_project.settings'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_environment(self): "minimal: manage.py can't execute user commands, even if settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args, 'test_project.settings') self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") class ManageAlternateSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings file with a name other than 'settings.py'. """ def setUp(self): super().setUp() self.write_settings('alternate_settings.py') def test_builtin_command(self): "alternate: manage.py builtin commands fail with an error when no default settings provided" args = ['check', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, r"No module named '?(test_project\.)?settings'?", regex=True) def test_builtin_with_settings(self): "alternate: manage.py builtin commands work with settings provided as argument" args = ['check', '--settings=alternate_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertOutput(out, SYSTEM_CHECK_MSG) self.assertNoOutput(err) def test_builtin_with_environment(self): "alternate: manage.py builtin commands work if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'alternate_settings') self.assertOutput(out, SYSTEM_CHECK_MSG) self.assertNoOutput(err) def test_builtin_with_bad_settings(self): "alternate: manage.py builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "alternate: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "alternate: manage.py can't execute user commands without settings" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, r"No module named '?(test_project\.)?settings'?", regex=True) def test_custom_command_with_settings(self): "alternate: manage.py can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=alternate_settings'] out, err = self.run_manage(args) self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', False), ('pythonpath', None), ('settings', " "'alternate_settings'), ('traceback', False), ('verbosity', 1)]" ) self.assertNoOutput(err) def test_custom_command_with_environment(self): "alternate: manage.py can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args, 'alternate_settings') self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', False), ('pythonpath', None), ('settings', None), " "('traceback', False), ('verbosity', 1)]" ) self.assertNoOutput(err) def test_custom_command_output_color(self): "alternate: manage.py output syntax color can be deactivated with the `--no-color` option" args = ['noargs_command', '--no-color', '--settings=alternate_settings'] out, err = self.run_manage(args) self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', True), ('pythonpath', None), ('settings', " "'alternate_settings'), ('traceback', False), ('verbosity', 1)]" ) self.assertNoOutput(err) class ManageMultipleSettings(AdminScriptTestCase): """A series of tests for manage.py when multiple settings files (including the default 'settings.py') are available. The default settings file is insufficient for performing the operations described, so the alternate settings must be used by the running script. """ def setUp(self): super().setUp() self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes']) self.write_settings('alternate_settings.py') def test_builtin_command(self): "multiple: manage.py builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_settings(self): "multiple: manage.py builtin commands succeed if settings are provided as argument" args = ['check', '--settings=alternate_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "multiple: manage.py can execute builtin commands if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'alternate_settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "multiple: manage.py builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "multiple: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "multiple: manage.py can't execute user commands using default settings" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "multiple: manage.py can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=alternate_settings'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "multiple: manage.py can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args, 'alternate_settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class ManageSettingsWithSettingsErrors(AdminScriptTestCase): """ Tests for manage.py when using the default settings.py file containing runtime errors. """ def write_settings_with_import_error(self, filename): settings_file_path = os.path.join(self.test_dir, filename) with open(settings_file_path, 'w') as settings_file: settings_file.write('# Settings file automatically generated by admin_scripts test case\n') settings_file.write('# The next line will cause an import error:\nimport foo42bar\n') def test_import_error(self): """ import error: manage.py builtin commands shows useful diagnostic info when settings with import errors is provided (#14130). """ self.write_settings_with_import_error('settings.py') args = ['check', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named") self.assertOutput(err, "foo42bar") def test_attribute_error(self): """ manage.py builtin commands does not swallow attribute error due to bad settings (#18845). """ self.write_settings('settings.py', sdict={'BAD_VAR': 'INSTALLED_APPS.crash'}) args = ['collectstatic', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "AttributeError: 'list' object has no attribute 'crash'") def test_key_error(self): self.write_settings('settings.py', sdict={'BAD_VAR': 'DATABASES["blah"]'}) args = ['collectstatic', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "KeyError: 'blah'") def test_help(self): """ Test listing available commands output note when only core commands are available. """ self.write_settings( 'settings.py', extra='from django.core.exceptions import ImproperlyConfigured\n' 'raise ImproperlyConfigured()', ) args = ['help'] out, err = self.run_manage(args) self.assertOutput(out, 'only Django core commands are listed') self.assertNoOutput(err) class ManageCheck(AdminScriptTestCase): def test_nonexistent_app(self): """check reports an error on a nonexistent app in INSTALLED_APPS.""" self.write_settings( 'settings.py', apps=['admin_scriptz.broken_app'], sdict={'USE_I18N': False}, ) args = ['check'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, 'ModuleNotFoundError') self.assertOutput(err, 'No module named') self.assertOutput(err, 'admin_scriptz') def test_broken_app(self): """ manage.py check reports an ImportError if an app's models.py raises one on import """ self.write_settings('settings.py', apps=['admin_scripts.broken_app']) args = ['check'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, 'ImportError') def test_complex_app(self): """ manage.py check does not raise an ImportError validating a complex app with nested calls to load_app """ self.write_settings( 'settings.py', apps=[ 'admin_scripts.complex_app', 'admin_scripts.simple_app', 'django.contrib.admin.apps.SimpleAdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', ], sdict={ 'DEBUG': True, 'MIDDLEWARE': [ 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ], 'TEMPLATES': [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ], } ) args = ['check'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertEqual(out, 'System check identified no issues (0 silenced).\n') def test_app_with_import(self): """ manage.py check does not raise errors when an app imports a base class that itself has an abstract base. """ self.write_settings( 'settings.py', apps=[ 'admin_scripts.app_with_import', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', ], sdict={'DEBUG': True}, ) args = ['check'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertEqual(out, 'System check identified no issues (0 silenced).\n') def test_output_format(self): """ All errors/warnings should be sorted by level and by message. """ self.write_settings( 'settings.py', apps=[ 'admin_scripts.app_raising_messages', 'django.contrib.auth', 'django.contrib.contenttypes', ], sdict={'DEBUG': True}, ) args = ['check'] out, err = self.run_manage(args) expected_err = ( "SystemCheckError: System check identified some issues:\n" "\n" "ERRORS:\n" "?: An error\n" "\tHINT: Error hint\n" "\n" "WARNINGS:\n" "a: Second warning\n" "obj: First warning\n" "\tHINT: Hint\n" "\n" "System check identified 3 issues (0 silenced).\n" ) self.assertEqual(err, expected_err) self.assertNoOutput(out) def test_warning_does_not_halt(self): """ When there are only warnings or less serious messages, then Django should not prevent user from launching their project, so `check` command should not raise `CommandError` exception. In this test we also test output format. """ self.write_settings( 'settings.py', apps=[ 'admin_scripts.app_raising_warning', 'django.contrib.auth', 'django.contrib.contenttypes', ], sdict={'DEBUG': True}, ) args = ['check'] out, err = self.run_manage(args) expected_err = ( "System check identified some issues:\n" # No "CommandError: " part "\n" "WARNINGS:\n" "?: A warning\n" "\n" "System check identified 1 issue (0 silenced).\n" ) self.assertEqual(err, expected_err) self.assertNoOutput(out) class ManageRunserver(SimpleTestCase): def setUp(self): def monkey_run(*args, **options): return self.output = StringIO() self.cmd = RunserverCommand(stdout=self.output) self.cmd.run = monkey_run def assertServerSettings(self, addr, port, ipv6=False, raw_ipv6=False): self.assertEqual(self.cmd.addr, addr) self.assertEqual(self.cmd.port, port) self.assertEqual(self.cmd.use_ipv6, ipv6) self.assertEqual(self.cmd._raw_ipv6, raw_ipv6) def test_runserver_addrport(self): call_command(self.cmd) self.assertServerSettings('127.0.0.1', '8000') call_command(self.cmd, addrport="1.2.3.4:8000") self.assertServerSettings('1.2.3.4', '8000') call_command(self.cmd, addrport="7000") self.assertServerSettings('127.0.0.1', '7000') @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6") def test_runner_addrport_ipv6(self): call_command(self.cmd, addrport="", use_ipv6=True) self.assertServerSettings('::1', '8000', ipv6=True, raw_ipv6=True) call_command(self.cmd, addrport="7000", use_ipv6=True) self.assertServerSettings('::1', '7000', ipv6=True, raw_ipv6=True) call_command(self.cmd, addrport="[2001:0db8:1234:5678::9]:7000") self.assertServerSettings('2001:0db8:1234:5678::9', '7000', ipv6=True, raw_ipv6=True) def test_runner_hostname(self): call_command(self.cmd, addrport="localhost:8000") self.assertServerSettings('localhost', '8000') call_command(self.cmd, addrport="test.domain.local:7000") self.assertServerSettings('test.domain.local', '7000') @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6") def test_runner_hostname_ipv6(self): call_command(self.cmd, addrport="test.domain.local:7000", use_ipv6=True) self.assertServerSettings('test.domain.local', '7000', ipv6=True) def test_runner_custom_defaults(self): self.cmd.default_addr = '0.0.0.0' self.cmd.default_port = '5000' call_command(self.cmd) self.assertServerSettings('0.0.0.0', '5000') @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6") def test_runner_custom_defaults_ipv6(self): self.cmd.default_addr_ipv6 = '::' call_command(self.cmd, use_ipv6=True) self.assertServerSettings('::', '8000', ipv6=True, raw_ipv6=True) def test_runner_ambiguous(self): # Only 4 characters, all of which could be in an ipv6 address call_command(self.cmd, addrport="beef:7654") self.assertServerSettings('beef', '7654') # Uses only characters that could be in an ipv6 address call_command(self.cmd, addrport="deadbeef:7654") self.assertServerSettings('deadbeef', '7654') def test_no_database(self): """ Ensure runserver.check_migrations doesn't choke on empty DATABASES. """ tested_connections = ConnectionHandler({}) with mock.patch('django.core.management.base.connections', new=tested_connections): self.cmd.check_migrations() def test_readonly_database(self): """ runserver.check_migrations() doesn't choke when a database is read-only. """ with mock.patch.object(MigrationRecorder, 'has_table', return_value=False): self.cmd.check_migrations() # You have # ... self.assertIn('unapplied migration(s)', self.output.getvalue()) class ManageRunserverMigrationWarning(TestCase): def setUp(self): self.stdout = StringIO() self.runserver_command = RunserverCommand(stdout=self.stdout) @override_settings(INSTALLED_APPS=["admin_scripts.app_waiting_migration"]) def test_migration_warning_one_app(self): self.runserver_command.check_migrations() output = self.stdout.getvalue() self.assertIn('You have 1 unapplied migration(s)', output) self.assertIn('apply the migrations for app(s): app_waiting_migration.', output) @override_settings( INSTALLED_APPS=[ "admin_scripts.app_waiting_migration", "admin_scripts.another_app_waiting_migration", ], ) def test_migration_warning_multiple_apps(self): self.runserver_command.check_migrations() output = self.stdout.getvalue() self.assertIn('You have 2 unapplied migration(s)', output) self.assertIn( 'apply the migrations for app(s): another_app_waiting_migration, ' 'app_waiting_migration.', output ) class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase): def setUp(self): super().setUp() self.write_settings('settings.py', sdict={ 'ALLOWED_HOSTS': [], 'DEBUG': False, }) def test_empty_allowed_hosts_error(self): out, err = self.run_manage(['runserver']) self.assertNoOutput(out) self.assertOutput(err, 'CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.') class ManageTestserver(SimpleTestCase): @mock.patch.object(TestserverCommand, 'handle', return_value='') def test_testserver_handle_params(self, mock_handle): out = StringIO() call_command('testserver', 'blah.json', stdout=out) mock_handle.assert_called_with( 'blah.json', stdout=out, settings=None, pythonpath=None, verbosity=1, traceback=False, addrport='', no_color=False, use_ipv6=False, skip_checks=True, interactive=True, force_color=False, ) @mock.patch('django.db.connection.creation.create_test_db', return_value='test_db') @mock.patch.object(LoaddataCommand, 'handle', return_value='') @mock.patch.object(RunserverCommand, 'handle', return_value='') def test_params_to_runserver(self, mock_runserver_handle, mock_loaddata_handle, mock_create_test_db): out = StringIO() call_command('testserver', 'blah.json', stdout=out) mock_runserver_handle.assert_called_with( addrport='', force_color=False, insecure_serving=False, no_color=False, pythonpath=None, settings=None, shutdown_message=( "\nServer stopped.\nNote that the test database, 'test_db', " "has not been deleted. You can explore it on your own." ), skip_checks=True, traceback=False, use_ipv6=False, use_reloader=False, use_static_handler=True, use_threading=connection.features.test_db_allows_multiple_connections, verbosity=1, ) ########################################################################## # COMMAND PROCESSING TESTS # user-space commands are correctly handled - in particular, arguments to # the commands are correctly parsed and processed. ########################################################################## class ColorCommand(BaseCommand): requires_system_checks = False def handle(self, *args, **options): self.stdout.write('Hello, world!', self.style.ERROR) self.stderr.write('Hello, world!', self.style.ERROR) class CommandTypes(AdminScriptTestCase): "Tests for the various types of base command types that can be defined." def setUp(self): super().setUp() self.write_settings('settings.py') def test_version(self): "version is handled as a special case" args = ['version'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, get_version()) def test_version_alternative(self): "--version is equivalent to version" args1, args2 = ['version'], ['--version'] # It's possible one outputs on stderr and the other on stdout, hence the set self.assertEqual(set(self.run_manage(args1)), set(self.run_manage(args2))) def test_help(self): "help is handled as a special case" args = ['help'] out, err = self.run_manage(args) self.assertOutput(out, "Type 'manage.py help <subcommand>' for help on a specific subcommand.") self.assertOutput(out, '[django]') self.assertOutput(out, 'startapp') self.assertOutput(out, 'startproject') def test_help_commands(self): "help --commands shows the list of all available commands" args = ['help', '--commands'] out, err = self.run_manage(args) self.assertNotInOutput(out, 'usage:') self.assertNotInOutput(out, 'Options:') self.assertNotInOutput(out, '[django]') self.assertOutput(out, 'startapp') self.assertOutput(out, 'startproject') self.assertNotInOutput(out, '\n\n') def test_help_alternative(self): "--help is equivalent to help" args1, args2 = ['help'], ['--help'] self.assertEqual(self.run_manage(args1), self.run_manage(args2)) def test_help_short_altert(self): "-h is handled as a short form of --help" args1, args2 = ['--help'], ['-h'] self.assertEqual(self.run_manage(args1), self.run_manage(args2)) def test_specific_help(self): "--help can be used on a specific command" args = ['check', '--help'] out, err = self.run_manage(args) self.assertNoOutput(err) # Command-specific options like --tag appear before options common to # all commands like --version. tag_location = out.find('--tag') version_location = out.find('--version') self.assertNotEqual(tag_location, -1) self.assertNotEqual(version_location, -1) self.assertLess(tag_location, version_location) self.assertOutput(out, "Checks the entire Django project for potential problems.") def test_color_style(self): style = color.no_style() self.assertEqual(style.ERROR('Hello, world!'), 'Hello, world!') style = color.make_style('nocolor') self.assertEqual(style.ERROR('Hello, world!'), 'Hello, world!') style = color.make_style('dark') self.assertIn('Hello, world!', style.ERROR('Hello, world!')) self.assertNotEqual(style.ERROR('Hello, world!'), 'Hello, world!') # Default palette has color. style = color.make_style('') self.assertIn('Hello, world!', style.ERROR('Hello, world!')) self.assertNotEqual(style.ERROR('Hello, world!'), 'Hello, world!') def test_command_color(self): out = StringIO() err = StringIO() command = ColorCommand(stdout=out, stderr=err) call_command(command) if color.supports_color(): self.assertIn('Hello, world!\n', out.getvalue()) self.assertIn('Hello, world!\n', err.getvalue()) self.assertNotEqual(out.getvalue(), 'Hello, world!\n') self.assertNotEqual(err.getvalue(), 'Hello, world!\n') else: self.assertEqual(out.getvalue(), 'Hello, world!\n') self.assertEqual(err.getvalue(), 'Hello, world!\n') def test_command_no_color(self): "--no-color prevent colorization of the output" out = StringIO() err = StringIO() command = ColorCommand(stdout=out, stderr=err, no_color=True) call_command(command) self.assertEqual(out.getvalue(), 'Hello, world!\n') self.assertEqual(err.getvalue(), 'Hello, world!\n') out = StringIO() err = StringIO() command = ColorCommand(stdout=out, stderr=err) call_command(command, no_color=True) self.assertEqual(out.getvalue(), 'Hello, world!\n') self.assertEqual(err.getvalue(), 'Hello, world!\n') def test_force_color_execute(self): out = StringIO() err = StringIO() with mock.patch.object(sys.stdout, 'isatty', lambda: False): command = ColorCommand(stdout=out, stderr=err) call_command(command, force_color=True) self.assertEqual(out.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m') self.assertEqual(err.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m') def test_force_color_command_init(self): out = StringIO() err = StringIO() with mock.patch.object(sys.stdout, 'isatty', lambda: False): command = ColorCommand(stdout=out, stderr=err, force_color=True) call_command(command) self.assertEqual(out.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m') self.assertEqual(err.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m') def test_no_color_force_color_mutually_exclusive_execute(self): msg = "The --no-color and --force-color options can't be used together." with self.assertRaisesMessage(CommandError, msg): call_command(BaseCommand(), no_color=True, force_color=True) def test_no_color_force_color_mutually_exclusive_command_init(self): msg = "'no_color' and 'force_color' can't be used together." with self.assertRaisesMessage(CommandError, msg): call_command(BaseCommand(no_color=True, force_color=True)) def test_custom_stdout(self): class Command(BaseCommand): requires_system_checks = False def handle(self, *args, **options): self.stdout.write("Hello, World!") out = StringIO() command = Command(stdout=out) call_command(command) self.assertEqual(out.getvalue(), "Hello, World!\n") out.truncate(0) new_out = StringIO() call_command(command, stdout=new_out) self.assertEqual(out.getvalue(), "") self.assertEqual(new_out.getvalue(), "Hello, World!\n") def test_custom_stderr(self): class Command(BaseCommand): requires_system_checks = False def handle(self, *args, **options): self.stderr.write("Hello, World!") err = StringIO() command = Command(stderr=err) call_command(command) self.assertEqual(err.getvalue(), "Hello, World!\n") err.truncate(0) new_err = StringIO() call_command(command, stderr=new_err) self.assertEqual(err.getvalue(), "") self.assertEqual(new_err.getvalue(), "Hello, World!\n") def test_base_command(self): "User BaseCommands can execute when a label is provided" args = ['base_command', 'testlabel'] expected_labels = "('testlabel',)" self._test_base_command(args, expected_labels) def test_base_command_no_label(self): "User BaseCommands can execute when no labels are provided" args = ['base_command'] expected_labels = "()" self._test_base_command(args, expected_labels) def test_base_command_multiple_label(self): "User BaseCommands can execute when no labels are provided" args = ['base_command', 'testlabel', 'anotherlabel'] expected_labels = "('testlabel', 'anotherlabel')" self._test_base_command(args, expected_labels) def test_base_command_with_option(self): "User BaseCommands can execute with options when a label is provided" args = ['base_command', 'testlabel', '--option_a=x'] expected_labels = "('testlabel',)" self._test_base_command(args, expected_labels, option_a="'x'") def test_base_command_with_options(self): "User BaseCommands can execute with multiple options when a label is provided" args = ['base_command', 'testlabel', '-a', 'x', '--option_b=y'] expected_labels = "('testlabel',)" self._test_base_command(args, expected_labels, option_a="'x'", option_b="'y'") def test_base_command_with_wrong_option(self): "User BaseCommands outputs command usage when wrong option is specified" args = ['base_command', '--invalid'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "usage: manage.py base_command") self.assertOutput(err, "error: unrecognized arguments: --invalid") def _test_base_command(self, args, labels, option_a="'1'", option_b="'2'"): out, err = self.run_manage(args) expected_out = ( "EXECUTE:BaseCommand labels=%s, " "options=[('force_color', False), ('no_color', False), " "('option_a', %s), ('option_b', %s), ('option_c', '3'), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]") % (labels, option_a, option_b) self.assertNoOutput(err) self.assertOutput(out, expected_out) def test_base_run_from_argv(self): """ Test run_from_argv properly terminates even with custom execute() (#19665) Also test proper traceback display. """ err = StringIO() command = BaseCommand(stderr=err) def raise_command_error(*args, **kwargs): raise CommandError("Custom error") command.execute = lambda args: args # This will trigger TypeError # If the Exception is not CommandError it should always # raise the original exception. with self.assertRaises(TypeError): command.run_from_argv(['', '']) # If the Exception is CommandError and --traceback is not present # this command should raise a SystemExit and don't print any # traceback to the stderr. command.execute = raise_command_error err.truncate(0) with self.assertRaises(SystemExit): command.run_from_argv(['', '']) err_message = err.getvalue() self.assertNotIn("Traceback", err_message) self.assertIn("CommandError", err_message) # If the Exception is CommandError and --traceback is present # this command should raise the original CommandError as if it # were not a CommandError. err.truncate(0) with self.assertRaises(CommandError): command.run_from_argv(['', '', '--traceback']) def test_run_from_argv_non_ascii_error(self): """ Non-ASCII message of CommandError does not raise any UnicodeDecodeError in run_from_argv. """ def raise_command_error(*args, **kwargs): raise CommandError("Erreur personnalisée") command = BaseCommand(stderr=StringIO()) command.execute = raise_command_error with self.assertRaises(SystemExit): command.run_from_argv(['', '']) def test_run_from_argv_closes_connections(self): """ A command called from the command line should close connections after being executed (#21255). """ command = BaseCommand(stderr=StringIO()) command.check = lambda: [] command.handle = lambda *args, **kwargs: args with mock.patch('django.core.management.base.connections') as mock_connections: command.run_from_argv(['', '']) # Test connections have been closed self.assertTrue(mock_connections.close_all.called) def test_noargs(self): "NoArg Commands can be executed" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', False), ('pythonpath', None), ('settings', None), " "('traceback', False), ('verbosity', 1)]" ) def test_noargs_with_args(self): "NoArg Commands raise an error if an argument is provided" args = ['noargs_command', 'argument'] out, err = self.run_manage(args) self.assertOutput(err, "error: unrecognized arguments: argument") def test_app_command(self): "User AppCommands can execute when a single app name is provided" args = ['app_command', 'auth'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=") self.assertOutput( out, ", options=[('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]" ) def test_app_command_no_apps(self): "User AppCommands raise an error when no app name is provided" args = ['app_command'] out, err = self.run_manage(args) self.assertOutput(err, 'error: Enter at least one application label.') def test_app_command_multiple_apps(self): "User AppCommands raise an error when multiple app names are provided" args = ['app_command', 'auth', 'contenttypes'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=") self.assertOutput( out, ", options=[('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]" ) self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.contenttypes, options=") self.assertOutput( out, ", options=[('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]" ) def test_app_command_invalid_app_label(self): "User AppCommands can execute when a single app name is provided" args = ['app_command', 'NOT_AN_APP'] out, err = self.run_manage(args) self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.") def test_app_command_some_invalid_app_labels(self): "User AppCommands can execute when some of the provided app names are invalid" args = ['app_command', 'auth', 'NOT_AN_APP'] out, err = self.run_manage(args) self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.") def test_label_command(self): "User LabelCommands can execute when a label is provided" args = ['label_command', 'testlabel'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:LabelCommand label=testlabel, options=[('force_color', " "False), ('no_color', False), ('pythonpath', None), ('settings', " "None), ('traceback', False), ('verbosity', 1)]" ) def test_label_command_no_label(self): "User LabelCommands raise an error if no label is provided" args = ['label_command'] out, err = self.run_manage(args) self.assertOutput(err, 'Enter at least one label') def test_label_command_multiple_label(self): "User LabelCommands are executed multiple times if multiple labels are provided" args = ['label_command', 'testlabel', 'anotherlabel'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:LabelCommand label=testlabel, options=[('force_color', " "False), ('no_color', False), ('pythonpath', None), " "('settings', None), ('traceback', False), ('verbosity', 1)]" ) self.assertOutput( out, "EXECUTE:LabelCommand label=anotherlabel, options=[('force_color', " "False), ('no_color', False), ('pythonpath', None), " "('settings', None), ('traceback', False), ('verbosity', 1)]" ) class Discovery(SimpleTestCase): def test_precedence(self): """ Apps listed first in INSTALLED_APPS have precedence. """ with self.settings(INSTALLED_APPS=['admin_scripts.complex_app', 'admin_scripts.simple_app', 'django.contrib.auth', 'django.contrib.contenttypes']): out = StringIO() call_command('duplicate', stdout=out) self.assertEqual(out.getvalue().strip(), 'complex_app') with self.settings(INSTALLED_APPS=['admin_scripts.simple_app', 'admin_scripts.complex_app', 'django.contrib.auth', 'django.contrib.contenttypes']): out = StringIO() call_command('duplicate', stdout=out) self.assertEqual(out.getvalue().strip(), 'simple_app') class ArgumentOrder(AdminScriptTestCase): """Tests for 2-stage argument parsing scheme. django-admin command arguments are parsed in 2 parts; the core arguments (--settings, --traceback and --pythonpath) are parsed using a basic parser, ignoring any unknown options. Then the full settings are passed to the command parser, which extracts commands of interest to the individual command. """ def setUp(self): super().setUp() self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes']) self.write_settings('alternate_settings.py') def test_setting_then_option(self): """ Options passed after settings are correctly handled. """ args = ['base_command', 'testlabel', '--settings=alternate_settings', '--option_a=x'] self._test(args) def test_setting_then_short_option(self): """ Short options passed after settings are correctly handled. """ args = ['base_command', 'testlabel', '--settings=alternate_settings', '-a', 'x'] self._test(args) def test_option_then_setting(self): """ Options passed before settings are correctly handled. """ args = ['base_command', 'testlabel', '--option_a=x', '--settings=alternate_settings'] self._test(args) def test_short_option_then_setting(self): """ Short options passed before settings are correctly handled. """ args = ['base_command', 'testlabel', '-a', 'x', '--settings=alternate_settings'] self._test(args) def test_option_then_setting_then_option(self): """ Options are correctly handled when they are passed before and after a setting. """ args = ['base_command', 'testlabel', '--option_a=x', '--settings=alternate_settings', '--option_b=y'] self._test(args, option_b="'y'") def _test(self, args, option_b="'2'"): out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:BaseCommand labels=('testlabel',), options=[" "('force_color', False), ('no_color', False), ('option_a', 'x'), " "('option_b', %s), ('option_c', '3'), ('pythonpath', None), " "('settings', 'alternate_settings'), ('traceback', False), " "('verbosity', 1)]" % option_b ) @override_settings(ROOT_URLCONF='admin_scripts.urls') class StartProject(LiveServerTestCase, AdminScriptTestCase): available_apps = [ 'admin_scripts', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', ] def test_wrong_args(self): "Make sure passing the wrong kinds of arguments outputs an error and prints usage" out, err = self.run_django_admin(['startproject']) self.assertNoOutput(out) self.assertOutput(err, "usage:") self.assertOutput(err, "You must provide a project name.") def test_simple_project(self): "Make sure the startproject management command creates a project" args = ['startproject', 'testproject'] testproject_dir = os.path.join(self.test_dir, 'testproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) # running again.. out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "already exists") def test_invalid_project_name(self): "Make sure the startproject management command validates a project name" for bad_name in ('7testproject', '../testproject'): with self.subTest(project_name=bad_name): args = ['startproject', bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "Error: '%s' is not a valid project name. Please make " "sure the name is a valid identifier." % bad_name ) self.assertFalse(os.path.exists(testproject_dir)) def test_importable_project_name(self): """ startproject validates that project name doesn't clash with existing Python modules. """ bad_name = 'os' args = ['startproject', bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "CommandError: 'os' conflicts with the name of an existing " "Python module and cannot be used as a project name. Please try " "another name." ) self.assertFalse(os.path.exists(testproject_dir)) def test_simple_project_different_directory(self): "Make sure the startproject management command creates a project in a specific directory" args = ['startproject', 'testproject', 'othertestproject'] testproject_dir = os.path.join(self.test_dir, 'othertestproject') os.mkdir(testproject_dir) out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'manage.py'))) # running again.. out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput( err, "already exists. Overlaying a project into an existing directory " "won't replace conflicting files." ) def test_custom_project_template(self): "Make sure the startproject management command is able to use a different project template" template_path = os.path.join(custom_templates_dir, 'project_template') args = ['startproject', '--template', template_path, 'customtestproject'] testproject_dir = os.path.join(self.test_dir, 'customtestproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'additional_dir'))) def test_template_dir_with_trailing_slash(self): "Ticket 17475: Template dir passed has a trailing path separator" template_path = os.path.join(custom_templates_dir, 'project_template' + os.sep) args = ['startproject', '--template', template_path, 'customtestproject'] testproject_dir = os.path.join(self.test_dir, 'customtestproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'additional_dir'))) def test_custom_project_template_from_tarball_by_path(self): "Make sure the startproject management command is able to use a different project template from a tarball" template_path = os.path.join(custom_templates_dir, 'project_template.tgz') args = ['startproject', '--template', template_path, 'tarballtestproject'] testproject_dir = os.path.join(self.test_dir, 'tarballtestproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py'))) def test_custom_project_template_from_tarball_to_alternative_location(self): "Startproject can use a project template from a tarball and create it in a specified location" template_path = os.path.join(custom_templates_dir, 'project_template.tgz') args = ['startproject', '--template', template_path, 'tarballtestproject', 'altlocation'] testproject_dir = os.path.join(self.test_dir, 'altlocation') os.mkdir(testproject_dir) out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py'))) def test_custom_project_template_from_tarball_by_url(self): """ The startproject management command is able to use a different project template from a tarball via a URL. """ template_url = '%s/custom_templates/project_template.tgz' % self.live_server_url args = ['startproject', '--template', template_url, 'urltestproject'] testproject_dir = os.path.join(self.test_dir, 'urltestproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py'))) def test_project_template_tarball_url(self): "Startproject management command handles project template tar/zip balls from non-canonical urls" template_url = '%s/custom_templates/project_template.tgz/' % self.live_server_url args = ['startproject', '--template', template_url, 'urltestproject'] testproject_dir = os.path.join(self.test_dir, 'urltestproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py'))) def test_file_without_extension(self): "Make sure the startproject management command is able to render custom files" template_path = os.path.join(custom_templates_dir, 'project_template') args = ['startproject', '--template', template_path, 'customtestproject', '-e', 'txt', '-n', 'Procfile'] testproject_dir = os.path.join(self.test_dir, 'customtestproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'additional_dir'))) base_path = os.path.join(testproject_dir, 'additional_dir') for f in ('Procfile', 'additional_file.py', 'requirements.txt'): self.assertTrue(os.path.exists(os.path.join(base_path, f))) with open(os.path.join(base_path, f)) as fh: self.assertEqual(fh.read().strip(), '# some file for customtestproject test project') def test_custom_project_template_context_variables(self): "Make sure template context variables are rendered with proper values" template_path = os.path.join(custom_templates_dir, 'project_template') args = ['startproject', '--template', template_path, 'another_project', 'project_dir'] testproject_dir = os.path.join(self.test_dir, 'project_dir') os.mkdir(testproject_dir) out, err = self.run_django_admin(args) self.assertNoOutput(err) test_manage_py = os.path.join(testproject_dir, 'manage.py') with open(test_manage_py) as fp: content = fp.read() self.assertIn("project_name = 'another_project'", content) self.assertIn("project_directory = '%s'" % testproject_dir, content) def test_no_escaping_of_project_variables(self): "Make sure template context variables are not html escaped" # We're using a custom command so we need the alternate settings self.write_settings('alternate_settings.py') template_path = os.path.join(custom_templates_dir, 'project_template') args = [ 'custom_startproject', '--template', template_path, 'another_project', 'project_dir', '--extra', '<&>', '--settings=alternate_settings', ] testproject_dir = os.path.join(self.test_dir, 'project_dir') os.mkdir(testproject_dir) out, err = self.run_manage(args) self.assertNoOutput(err) test_manage_py = os.path.join(testproject_dir, 'additional_dir', 'extra.py') with open(test_manage_py) as fp: content = fp.read() self.assertIn("<&>", content) def test_custom_project_destination_missing(self): """ Make sure an exception is raised when the provided destination directory doesn't exist """ template_path = os.path.join(custom_templates_dir, 'project_template') args = ['startproject', '--template', template_path, 'yet_another_project', 'project_dir2'] testproject_dir = os.path.join(self.test_dir, 'project_dir2') out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Destination directory '%s' does not exist, please create it first." % testproject_dir) self.assertFalse(os.path.exists(testproject_dir)) def test_custom_project_template_with_non_ascii_templates(self): """ The startproject management command is able to render templates with non-ASCII content. """ template_path = os.path.join(custom_templates_dir, 'project_template') args = ['startproject', '--template', template_path, '--extension=txt', 'customtestproject'] testproject_dir = os.path.join(self.test_dir, 'customtestproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) path = os.path.join(testproject_dir, 'ticket-18091-non-ascii-template.txt') with open(path, encoding='utf-8') as f: self.assertEqual(f.read().splitlines(False), [ 'Some non-ASCII text for testing ticket #18091:', 'üäö €']) class StartApp(AdminScriptTestCase): def test_invalid_name(self): """startapp validates that app name is a valid Python identifier.""" for bad_name in ('7testproject', '../testproject'): with self.subTest(app_name=bad_name): args = ['startapp', bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "CommandError: '{}' is not a valid app name. Please make " "sure the name is a valid identifier.".format(bad_name) ) self.assertFalse(os.path.exists(testproject_dir)) def test_importable_name(self): """ startapp validates that app name doesn't clash with existing Python modules. """ bad_name = 'os' args = ['startapp', bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "CommandError: 'os' conflicts with the name of an existing " "Python module and cannot be used as an app name. Please try " "another name." ) self.assertFalse(os.path.exists(testproject_dir)) def test_invalid_target_name(self): for bad_target in ('invalid.dir_name', '7invalid_dir_name', '.invalid_dir_name'): with self.subTest(bad_target): _, err = self.run_django_admin(['startapp', 'app', bad_target]) self.assertOutput( err, "CommandError: '%s' is not a valid app directory. Please " "make sure the directory is a valid identifier." % bad_target ) def test_importable_target_name(self): _, err = self.run_django_admin(['startapp', 'app', 'os']) self.assertOutput( err, "CommandError: 'os' conflicts with the name of an existing Python " "module and cannot be used as an app directory. Please try " "another directory." ) def test_overlaying_app(self): self.run_django_admin(['startapp', 'app1']) out, err = self.run_django_admin(['startapp', 'app2', 'app1']) self.assertOutput( err, "already exists. Overlaying an app into an existing directory " "won't replace conflicting files." ) class DiffSettings(AdminScriptTestCase): """Tests for diffsettings management command.""" def test_basic(self): """Runs without error and emits settings diff.""" self.write_settings('settings_to_diff.py', sdict={'FOO': '"bar"'}) args = ['diffsettings', '--settings=settings_to_diff'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "FOO = 'bar' ###") # Attributes from django.conf.Settings don't appear. self.assertNotInOutput(out, 'is_overridden = ') def test_settings_configured(self): out, err = self.run_manage(['diffsettings'], manage_py='configured_settings_manage.py') self.assertNoOutput(err) self.assertOutput(out, 'CUSTOM = 1 ###\nDEBUG = True') # Attributes from django.conf.UserSettingsHolder don't appear. self.assertNotInOutput(out, 'default_settings = ') def test_dynamic_settings_configured(self): # Custom default settings appear. out, err = self.run_manage(['diffsettings'], manage_py='configured_dynamic_settings_manage.py') self.assertNoOutput(err) self.assertOutput(out, "FOO = 'bar' ###") def test_all(self): """The all option also shows settings with the default value.""" self.write_settings('settings_to_diff.py', sdict={'STATIC_URL': 'None'}) args = ['diffsettings', '--settings=settings_to_diff', '--all'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "### STATIC_URL = None") def test_custom_default(self): """ The --default option specifies an alternate settings module for comparison. """ self.write_settings('settings_default.py', sdict={'FOO': '"foo"', 'BAR': '"bar1"'}) self.write_settings('settings_to_diff.py', sdict={'FOO': '"foo"', 'BAR': '"bar2"'}) out, err = self.run_manage(['diffsettings', '--settings=settings_to_diff', '--default=settings_default']) self.assertNoOutput(err) self.assertNotInOutput(out, "FOO") self.assertOutput(out, "BAR = 'bar2'") def test_unified(self): """--output=unified emits settings diff in unified mode.""" self.write_settings('settings_to_diff.py', sdict={'FOO': '"bar"'}) args = ['diffsettings', '--settings=settings_to_diff', '--output=unified'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "+ FOO = 'bar'") self.assertOutput(out, "- SECRET_KEY = ''") self.assertOutput(out, "+ SECRET_KEY = 'django_tests_secret_key'") self.assertNotInOutput(out, " APPEND_SLASH = True") def test_unified_all(self): """ --output=unified --all emits settings diff in unified mode and includes settings with the default value. """ self.write_settings('settings_to_diff.py', sdict={'FOO': '"bar"'}) args = ['diffsettings', '--settings=settings_to_diff', '--output=unified', '--all'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, " APPEND_SLASH = True") self.assertOutput(out, "+ FOO = 'bar'") self.assertOutput(out, "- SECRET_KEY = ''") class Dumpdata(AdminScriptTestCase): """Tests for dumpdata management command.""" def setUp(self): super().setUp() self.write_settings('settings.py') def test_pks_parsing(self): """Regression for #20509 Test would raise an exception rather than printing an error message. """ args = ['dumpdata', '--pks=1'] out, err = self.run_manage(args) self.assertOutput(err, "You can only use --pks option with one model") self.assertNoOutput(out) class MainModule(AdminScriptTestCase): """python -m django works like django-admin.""" def test_runs_django_admin(self): cmd_out, _ = self.run_django_admin(['--version']) mod_out, _ = self.run_test('-m', ['django', '--version']) self.assertEqual(mod_out, cmd_out) def test_program_name_in_help(self): out, err = self.run_test('-m', ['django', 'help']) self.assertOutput(out, "Type 'python -m django help <subcommand>' for help on a specific subcommand.") class DjangoAdminSuggestions(AdminScriptTestCase): def setUp(self): super().setUp() self.write_settings('settings.py') def test_suggestions(self): args = ['rnserver', '--settings=test_project.settings'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'rnserver'. Did you mean runserver?") def test_no_suggestions(self): args = ['abcdef', '--settings=test_project.settings'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertNotInOutput(err, 'Did you mean')
422b8fc46dcdd8a19875b9ebbaabd0cc7d99c84fb90c34c9de84231412b0b09c
from operator import attrgetter from django.db import IntegrityError, NotSupportedError, connection from django.db.models import FileField, Value from django.db.models.functions import Lower from django.test import ( TestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from .models import ( Country, NoFields, NullableFields, Pizzeria, ProxyCountry, ProxyMultiCountry, ProxyMultiProxyCountry, ProxyProxyCountry, Restaurant, State, TwoFields, ) class BulkCreateTests(TestCase): def setUp(self): self.data = [ Country(name="United States of America", iso_two_letter="US"), Country(name="The Netherlands", iso_two_letter="NL"), Country(name="Germany", iso_two_letter="DE"), Country(name="Czech Republic", iso_two_letter="CZ") ] def test_simple(self): created = Country.objects.bulk_create(self.data) self.assertEqual(len(created), 4) self.assertQuerysetEqual(Country.objects.order_by("-name"), [ "United States of America", "The Netherlands", "Germany", "Czech Republic" ], attrgetter("name")) created = Country.objects.bulk_create([]) self.assertEqual(created, []) self.assertEqual(Country.objects.count(), 4) @skipUnlessDBFeature('has_bulk_insert') def test_efficiency(self): with self.assertNumQueries(1): Country.objects.bulk_create(self.data) @skipUnlessDBFeature('has_bulk_insert') def test_long_non_ascii_text(self): """ Inserting non-ASCII values with a length in the range 2001 to 4000 characters, i.e. 4002 to 8000 bytes, must be set as a CLOB on Oracle (#22144). """ Country.objects.bulk_create([Country(description='Ж' * 3000)]) self.assertEqual(Country.objects.count(), 1) @skipUnlessDBFeature('has_bulk_insert') def test_long_and_short_text(self): Country.objects.bulk_create([ Country(description='a' * 4001), Country(description='a'), Country(description='Ж' * 2001), Country(description='Ж'), ]) self.assertEqual(Country.objects.count(), 4) def test_multi_table_inheritance_unsupported(self): expected_message = "Can't bulk create a multi-table inherited model" with self.assertRaisesMessage(ValueError, expected_message): Pizzeria.objects.bulk_create([ Pizzeria(name="The Art of Pizza"), ]) with self.assertRaisesMessage(ValueError, expected_message): ProxyMultiCountry.objects.bulk_create([ ProxyMultiCountry(name="Fillory", iso_two_letter="FL"), ]) with self.assertRaisesMessage(ValueError, expected_message): ProxyMultiProxyCountry.objects.bulk_create([ ProxyMultiProxyCountry(name="Fillory", iso_two_letter="FL"), ]) def test_proxy_inheritance_supported(self): ProxyCountry.objects.bulk_create([ ProxyCountry(name="Qwghlm", iso_two_letter="QW"), Country(name="Tortall", iso_two_letter="TA"), ]) self.assertQuerysetEqual(ProxyCountry.objects.all(), { "Qwghlm", "Tortall" }, attrgetter("name"), ordered=False) ProxyProxyCountry.objects.bulk_create([ ProxyProxyCountry(name="Netherlands", iso_two_letter="NT"), ]) self.assertQuerysetEqual(ProxyProxyCountry.objects.all(), { "Qwghlm", "Tortall", "Netherlands", }, attrgetter("name"), ordered=False) def test_non_auto_increment_pk(self): State.objects.bulk_create([ State(two_letter_code=s) for s in ["IL", "NY", "CA", "ME"] ]) self.assertQuerysetEqual(State.objects.order_by("two_letter_code"), [ "CA", "IL", "ME", "NY", ], attrgetter("two_letter_code")) @skipUnlessDBFeature('has_bulk_insert') def test_non_auto_increment_pk_efficiency(self): with self.assertNumQueries(1): State.objects.bulk_create([ State(two_letter_code=s) for s in ["IL", "NY", "CA", "ME"] ]) self.assertQuerysetEqual(State.objects.order_by("two_letter_code"), [ "CA", "IL", "ME", "NY", ], attrgetter("two_letter_code")) @skipIfDBFeature('allows_auto_pk_0') def test_zero_as_autoval(self): """ Zero as id for AutoField should raise exception in MySQL, because MySQL does not allow zero for automatic primary key. """ valid_country = Country(name='Germany', iso_two_letter='DE') invalid_country = Country(id=0, name='Poland', iso_two_letter='PL') msg = 'The database backend does not accept 0 as a value for AutoField.' with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create([valid_country, invalid_country]) def test_batch_same_vals(self): # SQLite had a problem where all the same-valued models were # collapsed to one insert. Restaurant.objects.bulk_create([ Restaurant(name='foo') for i in range(0, 2) ]) self.assertEqual(Restaurant.objects.count(), 2) def test_large_batch(self): TwoFields.objects.bulk_create([ TwoFields(f1=i, f2=i + 1) for i in range(0, 1001) ]) self.assertEqual(TwoFields.objects.count(), 1001) self.assertEqual( TwoFields.objects.filter(f1__gte=450, f1__lte=550).count(), 101) self.assertEqual(TwoFields.objects.filter(f2__gte=901).count(), 101) @skipUnlessDBFeature('has_bulk_insert') def test_large_single_field_batch(self): # SQLite had a problem with more than 500 UNIONed selects in single # query. Restaurant.objects.bulk_create([ Restaurant() for i in range(0, 501) ]) @skipUnlessDBFeature('has_bulk_insert') def test_large_batch_efficiency(self): with override_settings(DEBUG=True): connection.queries_log.clear() TwoFields.objects.bulk_create([ TwoFields(f1=i, f2=i + 1) for i in range(0, 1001) ]) self.assertLess(len(connection.queries), 10) def test_large_batch_mixed(self): """ Test inserting a large batch with objects having primary key set mixed together with objects without PK set. """ TwoFields.objects.bulk_create([ TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1) for i in range(100000, 101000) ]) self.assertEqual(TwoFields.objects.count(), 1000) # We can't assume much about the ID's created, except that the above # created IDs must exist. id_range = range(100000, 101000, 2) self.assertEqual(TwoFields.objects.filter(id__in=id_range).count(), 500) self.assertEqual(TwoFields.objects.exclude(id__in=id_range).count(), 500) @skipUnlessDBFeature('has_bulk_insert') def test_large_batch_mixed_efficiency(self): """ Test inserting a large batch with objects having primary key set mixed together with objects without PK set. """ with override_settings(DEBUG=True): connection.queries_log.clear() TwoFields.objects.bulk_create([ TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1) for i in range(100000, 101000)]) self.assertLess(len(connection.queries), 10) def test_explicit_batch_size(self): objs = [TwoFields(f1=i, f2=i) for i in range(0, 4)] num_objs = len(objs) TwoFields.objects.bulk_create(objs, batch_size=1) self.assertEqual(TwoFields.objects.count(), num_objs) TwoFields.objects.all().delete() TwoFields.objects.bulk_create(objs, batch_size=2) self.assertEqual(TwoFields.objects.count(), num_objs) TwoFields.objects.all().delete() TwoFields.objects.bulk_create(objs, batch_size=3) self.assertEqual(TwoFields.objects.count(), num_objs) TwoFields.objects.all().delete() TwoFields.objects.bulk_create(objs, batch_size=num_objs) self.assertEqual(TwoFields.objects.count(), num_objs) def test_empty_model(self): NoFields.objects.bulk_create([NoFields() for i in range(2)]) self.assertEqual(NoFields.objects.count(), 2) @skipUnlessDBFeature('has_bulk_insert') def test_explicit_batch_size_efficiency(self): objs = [TwoFields(f1=i, f2=i) for i in range(0, 100)] with self.assertNumQueries(2): TwoFields.objects.bulk_create(objs, 50) TwoFields.objects.all().delete() with self.assertNumQueries(1): TwoFields.objects.bulk_create(objs, len(objs)) @skipUnlessDBFeature('has_bulk_insert') def test_bulk_insert_expressions(self): Restaurant.objects.bulk_create([ Restaurant(name="Sam's Shake Shack"), Restaurant(name=Lower(Value("Betty's Beetroot Bar"))) ]) bbb = Restaurant.objects.filter(name="betty's beetroot bar") self.assertEqual(bbb.count(), 1) @skipUnlessDBFeature('has_bulk_insert') def test_bulk_insert_nullable_fields(self): # NULL can be mixed with other values in nullable fields nullable_fields = [field for field in NullableFields._meta.get_fields() if field.name != 'id'] NullableFields.objects.bulk_create([ NullableFields(**{field.name: None}) for field in nullable_fields ]) self.assertEqual(NullableFields.objects.count(), len(nullable_fields)) for field in nullable_fields: with self.subTest(field=field): field_value = '' if isinstance(field, FileField) else None self.assertEqual(NullableFields.objects.filter(**{field.name: field_value}).count(), 1) @skipUnlessDBFeature('can_return_rows_from_bulk_insert') def test_set_pk_and_insert_single_item(self): with self.assertNumQueries(1): countries = Country.objects.bulk_create([self.data[0]]) self.assertEqual(len(countries), 1) self.assertEqual(Country.objects.get(pk=countries[0].pk), countries[0]) @skipUnlessDBFeature('can_return_rows_from_bulk_insert') def test_set_pk_and_query_efficiency(self): with self.assertNumQueries(1): countries = Country.objects.bulk_create(self.data) self.assertEqual(len(countries), 4) self.assertEqual(Country.objects.get(pk=countries[0].pk), countries[0]) self.assertEqual(Country.objects.get(pk=countries[1].pk), countries[1]) self.assertEqual(Country.objects.get(pk=countries[2].pk), countries[2]) self.assertEqual(Country.objects.get(pk=countries[3].pk), countries[3]) @skipUnlessDBFeature('can_return_rows_from_bulk_insert') def test_set_state(self): country_nl = Country(name='Netherlands', iso_two_letter='NL') country_be = Country(name='Belgium', iso_two_letter='BE') Country.objects.bulk_create([country_nl]) country_be.save() # Objects save via bulk_create() and save() should have equal state. self.assertEqual(country_nl._state.adding, country_be._state.adding) self.assertEqual(country_nl._state.db, country_be._state.db) def test_set_state_with_pk_specified(self): state_ca = State(two_letter_code='CA') state_ny = State(two_letter_code='NY') State.objects.bulk_create([state_ca]) state_ny.save() # Objects save via bulk_create() and save() should have equal state. self.assertEqual(state_ca._state.adding, state_ny._state.adding) self.assertEqual(state_ca._state.db, state_ny._state.db) @skipIfDBFeature('supports_ignore_conflicts') def test_ignore_conflicts_value_error(self): message = 'This database backend does not support ignoring conflicts.' with self.assertRaisesMessage(NotSupportedError, message): TwoFields.objects.bulk_create(self.data, ignore_conflicts=True) @skipUnlessDBFeature('supports_ignore_conflicts') def test_ignore_conflicts_ignore(self): data = [ TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2), TwoFields(f1=3, f2=3), ] TwoFields.objects.bulk_create(data) self.assertEqual(TwoFields.objects.count(), 3) # With ignore_conflicts=True, conflicts are ignored. conflicting_objects = [ TwoFields(f1=2, f2=2), TwoFields(f1=3, f2=3), ] TwoFields.objects.bulk_create([conflicting_objects[0]], ignore_conflicts=True) TwoFields.objects.bulk_create(conflicting_objects, ignore_conflicts=True) self.assertEqual(TwoFields.objects.count(), 3) self.assertIsNone(conflicting_objects[0].pk) self.assertIsNone(conflicting_objects[1].pk) # New objects are created and conflicts are ignored. new_object = TwoFields(f1=4, f2=4) TwoFields.objects.bulk_create(conflicting_objects + [new_object], ignore_conflicts=True) self.assertEqual(TwoFields.objects.count(), 4) self.assertIsNone(new_object.pk) # Without ignore_conflicts=True, there's a problem. with self.assertRaises(IntegrityError): TwoFields.objects.bulk_create(conflicting_objects)
77e6e30f94e3ea2dcbf92bc5c81cf839435e473752d0aa7f94f89a22e602fff8
import datetime from unittest import mock, skipIf, skipUnless from django.core.exceptions import FieldError from django.db import NotSupportedError, connection from django.db.models import ( F, Func, OuterRef, Q, RowRange, Subquery, Value, ValueRange, Window, WindowFrame, ) from django.db.models.aggregates import Avg, Max, Min, Sum from django.db.models.functions import ( CumeDist, DenseRank, ExtractYear, FirstValue, Lag, LastValue, Lead, NthValue, Ntile, PercentRank, Rank, RowNumber, Upper, ) from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from .models import Employee @skipUnlessDBFeature('supports_over_clause') class WindowFunctionTests(TestCase): @classmethod def setUpTestData(cls): Employee.objects.bulk_create([ Employee(name=e[0], salary=e[1], department=e[2], hire_date=e[3], age=e[4]) for e in [ ('Jones', 45000, 'Accounting', datetime.datetime(2005, 11, 1), 20), ('Williams', 37000, 'Accounting', datetime.datetime(2009, 6, 1), 20), ('Jenson', 45000, 'Accounting', datetime.datetime(2008, 4, 1), 20), ('Adams', 50000, 'Accounting', datetime.datetime(2013, 7, 1), 50), ('Smith', 55000, 'Sales', datetime.datetime(2007, 6, 1), 30), ('Brown', 53000, 'Sales', datetime.datetime(2009, 9, 1), 30), ('Johnson', 40000, 'Marketing', datetime.datetime(2012, 3, 1), 30), ('Smith', 38000, 'Marketing', datetime.datetime(2009, 10, 1), 20), ('Wilkinson', 60000, 'IT', datetime.datetime(2011, 3, 1), 40), ('Moore', 34000, 'IT', datetime.datetime(2013, 8, 1), 40), ('Miller', 100000, 'Management', datetime.datetime(2005, 6, 1), 40), ('Johnson', 80000, 'Management', datetime.datetime(2005, 7, 1), 50), ] ]) def test_dense_rank(self): qs = Employee.objects.annotate(rank=Window( expression=DenseRank(), order_by=ExtractYear(F('hire_date')).asc(), )) self.assertQuerysetEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 1), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 1), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), 1), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 2), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 3), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 4), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), 4), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 4), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 5), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), 6), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), 7), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), 7), ], lambda entry: (entry.name, entry.salary, entry.department, entry.hire_date, entry.rank), ordered=False) def test_department_salary(self): qs = Employee.objects.annotate(department_sum=Window( expression=Sum('salary'), partition_by=F('department'), order_by=[F('hire_date').asc()], )).order_by('department', 'department_sum') self.assertQuerysetEqual(qs, [ ('Jones', 'Accounting', 45000, 45000), ('Jenson', 'Accounting', 45000, 90000), ('Williams', 'Accounting', 37000, 127000), ('Adams', 'Accounting', 50000, 177000), ('Wilkinson', 'IT', 60000, 60000), ('Moore', 'IT', 34000, 94000), ('Miller', 'Management', 100000, 100000), ('Johnson', 'Management', 80000, 180000), ('Smith', 'Marketing', 38000, 38000), ('Johnson', 'Marketing', 40000, 78000), ('Smith', 'Sales', 55000, 55000), ('Brown', 'Sales', 53000, 108000), ], lambda entry: (entry.name, entry.department, entry.salary, entry.department_sum)) def test_rank(self): """ Rank the employees based on the year they're were hired. Since there are multiple employees hired in different years, this will contain gaps. """ qs = Employee.objects.annotate(rank=Window( expression=Rank(), order_by=ExtractYear(F('hire_date')).asc(), )) self.assertQuerysetEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 1), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 1), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), 1), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 4), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 5), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 6), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), 6), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 6), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 9), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), 10), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), 11), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), 11), ], lambda entry: (entry.name, entry.salary, entry.department, entry.hire_date, entry.rank), ordered=False) def test_row_number(self): """ The row number window function computes the number based on the order in which the tuples were inserted. Depending on the backend, Oracle requires an ordering-clause in the Window expression. """ qs = Employee.objects.annotate(row_number=Window( expression=RowNumber(), order_by=F('pk').asc(), )).order_by('pk') self.assertQuerysetEqual(qs, [ ('Jones', 'Accounting', 1), ('Williams', 'Accounting', 2), ('Jenson', 'Accounting', 3), ('Adams', 'Accounting', 4), ('Smith', 'Sales', 5), ('Brown', 'Sales', 6), ('Johnson', 'Marketing', 7), ('Smith', 'Marketing', 8), ('Wilkinson', 'IT', 9), ('Moore', 'IT', 10), ('Miller', 'Management', 11), ('Johnson', 'Management', 12), ], lambda entry: (entry.name, entry.department, entry.row_number)) @skipIf(connection.vendor == 'oracle', "Oracle requires ORDER BY in row_number, ANSI:SQL doesn't") def test_row_number_no_ordering(self): """ The row number window function computes the number based on the order in which the tuples were inserted. """ # Add a default ordering for consistent results across databases. qs = Employee.objects.annotate(row_number=Window( expression=RowNumber(), )).order_by('pk') self.assertQuerysetEqual(qs, [ ('Jones', 'Accounting', 1), ('Williams', 'Accounting', 2), ('Jenson', 'Accounting', 3), ('Adams', 'Accounting', 4), ('Smith', 'Sales', 5), ('Brown', 'Sales', 6), ('Johnson', 'Marketing', 7), ('Smith', 'Marketing', 8), ('Wilkinson', 'IT', 9), ('Moore', 'IT', 10), ('Miller', 'Management', 11), ('Johnson', 'Management', 12), ], lambda entry: (entry.name, entry.department, entry.row_number)) def test_avg_salary_department(self): qs = Employee.objects.annotate(avg_salary=Window( expression=Avg('salary'), order_by=F('department').asc(), partition_by='department', )).order_by('department', '-salary', 'name') self.assertQuerysetEqual(qs, [ ('Adams', 50000, 'Accounting', 44250.00), ('Jenson', 45000, 'Accounting', 44250.00), ('Jones', 45000, 'Accounting', 44250.00), ('Williams', 37000, 'Accounting', 44250.00), ('Wilkinson', 60000, 'IT', 47000.00), ('Moore', 34000, 'IT', 47000.00), ('Miller', 100000, 'Management', 90000.00), ('Johnson', 80000, 'Management', 90000.00), ('Johnson', 40000, 'Marketing', 39000.00), ('Smith', 38000, 'Marketing', 39000.00), ('Smith', 55000, 'Sales', 54000.00), ('Brown', 53000, 'Sales', 54000.00), ], transform=lambda row: (row.name, row.salary, row.department, row.avg_salary)) def test_lag(self): """ Compute the difference between an employee's salary and the next highest salary in the employee's department. Return None if the employee has the lowest salary. """ qs = Employee.objects.annotate(lag=Window( expression=Lag(expression='salary', offset=1), partition_by=F('department'), order_by=[F('salary').asc(), F('name').asc()], )).order_by('department', F('salary').asc(), F('name').asc()) self.assertQuerysetEqual(qs, [ ('Williams', 37000, 'Accounting', None), ('Jenson', 45000, 'Accounting', 37000), ('Jones', 45000, 'Accounting', 45000), ('Adams', 50000, 'Accounting', 45000), ('Moore', 34000, 'IT', None), ('Wilkinson', 60000, 'IT', 34000), ('Johnson', 80000, 'Management', None), ('Miller', 100000, 'Management', 80000), ('Smith', 38000, 'Marketing', None), ('Johnson', 40000, 'Marketing', 38000), ('Brown', 53000, 'Sales', None), ('Smith', 55000, 'Sales', 53000), ], transform=lambda row: (row.name, row.salary, row.department, row.lag)) def test_first_value(self): qs = Employee.objects.annotate(first_value=Window( expression=FirstValue('salary'), partition_by=F('department'), order_by=F('hire_date').asc(), )).order_by('department', 'hire_date') self.assertQuerysetEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 45000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 45000), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 45000), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), 45000), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 60000), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), 60000), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 100000), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), 100000), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 38000), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), 38000), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 55000), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), 55000), ], lambda row: (row.name, row.salary, row.department, row.hire_date, row.first_value)) def test_last_value(self): qs = Employee.objects.annotate(last_value=Window( expression=LastValue('hire_date'), partition_by=F('department'), order_by=F('hire_date').asc(), )) self.assertQuerysetEqual(qs, [ ('Adams', 'Accounting', datetime.date(2013, 7, 1), 50000, datetime.date(2013, 7, 1)), ('Jenson', 'Accounting', datetime.date(2008, 4, 1), 45000, datetime.date(2008, 4, 1)), ('Jones', 'Accounting', datetime.date(2005, 11, 1), 45000, datetime.date(2005, 11, 1)), ('Williams', 'Accounting', datetime.date(2009, 6, 1), 37000, datetime.date(2009, 6, 1)), ('Moore', 'IT', datetime.date(2013, 8, 1), 34000, datetime.date(2013, 8, 1)), ('Wilkinson', 'IT', datetime.date(2011, 3, 1), 60000, datetime.date(2011, 3, 1)), ('Miller', 'Management', datetime.date(2005, 6, 1), 100000, datetime.date(2005, 6, 1)), ('Johnson', 'Management', datetime.date(2005, 7, 1), 80000, datetime.date(2005, 7, 1)), ('Johnson', 'Marketing', datetime.date(2012, 3, 1), 40000, datetime.date(2012, 3, 1)), ('Smith', 'Marketing', datetime.date(2009, 10, 1), 38000, datetime.date(2009, 10, 1)), ('Brown', 'Sales', datetime.date(2009, 9, 1), 53000, datetime.date(2009, 9, 1)), ('Smith', 'Sales', datetime.date(2007, 6, 1), 55000, datetime.date(2007, 6, 1)), ], transform=lambda row: (row.name, row.department, row.hire_date, row.salary, row.last_value), ordered=False) def test_function_list_of_values(self): qs = Employee.objects.annotate(lead=Window( expression=Lead(expression='salary'), order_by=[F('hire_date').asc(), F('name').desc()], partition_by='department', )).values_list('name', 'salary', 'department', 'hire_date', 'lead') \ .order_by('department', F('hire_date').asc(), F('name').desc()) self.assertNotIn('GROUP BY', str(qs.query)) self.assertSequenceEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 45000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 37000), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 50000), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), None), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 34000), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), None), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 80000), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), None), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 40000), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), None), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 53000), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), None), ]) def test_min_department(self): """An alternative way to specify a query for FirstValue.""" qs = Employee.objects.annotate(min_salary=Window( expression=Min('salary'), partition_by=F('department'), order_by=[F('salary').asc(), F('name').asc()] )).order_by('department', 'salary', 'name') self.assertQuerysetEqual(qs, [ ('Williams', 'Accounting', 37000, 37000), ('Jenson', 'Accounting', 45000, 37000), ('Jones', 'Accounting', 45000, 37000), ('Adams', 'Accounting', 50000, 37000), ('Moore', 'IT', 34000, 34000), ('Wilkinson', 'IT', 60000, 34000), ('Johnson', 'Management', 80000, 80000), ('Miller', 'Management', 100000, 80000), ('Smith', 'Marketing', 38000, 38000), ('Johnson', 'Marketing', 40000, 38000), ('Brown', 'Sales', 53000, 53000), ('Smith', 'Sales', 55000, 53000), ], lambda row: (row.name, row.department, row.salary, row.min_salary)) def test_max_per_year(self): """ Find the maximum salary awarded in the same year as the employee was hired, regardless of the department. """ qs = Employee.objects.annotate(max_salary_year=Window( expression=Max('salary'), order_by=ExtractYear('hire_date').asc(), partition_by=ExtractYear('hire_date') )).order_by(ExtractYear('hire_date'), 'salary') self.assertQuerysetEqual(qs, [ ('Jones', 'Accounting', 45000, 2005, 100000), ('Johnson', 'Management', 80000, 2005, 100000), ('Miller', 'Management', 100000, 2005, 100000), ('Smith', 'Sales', 55000, 2007, 55000), ('Jenson', 'Accounting', 45000, 2008, 45000), ('Williams', 'Accounting', 37000, 2009, 53000), ('Smith', 'Marketing', 38000, 2009, 53000), ('Brown', 'Sales', 53000, 2009, 53000), ('Wilkinson', 'IT', 60000, 2011, 60000), ('Johnson', 'Marketing', 40000, 2012, 40000), ('Moore', 'IT', 34000, 2013, 50000), ('Adams', 'Accounting', 50000, 2013, 50000), ], lambda row: (row.name, row.department, row.salary, row.hire_date.year, row.max_salary_year)) def test_cume_dist(self): """ Compute the cumulative distribution for the employees based on the salary in increasing order. Equal to rank/total number of rows (12). """ qs = Employee.objects.annotate(cume_dist=Window( expression=CumeDist(), order_by=F('salary').asc(), )).order_by('salary', 'name') # Round result of cume_dist because Oracle uses greater precision. self.assertQuerysetEqual(qs, [ ('Moore', 'IT', 34000, 0.0833333333), ('Williams', 'Accounting', 37000, 0.1666666667), ('Smith', 'Marketing', 38000, 0.25), ('Johnson', 'Marketing', 40000, 0.3333333333), ('Jenson', 'Accounting', 45000, 0.5), ('Jones', 'Accounting', 45000, 0.5), ('Adams', 'Accounting', 50000, 0.5833333333), ('Brown', 'Sales', 53000, 0.6666666667), ('Smith', 'Sales', 55000, 0.75), ('Wilkinson', 'IT', 60000, 0.8333333333), ('Johnson', 'Management', 80000, 0.9166666667), ('Miller', 'Management', 100000, 1), ], lambda row: (row.name, row.department, row.salary, round(row.cume_dist, 10))) def test_nthvalue(self): qs = Employee.objects.annotate( nth_value=Window(expression=NthValue( expression='salary', nth=2), order_by=[F('hire_date').asc(), F('name').desc()], partition_by=F('department'), ) ).order_by('department', 'hire_date', 'name') self.assertQuerysetEqual(qs, [ ('Jones', 'Accounting', datetime.date(2005, 11, 1), 45000, None), ('Jenson', 'Accounting', datetime.date(2008, 4, 1), 45000, 45000), ('Williams', 'Accounting', datetime.date(2009, 6, 1), 37000, 45000), ('Adams', 'Accounting', datetime.date(2013, 7, 1), 50000, 45000), ('Wilkinson', 'IT', datetime.date(2011, 3, 1), 60000, None), ('Moore', 'IT', datetime.date(2013, 8, 1), 34000, 34000), ('Miller', 'Management', datetime.date(2005, 6, 1), 100000, None), ('Johnson', 'Management', datetime.date(2005, 7, 1), 80000, 80000), ('Smith', 'Marketing', datetime.date(2009, 10, 1), 38000, None), ('Johnson', 'Marketing', datetime.date(2012, 3, 1), 40000, 40000), ('Smith', 'Sales', datetime.date(2007, 6, 1), 55000, None), ('Brown', 'Sales', datetime.date(2009, 9, 1), 53000, 53000), ], lambda row: (row.name, row.department, row.hire_date, row.salary, row.nth_value)) def test_lead(self): """ Determine what the next person hired in the same department makes. Because the dataset is ambiguous, the name is also part of the ordering clause. No default is provided, so None/NULL should be returned. """ qs = Employee.objects.annotate(lead=Window( expression=Lead(expression='salary'), order_by=[F('hire_date').asc(), F('name').desc()], partition_by='department', )).order_by('department', F('hire_date').asc(), F('name').desc()) self.assertQuerysetEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 45000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 37000), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 50000), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), None), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 34000), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), None), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 80000), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), None), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 40000), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), None), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 53000), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), None), ], transform=lambda row: (row.name, row.salary, row.department, row.hire_date, row.lead)) def test_lead_offset(self): """ Determine what the person hired after someone makes. Due to ambiguity, the name is also included in the ordering. """ qs = Employee.objects.annotate(lead=Window( expression=Lead('salary', offset=2), partition_by='department', order_by=F('hire_date').asc(), )) self.assertQuerysetEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 37000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 50000), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), None), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), None), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), None), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), None), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), None), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), None), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), None), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), None), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), None), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), None), ], transform=lambda row: (row.name, row.salary, row.department, row.hire_date, row.lead), ordered=False ) @skipUnlessDBFeature('supports_default_in_lead_lag') def test_lead_default(self): qs = Employee.objects.annotate(lead_default=Window( expression=Lead(expression='salary', offset=5, default=60000), partition_by=F('department'), order_by=F('department').asc(), )) self.assertEqual(list(qs.values_list('lead_default', flat=True).distinct()), [60000]) def test_ntile(self): """ Compute the group for each of the employees across the entire company, based on how high the salary is for them. There are twelve employees so it divides evenly into four groups. """ qs = Employee.objects.annotate(ntile=Window( expression=Ntile(num_buckets=4), order_by=F('salary').desc(), )).order_by('ntile', '-salary', 'name') self.assertQuerysetEqual(qs, [ ('Miller', 'Management', 100000, 1), ('Johnson', 'Management', 80000, 1), ('Wilkinson', 'IT', 60000, 1), ('Smith', 'Sales', 55000, 2), ('Brown', 'Sales', 53000, 2), ('Adams', 'Accounting', 50000, 2), ('Jenson', 'Accounting', 45000, 3), ('Jones', 'Accounting', 45000, 3), ('Johnson', 'Marketing', 40000, 3), ('Smith', 'Marketing', 38000, 4), ('Williams', 'Accounting', 37000, 4), ('Moore', 'IT', 34000, 4), ], lambda x: (x.name, x.department, x.salary, x.ntile)) def test_percent_rank(self): """ Calculate the percentage rank of the employees across the entire company based on salary and name (in case of ambiguity). """ qs = Employee.objects.annotate(percent_rank=Window( expression=PercentRank(), order_by=[F('salary').asc(), F('name').asc()], )).order_by('percent_rank') # Round to account for precision differences among databases. self.assertQuerysetEqual(qs, [ ('Moore', 'IT', 34000, 0.0), ('Williams', 'Accounting', 37000, 0.0909090909), ('Smith', 'Marketing', 38000, 0.1818181818), ('Johnson', 'Marketing', 40000, 0.2727272727), ('Jenson', 'Accounting', 45000, 0.3636363636), ('Jones', 'Accounting', 45000, 0.4545454545), ('Adams', 'Accounting', 50000, 0.5454545455), ('Brown', 'Sales', 53000, 0.6363636364), ('Smith', 'Sales', 55000, 0.7272727273), ('Wilkinson', 'IT', 60000, 0.8181818182), ('Johnson', 'Management', 80000, 0.9090909091), ('Miller', 'Management', 100000, 1.0), ], transform=lambda row: (row.name, row.department, row.salary, round(row.percent_rank, 10))) def test_nth_returns_null(self): """ Find the nth row of the data set. None is returned since there are fewer than 20 rows in the test data. """ qs = Employee.objects.annotate(nth_value=Window( expression=NthValue('salary', nth=20), order_by=F('salary').asc() )) self.assertEqual(list(qs.values_list('nth_value', flat=True).distinct()), [None]) def test_multiple_partitioning(self): """ Find the maximum salary for each department for people hired in the same year. """ qs = Employee.objects.annotate(max=Window( expression=Max('salary'), partition_by=[F('department'), ExtractYear(F('hire_date'))], )).order_by('department', 'hire_date', 'name') self.assertQuerysetEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 45000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 45000), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 37000), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), 50000), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 60000), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), 34000), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 100000), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), 100000), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 38000), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), 40000), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 55000), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), 53000), ], transform=lambda row: (row.name, row.salary, row.department, row.hire_date, row.max)) def test_multiple_ordering(self): """ Accumulate the salaries over the departments based on hire_date. If two people were hired on the same date in the same department, the ordering clause will render a different result for those people. """ qs = Employee.objects.annotate(sum=Window( expression=Sum('salary'), partition_by='department', order_by=[F('hire_date').asc(), F('name').asc()], )).order_by('department', 'sum') self.assertQuerysetEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 45000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 90000), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 127000), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), 177000), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 60000), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), 94000), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 100000), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), 180000), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 38000), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), 78000), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 55000), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), 108000), ], transform=lambda row: (row.name, row.salary, row.department, row.hire_date, row.sum)) @skipUnlessDBFeature('supports_frame_range_fixed_distance') def test_range_n_preceding_and_following(self): qs = Employee.objects.annotate(sum=Window( expression=Sum('salary'), order_by=F('salary').asc(), partition_by='department', frame=ValueRange(start=-2, end=2), )) self.assertIn('RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING', str(qs.query)) self.assertQuerysetEqual(qs, [ ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 37000), ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 90000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 90000), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), 50000), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), 53000), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 55000), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), 40000), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 38000), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 60000), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), 34000), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 100000), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), 80000), ], transform=lambda row: (row.name, row.salary, row.department, row.hire_date, row.sum), ordered=False) def test_range_unbound(self): """A query with RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.""" qs = Employee.objects.annotate(sum=Window( expression=Sum('salary'), partition_by='age', order_by=[F('age').asc()], frame=ValueRange(start=None, end=None), )).order_by('department', 'hire_date', 'name') self.assertIn('RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING', str(qs.query)) self.assertQuerysetEqual(qs, [ ('Jones', 'Accounting', 45000, datetime.date(2005, 11, 1), 165000), ('Jenson', 'Accounting', 45000, datetime.date(2008, 4, 1), 165000), ('Williams', 'Accounting', 37000, datetime.date(2009, 6, 1), 165000), ('Adams', 'Accounting', 50000, datetime.date(2013, 7, 1), 130000), ('Wilkinson', 'IT', 60000, datetime.date(2011, 3, 1), 194000), ('Moore', 'IT', 34000, datetime.date(2013, 8, 1), 194000), ('Miller', 'Management', 100000, datetime.date(2005, 6, 1), 194000), ('Johnson', 'Management', 80000, datetime.date(2005, 7, 1), 130000), ('Smith', 'Marketing', 38000, datetime.date(2009, 10, 1), 165000), ('Johnson', 'Marketing', 40000, datetime.date(2012, 3, 1), 148000), ('Smith', 'Sales', 55000, datetime.date(2007, 6, 1), 148000), ('Brown', 'Sales', 53000, datetime.date(2009, 9, 1), 148000) ], transform=lambda row: (row.name, row.department, row.salary, row.hire_date, row.sum)) @skipIf( connection.vendor == 'sqlite' and connection.Database.sqlite_version_info < (3, 27), 'Nondeterministic failure on SQLite < 3.27.' ) def test_subquery_row_range_rank(self): qs = Employee.objects.annotate( highest_avg_salary_date=Subquery( Employee.objects.filter( department=OuterRef('department'), ).annotate( avg_salary=Window( expression=Avg('salary'), order_by=[F('hire_date').asc()], frame=RowRange(start=-1, end=1), ), ).order_by('-avg_salary', 'hire_date').values('hire_date')[:1], ), ).order_by('department', 'name') self.assertQuerysetEqual(qs, [ ('Adams', 'Accounting', datetime.date(2005, 11, 1)), ('Jenson', 'Accounting', datetime.date(2005, 11, 1)), ('Jones', 'Accounting', datetime.date(2005, 11, 1)), ('Williams', 'Accounting', datetime.date(2005, 11, 1)), ('Moore', 'IT', datetime.date(2011, 3, 1)), ('Wilkinson', 'IT', datetime.date(2011, 3, 1)), ('Johnson', 'Management', datetime.date(2005, 6, 1)), ('Miller', 'Management', datetime.date(2005, 6, 1)), ('Johnson', 'Marketing', datetime.date(2009, 10, 1)), ('Smith', 'Marketing', datetime.date(2009, 10, 1)), ('Brown', 'Sales', datetime.date(2007, 6, 1)), ('Smith', 'Sales', datetime.date(2007, 6, 1)), ], transform=lambda row: (row.name, row.department, row.highest_avg_salary_date)) def test_row_range_rank(self): """ A query with ROWS BETWEEN UNBOUNDED PRECEDING AND 3 FOLLOWING. The resulting sum is the sum of the three next (if they exist) and all previous rows according to the ordering clause. """ qs = Employee.objects.annotate(sum=Window( expression=Sum('salary'), order_by=[F('hire_date').asc(), F('name').desc()], frame=RowRange(start=None, end=3), )).order_by('sum', 'hire_date') self.assertIn('ROWS BETWEEN UNBOUNDED PRECEDING AND 3 FOLLOWING', str(qs.query)) self.assertQuerysetEqual(qs, [ ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 280000), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), 325000), ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 362000), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 415000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 453000), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 513000), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), 553000), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 603000), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 637000), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), 637000), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), 637000), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), 637000), ], transform=lambda row: (row.name, row.salary, row.department, row.hire_date, row.sum)) @skipUnlessDBFeature('can_distinct_on_fields') def test_distinct_window_function(self): """ Window functions are not aggregates, and hence a query to filter out duplicates may be useful. """ qs = Employee.objects.annotate( sum=Window( expression=Sum('salary'), partition_by=ExtractYear('hire_date'), order_by=ExtractYear('hire_date') ), year=ExtractYear('hire_date'), ).values('year', 'sum').distinct('year').order_by('year') results = [ {'year': 2005, 'sum': 225000}, {'year': 2007, 'sum': 55000}, {'year': 2008, 'sum': 45000}, {'year': 2009, 'sum': 128000}, {'year': 2011, 'sum': 60000}, {'year': 2012, 'sum': 40000}, {'year': 2013, 'sum': 84000}, ] for idx, val in zip(range(len(results)), results): with self.subTest(result=val): self.assertEqual(qs[idx], val) def test_fail_update(self): """Window expressions can't be used in an UPDATE statement.""" msg = ( 'Window expressions are not allowed in this query (salary=<Window: ' 'Max(Col(expressions_window_employee, expressions_window.Employee.salary)) ' 'OVER (PARTITION BY Col(expressions_window_employee, ' 'expressions_window.Employee.department))>).' ) with self.assertRaisesMessage(FieldError, msg): Employee.objects.filter(department='Management').update( salary=Window(expression=Max('salary'), partition_by='department'), ) def test_fail_insert(self): """Window expressions can't be used in an INSERT statement.""" msg = ( 'Window expressions are not allowed in this query (salary=<Window: ' 'Sum(Value(10000), order_by=OrderBy(F(pk), descending=False)) OVER ()' ) with self.assertRaisesMessage(FieldError, msg): Employee.objects.create( name='Jameson', department='Management', hire_date=datetime.date(2007, 7, 1), salary=Window(expression=Sum(Value(10000), order_by=F('pk').asc())), ) def test_window_expression_within_subquery(self): subquery_qs = Employee.objects.annotate( highest=Window(FirstValue('id'), partition_by=F('department'), order_by=F('salary').desc()) ).values('highest') highest_salary = Employee.objects.filter(pk__in=subquery_qs) self.assertSequenceEqual(highest_salary.values('department', 'salary'), [ {'department': 'Accounting', 'salary': 50000}, {'department': 'Sales', 'salary': 55000}, {'department': 'Marketing', 'salary': 40000}, {'department': 'IT', 'salary': 60000}, {'department': 'Management', 'salary': 100000} ]) def test_invalid_start_value_range(self): msg = "start argument must be a negative integer, zero, or None, but got '3'." with self.assertRaisesMessage(ValueError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), order_by=F('hire_date').asc(), frame=ValueRange(start=3), ))) def test_invalid_end_value_range(self): msg = "end argument must be a positive integer, zero, or None, but got '-3'." with self.assertRaisesMessage(ValueError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), order_by=F('hire_date').asc(), frame=ValueRange(end=-3), ))) def test_invalid_type_end_value_range(self): msg = "end argument must be a positive integer, zero, or None, but got 'a'." with self.assertRaisesMessage(ValueError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), order_by=F('hire_date').asc(), frame=ValueRange(end='a'), ))) def test_invalid_type_start_value_range(self): msg = "start argument must be a negative integer, zero, or None, but got 'a'." with self.assertRaisesMessage(ValueError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), frame=ValueRange(start='a'), ))) def test_invalid_type_end_row_range(self): msg = "end argument must be a positive integer, zero, or None, but got 'a'." with self.assertRaisesMessage(ValueError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), frame=RowRange(end='a'), ))) @skipUnless(connection.vendor == 'postgresql', 'Frame construction not allowed on PostgreSQL') def test_postgresql_illegal_range_frame_start(self): msg = 'PostgreSQL only supports UNBOUNDED together with PRECEDING and FOLLOWING.' with self.assertRaisesMessage(NotSupportedError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), order_by=F('hire_date').asc(), frame=ValueRange(start=-1), ))) @skipUnless(connection.vendor == 'postgresql', 'Frame construction not allowed on PostgreSQL') def test_postgresql_illegal_range_frame_end(self): msg = 'PostgreSQL only supports UNBOUNDED together with PRECEDING and FOLLOWING.' with self.assertRaisesMessage(NotSupportedError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), order_by=F('hire_date').asc(), frame=ValueRange(end=1), ))) def test_invalid_type_start_row_range(self): msg = "start argument must be a negative integer, zero, or None, but got 'a'." with self.assertRaisesMessage(ValueError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), order_by=F('hire_date').asc(), frame=RowRange(start='a'), ))) class WindowUnsupportedTests(TestCase): def test_unsupported_backend(self): msg = 'This backend does not support window expressions.' with mock.patch.object(connection.features, 'supports_over_clause', False): with self.assertRaisesMessage(NotSupportedError, msg): Employee.objects.annotate(dense_rank=Window(expression=DenseRank())).get() class NonQueryWindowTests(SimpleTestCase): def test_window_repr(self): self.assertEqual( repr(Window(expression=Sum('salary'), partition_by='department')), '<Window: Sum(F(salary)) OVER (PARTITION BY F(department))>' ) self.assertEqual( repr(Window(expression=Avg('salary'), order_by=F('department').asc())), '<Window: Avg(F(salary)) OVER (ORDER BY OrderBy(F(department), descending=False))>' ) def test_window_frame_repr(self): self.assertEqual( repr(RowRange(start=-1)), '<RowRange: ROWS BETWEEN 1 PRECEDING AND UNBOUNDED FOLLOWING>' ) self.assertEqual( repr(ValueRange(start=None, end=1)), '<ValueRange: RANGE BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING>' ) self.assertEqual( repr(ValueRange(start=0, end=0)), '<ValueRange: RANGE BETWEEN CURRENT ROW AND CURRENT ROW>' ) self.assertEqual( repr(RowRange(start=0, end=0)), '<RowRange: ROWS BETWEEN CURRENT ROW AND CURRENT ROW>' ) def test_empty_group_by_cols(self): window = Window(expression=Sum('pk')) self.assertEqual(window.get_group_by_cols(), []) self.assertFalse(window.contains_aggregate) def test_frame_empty_group_by_cols(self): frame = WindowFrame() self.assertEqual(frame.get_group_by_cols(), []) def test_frame_window_frame_notimplemented(self): frame = WindowFrame() msg = 'Subclasses must implement window_frame_start_end().' with self.assertRaisesMessage(NotImplementedError, msg): frame.window_frame_start_end(None, None, None) def test_invalid_filter(self): msg = 'Window is disallowed in the filter clause' qs = Employee.objects.annotate(dense_rank=Window(expression=DenseRank())) with self.assertRaisesMessage(NotSupportedError, msg): qs.filter(dense_rank__gte=1) with self.assertRaisesMessage(NotSupportedError, msg): qs.annotate(inc_rank=F('dense_rank') + Value(1)).filter(inc_rank__gte=1) with self.assertRaisesMessage(NotSupportedError, msg): qs.filter(id=F('dense_rank')) with self.assertRaisesMessage(NotSupportedError, msg): qs.filter(id=Func('dense_rank', 2, function='div')) with self.assertRaisesMessage(NotSupportedError, msg): qs.annotate(total=Sum('dense_rank', filter=Q(name='Jones'))).filter(total=1) def test_invalid_order_by(self): msg = 'order_by must be either an Expression or a sequence of expressions' with self.assertRaisesMessage(ValueError, msg): Window(expression=Sum('power'), order_by='-horse') def test_invalid_source_expression(self): msg = "Expression 'Upper' isn't compatible with OVER clauses." with self.assertRaisesMessage(ValueError, msg): Window(expression=Upper('name'))
aff454076ec1ab9be243ad18576e519d839f8fbb0d7fa81a2b51bd2825d7e9b5
from datetime import datetime from operator import attrgetter from django.core.exceptions import FieldError from django.db.models import ( CharField, DateTimeField, F, Max, OuterRef, Subquery, Value, ) from django.db.models.functions import Upper from django.test import TestCase from .models import Article, Author, ChildArticle, OrderedByFArticle, Reference class OrderingTests(TestCase): @classmethod def setUpTestData(cls): cls.a1 = Article.objects.create(headline="Article 1", pub_date=datetime(2005, 7, 26)) cls.a2 = Article.objects.create(headline="Article 2", pub_date=datetime(2005, 7, 27)) cls.a3 = Article.objects.create(headline="Article 3", pub_date=datetime(2005, 7, 27)) cls.a4 = Article.objects.create(headline="Article 4", pub_date=datetime(2005, 7, 28)) cls.author_1 = Author.objects.create(name="Name 1") cls.author_2 = Author.objects.create(name="Name 2") for i in range(2): Author.objects.create() def test_default_ordering(self): """ By default, Article.objects.all() orders by pub_date descending, then headline ascending. """ self.assertQuerysetEqual( Article.objects.all(), [ "Article 4", "Article 2", "Article 3", "Article 1", ], attrgetter("headline") ) # Getting a single item should work too: self.assertEqual(Article.objects.all()[0], self.a4) def test_default_ordering_override(self): """ Override ordering with order_by, which is in the same format as the ordering attribute in models. """ self.assertQuerysetEqual( Article.objects.order_by("headline"), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.order_by("pub_date", "-headline"), [ "Article 1", "Article 3", "Article 2", "Article 4", ], attrgetter("headline") ) def test_order_by_override(self): """ Only the last order_by has any effect (since they each override any previous ordering). """ self.assertQuerysetEqual( Article.objects.order_by("id"), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.order_by("id").order_by("-headline"), [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline") ) def test_order_by_nulls_first_and_last(self): msg = "nulls_first and nulls_last are mutually exclusive" with self.assertRaisesMessage(ValueError, msg): Article.objects.order_by(F("author").desc(nulls_last=True, nulls_first=True)) def assertQuerysetEqualReversible(self, queryset, sequence): self.assertSequenceEqual(queryset, sequence) self.assertSequenceEqual(queryset.reverse(), list(reversed(sequence))) def test_order_by_nulls_last(self): Article.objects.filter(headline="Article 3").update(author=self.author_1) Article.objects.filter(headline="Article 4").update(author=self.author_2) # asc and desc are chainable with nulls_last. self.assertQuerysetEqualReversible( Article.objects.order_by(F("author").desc(nulls_last=True), 'headline'), [self.a4, self.a3, self.a1, self.a2], ) self.assertQuerysetEqualReversible( Article.objects.order_by(F("author").asc(nulls_last=True), 'headline'), [self.a3, self.a4, self.a1, self.a2], ) self.assertQuerysetEqualReversible( Article.objects.order_by(Upper("author__name").desc(nulls_last=True), 'headline'), [self.a4, self.a3, self.a1, self.a2], ) self.assertQuerysetEqualReversible( Article.objects.order_by(Upper("author__name").asc(nulls_last=True), 'headline'), [self.a3, self.a4, self.a1, self.a2], ) def test_order_by_nulls_first(self): Article.objects.filter(headline="Article 3").update(author=self.author_1) Article.objects.filter(headline="Article 4").update(author=self.author_2) # asc and desc are chainable with nulls_first. self.assertQuerysetEqualReversible( Article.objects.order_by(F("author").asc(nulls_first=True), 'headline'), [self.a1, self.a2, self.a3, self.a4], ) self.assertQuerysetEqualReversible( Article.objects.order_by(F("author").desc(nulls_first=True), 'headline'), [self.a1, self.a2, self.a4, self.a3], ) self.assertQuerysetEqualReversible( Article.objects.order_by(Upper("author__name").asc(nulls_first=True), 'headline'), [self.a1, self.a2, self.a3, self.a4], ) self.assertQuerysetEqualReversible( Article.objects.order_by(Upper("author__name").desc(nulls_first=True), 'headline'), [self.a1, self.a2, self.a4, self.a3], ) def test_orders_nulls_first_on_filtered_subquery(self): Article.objects.filter(headline='Article 1').update(author=self.author_1) Article.objects.filter(headline='Article 2').update(author=self.author_1) Article.objects.filter(headline='Article 4').update(author=self.author_2) Author.objects.filter(name__isnull=True).delete() author_3 = Author.objects.create(name='Name 3') article_subquery = Article.objects.filter( author=OuterRef('pk'), headline__icontains='Article', ).order_by().values('author').annotate( last_date=Max('pub_date'), ).values('last_date') self.assertQuerysetEqualReversible( Author.objects.annotate( last_date=Subquery(article_subquery, output_field=DateTimeField()) ).order_by( F('last_date').asc(nulls_first=True) ).distinct(), [author_3, self.author_1, self.author_2], ) def test_stop_slicing(self): """ Use the 'stop' part of slicing notation to limit the results. """ self.assertQuerysetEqual( Article.objects.order_by("headline")[:2], [ "Article 1", "Article 2", ], attrgetter("headline") ) def test_stop_start_slicing(self): """ Use the 'stop' and 'start' parts of slicing notation to offset the result list. """ self.assertQuerysetEqual( Article.objects.order_by("headline")[1:3], [ "Article 2", "Article 3", ], attrgetter("headline") ) def test_random_ordering(self): """ Use '?' to order randomly. """ self.assertEqual( len(list(Article.objects.order_by("?"))), 4 ) def test_reversed_ordering(self): """ Ordering can be reversed using the reverse() method on a queryset. This allows you to extract things like "the last two items" (reverse and then take the first two). """ self.assertQuerysetEqual( Article.objects.all().reverse()[:2], [ "Article 1", "Article 3", ], attrgetter("headline") ) def test_reverse_ordering_pure(self): qs1 = Article.objects.order_by(F('headline').asc()) qs2 = qs1.reverse() self.assertQuerysetEqual( qs2, [ 'Article 4', 'Article 3', 'Article 2', 'Article 1', ], attrgetter('headline'), ) self.assertQuerysetEqual( qs1, [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) def test_reverse_meta_ordering_pure(self): Article.objects.create( headline='Article 5', pub_date=datetime(2005, 7, 30), author=self.author_1, second_author=self.author_2, ) Article.objects.create( headline='Article 5', pub_date=datetime(2005, 7, 30), author=self.author_2, second_author=self.author_1, ) self.assertQuerysetEqual( Article.objects.filter(headline='Article 5').reverse(), ['Name 2', 'Name 1'], attrgetter('author.name'), ) self.assertQuerysetEqual( Article.objects.filter(headline='Article 5'), ['Name 1', 'Name 2'], attrgetter('author.name'), ) def test_no_reordering_after_slicing(self): msg = 'Cannot reverse a query once a slice has been taken.' qs = Article.objects.all()[0:2] with self.assertRaisesMessage(TypeError, msg): qs.reverse() with self.assertRaisesMessage(TypeError, msg): qs.last() def test_extra_ordering(self): """ Ordering can be based on fields included from an 'extra' clause """ self.assertQuerysetEqual( Article.objects.extra(select={"foo": "pub_date"}, order_by=["foo", "headline"]), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) def test_extra_ordering_quoting(self): """ If the extra clause uses an SQL keyword for a name, it will be protected by quoting. """ self.assertQuerysetEqual( Article.objects.extra(select={"order": "pub_date"}, order_by=["order", "headline"]), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) def test_extra_ordering_with_table_name(self): self.assertQuerysetEqual( Article.objects.extra(order_by=['ordering_article.headline']), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.extra(order_by=['-ordering_article.headline']), [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline") ) def test_order_by_pk(self): """ 'pk' works as an ordering option in Meta. """ self.assertQuerysetEqual( Author.objects.all(), list(reversed(range(1, Author.objects.count() + 1))), attrgetter("pk"), ) def test_order_by_fk_attname(self): """ ordering by a foreign key by its attribute name prevents the query from inheriting its related model ordering option (#19195). """ for i in range(1, 5): author = Author.objects.get(pk=i) article = getattr(self, "a%d" % (5 - i)) article.author = author article.save(update_fields={'author'}) self.assertQuerysetEqual( Article.objects.order_by('author_id'), [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline") ) def test_order_by_f_expression(self): self.assertQuerysetEqual( Article.objects.order_by(F('headline')), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.order_by(F('headline').asc()), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.order_by(F('headline').desc()), [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline") ) def test_order_by_f_expression_duplicates(self): """ A column may only be included once (the first occurrence) so we check to ensure there are no duplicates by inspecting the SQL. """ qs = Article.objects.order_by(F('headline').asc(), F('headline').desc()) sql = str(qs.query).upper() fragment = sql[sql.find('ORDER BY'):] self.assertEqual(fragment.count('HEADLINE'), 1) self.assertQuerysetEqual( qs, [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) qs = Article.objects.order_by(F('headline').desc(), F('headline').asc()) sql = str(qs.query).upper() fragment = sql[sql.find('ORDER BY'):] self.assertEqual(fragment.count('HEADLINE'), 1) self.assertQuerysetEqual( qs, [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline") ) def test_order_by_constant_value(self): # Order by annotated constant from selected columns. qs = Article.objects.annotate( constant=Value('1', output_field=CharField()), ).order_by('constant', '-headline') self.assertSequenceEqual(qs, [self.a4, self.a3, self.a2, self.a1]) # Order by annotated constant which is out of selected columns. self.assertSequenceEqual( qs.values_list('headline', flat=True), [ 'Article 4', 'Article 3', 'Article 2', 'Article 1', ], ) # Order by constant. qs = Article.objects.order_by(Value('1', output_field=CharField()), '-headline') self.assertSequenceEqual(qs, [self.a4, self.a3, self.a2, self.a1]) def test_order_by_constant_value_without_output_field(self): msg = 'Cannot resolve expression type, unknown output_field' qs = Article.objects.annotate(constant=Value('1')).order_by('constant') for ordered_qs in ( qs, qs.values('headline'), Article.objects.order_by(Value('1')), ): with self.subTest(ordered_qs=ordered_qs), self.assertRaisesMessage(FieldError, msg): ordered_qs.first() def test_related_ordering_duplicate_table_reference(self): """ An ordering referencing a model with an ordering referencing a model multiple time no circular reference should be detected (#24654). """ first_author = Author.objects.create() second_author = Author.objects.create() self.a1.author = first_author self.a1.second_author = second_author self.a1.save() self.a2.author = second_author self.a2.second_author = first_author self.a2.save() r1 = Reference.objects.create(article_id=self.a1.pk) r2 = Reference.objects.create(article_id=self.a2.pk) self.assertSequenceEqual(Reference.objects.all(), [r2, r1]) def test_default_ordering_by_f_expression(self): """F expressions can be used in Meta.ordering.""" articles = OrderedByFArticle.objects.all() articles.filter(headline='Article 2').update(author=self.author_2) articles.filter(headline='Article 3').update(author=self.author_1) self.assertQuerysetEqual( articles, ['Article 1', 'Article 4', 'Article 3', 'Article 2'], attrgetter('headline') ) def test_order_by_ptr_field_with_default_ordering_by_expression(self): ca1 = ChildArticle.objects.create( headline='h2', pub_date=datetime(2005, 7, 27), author=self.author_2, ) ca2 = ChildArticle.objects.create( headline='h2', pub_date=datetime(2005, 7, 27), author=self.author_1, ) ca3 = ChildArticle.objects.create( headline='h3', pub_date=datetime(2005, 7, 27), author=self.author_1, ) ca4 = ChildArticle.objects.create(headline='h1', pub_date=datetime(2005, 7, 28)) articles = ChildArticle.objects.order_by('article_ptr') self.assertSequenceEqual(articles, [ca4, ca2, ca1, ca3])
57d3cb42eea7b1f280787919579ce4a2e0ae2665e3fcec632d46ce77f15403b2
""" Specifying ordering Specify default ordering for a model using the ``ordering`` attribute, which should be a list or tuple of field names. This tells Django how to order ``QuerySet`` results. If a field name in ``ordering`` starts with a hyphen, that field will be ordered in descending order. Otherwise, it'll be ordered in ascending order. The special-case field name ``"?"`` specifies random order. The ordering attribute is not required. If you leave it off, ordering will be undefined -- not random, just undefined. """ from django.db import models from django.db.models.expressions import OrderBy class Author(models.Model): name = models.CharField(max_length=63, null=True, blank=True) class Meta: ordering = ('-pk',) class Article(models.Model): author = models.ForeignKey(Author, models.SET_NULL, null=True) second_author = models.ForeignKey(Author, models.SET_NULL, null=True, related_name='+') headline = models.CharField(max_length=100) pub_date = models.DateTimeField() class Meta: ordering = ( '-pub_date', models.F('headline'), models.F('author__name').asc(), OrderBy(models.F('second_author__name')), ) def __str__(self): return self.headline class OrderedByAuthorArticle(Article): class Meta: proxy = True ordering = ('author', 'second_author') class OrderedByFArticle(Article): class Meta: proxy = True ordering = (models.F('author').asc(nulls_first=True), 'id') class ChildArticle(Article): pass class Reference(models.Model): article = models.ForeignKey(OrderedByAuthorArticle, models.CASCADE) class Meta: ordering = ('article',)
564296d8c79123c91a37f84df6e75e8b5b7ed28a268ee28182145881a6e04c4d
from django.conf import settings from django.contrib.flatpages.forms import FlatpageForm from django.contrib.flatpages.models import FlatPage from django.contrib.sites.models import Site from django.test import TestCase, modify_settings, override_settings from django.utils import translation @modify_settings(INSTALLED_APPS={'append': ['django.contrib.flatpages']}) @override_settings(SITE_ID=1) class FlatpageAdminFormTests(TestCase): @classmethod def setUpTestData(cls): # don't use the manager because we want to ensure the site exists # with pk=1, regardless of whether or not it already exists. cls.site1 = Site(pk=1, domain='example.com', name='example.com') cls.site1.save() def setUp(self): # Site fields cache needs to be cleared after flatpages is added to # INSTALLED_APPS Site._meta._expire_cache() self.form_data = { 'title': "A test page", 'content': "This is a test", 'sites': [settings.SITE_ID], } def test_flatpage_admin_form_url_validation(self): "The flatpage admin form correctly validates urls" self.assertTrue(FlatpageForm(data=dict(url='/new_flatpage/', **self.form_data)).is_valid()) self.assertTrue(FlatpageForm(data=dict(url='/some.special~chars/', **self.form_data)).is_valid()) self.assertTrue(FlatpageForm(data=dict(url='/some.very_special~chars-here/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a space/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a % char/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a ! char/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a & char/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a ? char/', **self.form_data)).is_valid()) def test_flatpage_requires_leading_slash(self): form = FlatpageForm(data=dict(url='no_leading_slash/', **self.form_data)) with translation.override('en'): self.assertFalse(form.is_valid()) self.assertEqual(form.errors['url'], ["URL is missing a leading slash."]) @override_settings(APPEND_SLASH=True, MIDDLEWARE=['django.middleware.common.CommonMiddleware']) def test_flatpage_requires_trailing_slash_with_append_slash(self): form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data)) with translation.override('en'): self.assertEqual( form.fields['url'].help_text, 'Example: “/about/contact/”. Make sure to have leading and ' 'trailing slashes.' ) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['url'], ["URL is missing a trailing slash."]) @override_settings(APPEND_SLASH=False, MIDDLEWARE=['django.middleware.common.CommonMiddleware']) def test_flatpage_doesnt_requires_trailing_slash_without_append_slash(self): form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data)) self.assertTrue(form.is_valid()) with translation.override('en'): self.assertEqual( form.fields['url'].help_text, 'Example: “/about/contact”. Make sure to have a leading slash.' ) def test_flatpage_admin_form_url_uniqueness_validation(self): "The flatpage admin form correctly enforces url uniqueness among flatpages of the same site" data = dict(url='/myflatpage1/', **self.form_data) FlatpageForm(data=data).save() f = FlatpageForm(data=data) with translation.override('en'): self.assertFalse(f.is_valid()) self.assertEqual( f.errors, {'__all__': ['Flatpage with url /myflatpage1/ already exists for site example.com']}) def test_flatpage_admin_form_edit(self): """ Existing flatpages can be edited in the admin form without triggering the url-uniqueness validation. """ existing = FlatPage.objects.create( url="/myflatpage1/", title="Some page", content="The content") existing.sites.add(settings.SITE_ID) data = dict(url='/myflatpage1/', **self.form_data) f = FlatpageForm(data=data, instance=existing) self.assertTrue(f.is_valid(), f.errors) updated = f.save() self.assertEqual(updated.title, "A test page") def test_flatpage_nosites(self): data = dict(url='/myflatpage1/', **self.form_data) data.update({'sites': ''}) f = FlatpageForm(data=data) self.assertFalse(f.is_valid()) self.assertEqual(f.errors, {'sites': [translation.gettext('This field is required.')]})
1e47f5f36eafe2d2d6e3a87a1b8a306c86ae54cfa2a996ebb167c7648fedcfe1
from datetime import datetime from django.test import TestCase from .models import Article, Reporter, Writer class M2MIntermediaryTests(TestCase): def test_intermediary(self): r1 = Reporter.objects.create(first_name="John", last_name="Smith") r2 = Reporter.objects.create(first_name="Jane", last_name="Doe") a = Article.objects.create( headline="This is a test", pub_date=datetime(2005, 7, 27) ) w1 = Writer.objects.create(reporter=r1, article=a, position="Main writer") w2 = Writer.objects.create(reporter=r2, article=a, position="Contributor") self.assertQuerysetEqual( a.writer_set.select_related().order_by("-position"), [ ("John Smith", "Main writer"), ("Jane Doe", "Contributor"), ], lambda w: (str(w.reporter), w.position) ) self.assertEqual(w1.reporter, r1) self.assertEqual(w2.reporter, r2) self.assertEqual(w1.article, a) self.assertEqual(w2.article, a) self.assertQuerysetEqual( r1.writer_set.all(), [ ("John Smith", "Main writer") ], lambda w: (str(w.reporter), w.position) )
0179329ef40bdf41a77638731ed8ce01c3707143e5a45c00a0809a2124cd8106
import datetime import os from decimal import Decimal from unittest import mock, skipUnless from django import forms from django.core.exceptions import ( NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ) from django.core.files.uploadedfile import SimpleUploadedFile from django.core.validators import ValidationError from django.db import connection, models from django.db.models.query import EmptyQuerySet from django.forms.models import ( ModelFormMetaclass, construct_instance, fields_for_model, model_to_dict, modelform_factory, ) from django.template import Context, Template from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from .models import ( Article, ArticleStatus, Author, Author1, Award, BetterWriter, BigInt, Book, Category, Character, Colour, ColourfulItem, CustomErrorMessage, CustomFF, CustomFieldForExclusionModel, DateTimePost, DerivedBook, DerivedPost, Document, ExplicitPK, FilePathModel, FlexibleDatePost, Homepage, ImprovedArticle, ImprovedArticleWithParentLink, Inventory, NullableUniqueCharFieldModel, Person, Photo, Post, Price, Product, Publication, PublicationDefaults, StrictAssignmentAll, StrictAssignmentFieldSpecific, Student, StumpJoke, TextFile, Triple, Writer, WriterProfile, test_images, ) if test_images: from .models import ImageFile, OptionalImageFile, NoExtensionImageFile class ImageFileForm(forms.ModelForm): class Meta: model = ImageFile fields = '__all__' class OptionalImageFileForm(forms.ModelForm): class Meta: model = OptionalImageFile fields = '__all__' class NoExtensionImageFileForm(forms.ModelForm): class Meta: model = NoExtensionImageFile fields = '__all__' class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' class PriceForm(forms.ModelForm): class Meta: model = Price fields = '__all__' class BookForm(forms.ModelForm): class Meta: model = Book fields = '__all__' class DerivedBookForm(forms.ModelForm): class Meta: model = DerivedBook fields = '__all__' class ExplicitPKForm(forms.ModelForm): class Meta: model = ExplicitPK fields = ('key', 'desc',) class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' class DerivedPostForm(forms.ModelForm): class Meta: model = DerivedPost fields = '__all__' class CustomWriterForm(forms.ModelForm): name = forms.CharField(required=False) class Meta: model = Writer fields = '__all__' class BaseCategoryForm(forms.ModelForm): class Meta: model = Category fields = '__all__' class ArticleForm(forms.ModelForm): class Meta: model = Article fields = '__all__' class RoykoForm(forms.ModelForm): class Meta: model = Writer fields = '__all__' class ArticleStatusForm(forms.ModelForm): class Meta: model = ArticleStatus fields = '__all__' class InventoryForm(forms.ModelForm): class Meta: model = Inventory fields = '__all__' class SelectInventoryForm(forms.Form): items = forms.ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode') class CustomFieldForExclusionForm(forms.ModelForm): class Meta: model = CustomFieldForExclusionModel fields = ['name', 'markup'] class TextFileForm(forms.ModelForm): class Meta: model = TextFile fields = '__all__' class BigIntForm(forms.ModelForm): class Meta: model = BigInt fields = '__all__' class ModelFormWithMedia(forms.ModelForm): class Media: js = ('/some/form/javascript',) css = { 'all': ('/some/form/css',) } class Meta: model = TextFile fields = '__all__' class CustomErrorMessageForm(forms.ModelForm): name1 = forms.CharField(error_messages={'invalid': 'Form custom error message.'}) class Meta: fields = '__all__' model = CustomErrorMessage class ModelFormBaseTest(TestCase): def test_base_form(self): self.assertEqual(list(BaseCategoryForm.base_fields), ['name', 'slug', 'url']) def test_no_model_class(self): class NoModelModelForm(forms.ModelForm): pass with self.assertRaisesMessage(ValueError, 'ModelForm has no model class specified.'): NoModelModelForm() def test_empty_fields_to_fields_for_model(self): """ An argument of fields=() to fields_for_model should return an empty dictionary """ field_dict = fields_for_model(Person, fields=()) self.assertEqual(len(field_dict), 0) def test_empty_fields_on_modelform(self): """ No fields on a ModelForm should actually result in no fields. """ class EmptyPersonForm(forms.ModelForm): class Meta: model = Person fields = () form = EmptyPersonForm() self.assertEqual(len(form.fields), 0) def test_empty_fields_to_construct_instance(self): """ No fields should be set on a model instance if construct_instance receives fields=(). """ form = modelform_factory(Person, fields="__all__")({'name': 'John Doe'}) self.assertTrue(form.is_valid()) instance = construct_instance(form, Person(), fields=()) self.assertEqual(instance.name, '') def test_blank_with_null_foreign_key_field(self): """ #13776 -- ModelForm's with models having a FK set to null=False and required=False should be valid. """ class FormForTestingIsValid(forms.ModelForm): class Meta: model = Student fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['character'].required = False char = Character.objects.create(username='user', last_action=datetime.datetime.today()) data = {'study': 'Engineering'} data2 = {'study': 'Engineering', 'character': char.pk} # form is valid because required=False for field 'character' f1 = FormForTestingIsValid(data) self.assertTrue(f1.is_valid()) f2 = FormForTestingIsValid(data2) self.assertTrue(f2.is_valid()) obj = f2.save() self.assertEqual(obj.character, char) def test_blank_false_with_null_true_foreign_key_field(self): """ A ModelForm with a model having ForeignKey(blank=False, null=True) and the form field set to required=False should allow the field to be unset. """ class AwardForm(forms.ModelForm): class Meta: model = Award fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['character'].required = False character = Character.objects.create(username='user', last_action=datetime.datetime.today()) award = Award.objects.create(name='Best sprinter', character=character) data = {'name': 'Best tester', 'character': ''} # remove character form = AwardForm(data=data, instance=award) self.assertTrue(form.is_valid()) award = form.save() self.assertIsNone(award.character) def test_save_blank_false_with_required_false(self): """ A ModelForm with a model with a field set to blank=False and the form field set to required=False should allow the field to be unset. """ obj = Writer.objects.create(name='test') form = CustomWriterForm(data={'name': ''}, instance=obj) self.assertTrue(form.is_valid()) obj = form.save() self.assertEqual(obj.name, '') def test_save_blank_null_unique_charfield_saves_null(self): form_class = modelform_factory(model=NullableUniqueCharFieldModel, fields=['codename']) empty_value = '' if connection.features.interprets_empty_strings_as_nulls else None form = form_class(data={'codename': ''}) self.assertTrue(form.is_valid()) form.save() self.assertEqual(form.instance.codename, empty_value) # Save a second form to verify there isn't a unique constraint violation. form = form_class(data={'codename': ''}) self.assertTrue(form.is_valid()) form.save() self.assertEqual(form.instance.codename, empty_value) def test_missing_fields_attribute(self): message = ( "Creating a ModelForm without either the 'fields' attribute " "or the 'exclude' attribute is prohibited; form " "MissingFieldsForm needs updating." ) with self.assertRaisesMessage(ImproperlyConfigured, message): class MissingFieldsForm(forms.ModelForm): class Meta: model = Category def test_extra_fields(self): class ExtraFields(BaseCategoryForm): some_extra_field = forms.BooleanField() self.assertEqual(list(ExtraFields.base_fields), ['name', 'slug', 'url', 'some_extra_field']) def test_extra_field_model_form(self): with self.assertRaisesMessage(FieldError, 'no-field'): class ExtraPersonForm(forms.ModelForm): """ ModelForm with an extra field """ age = forms.IntegerField() class Meta: model = Person fields = ('name', 'no-field') def test_extra_declared_field_model_form(self): class ExtraPersonForm(forms.ModelForm): """ ModelForm with an extra field """ age = forms.IntegerField() class Meta: model = Person fields = ('name', 'age') def test_extra_field_modelform_factory(self): with self.assertRaisesMessage(FieldError, 'Unknown field(s) (no-field) specified for Person'): modelform_factory(Person, fields=['no-field', 'name']) def test_replace_field(self): class ReplaceField(forms.ModelForm): url = forms.BooleanField() class Meta: model = Category fields = '__all__' self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField) def test_replace_field_variant_2(self): # Should have the same result as before, # but 'fields' attribute specified differently class ReplaceField(forms.ModelForm): url = forms.BooleanField() class Meta: model = Category fields = ['url'] self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField) def test_replace_field_variant_3(self): # Should have the same result as before, # but 'fields' attribute specified differently class ReplaceField(forms.ModelForm): url = forms.BooleanField() class Meta: model = Category fields = [] # url will still appear, since it is explicit above self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField) def test_override_field(self): class WriterForm(forms.ModelForm): book = forms.CharField(required=False) class Meta: model = Writer fields = '__all__' wf = WriterForm({'name': 'Richard Lockridge'}) self.assertTrue(wf.is_valid()) def test_limit_nonexistent_field(self): expected_msg = 'Unknown field(s) (nonexistent) specified for Category' with self.assertRaisesMessage(FieldError, expected_msg): class InvalidCategoryForm(forms.ModelForm): class Meta: model = Category fields = ['nonexistent'] def test_limit_fields_with_string(self): expected_msg = "CategoryForm.Meta.fields cannot be a string. Did you mean to type: ('url',)?" with self.assertRaisesMessage(TypeError, expected_msg): class CategoryForm(forms.ModelForm): class Meta: model = Category fields = ('url') # note the missing comma def test_exclude_fields(self): class ExcludeFields(forms.ModelForm): class Meta: model = Category exclude = ['url'] self.assertEqual(list(ExcludeFields.base_fields), ['name', 'slug']) def test_exclude_nonexistent_field(self): class ExcludeFields(forms.ModelForm): class Meta: model = Category exclude = ['nonexistent'] self.assertEqual(list(ExcludeFields.base_fields), ['name', 'slug', 'url']) def test_exclude_fields_with_string(self): expected_msg = "CategoryForm.Meta.exclude cannot be a string. Did you mean to type: ('url',)?" with self.assertRaisesMessage(TypeError, expected_msg): class CategoryForm(forms.ModelForm): class Meta: model = Category exclude = ('url') # note the missing comma def test_exclude_and_validation(self): # This Price instance generated by this form is not valid because the quantity # field is required, but the form is valid because the field is excluded from # the form. This is for backwards compatibility. class PriceFormWithoutQuantity(forms.ModelForm): class Meta: model = Price exclude = ('quantity',) form = PriceFormWithoutQuantity({'price': '6.00'}) self.assertTrue(form.is_valid()) price = form.save(commit=False) msg = "{'quantity': ['This field cannot be null.']}" with self.assertRaisesMessage(ValidationError, msg): price.full_clean() # The form should not validate fields that it doesn't contain even if they are # specified using 'fields', not 'exclude'. class PriceFormWithoutQuantity(forms.ModelForm): class Meta: model = Price fields = ('price',) form = PriceFormWithoutQuantity({'price': '6.00'}) self.assertTrue(form.is_valid()) # The form should still have an instance of a model that is not complete and # not saved into a DB yet. self.assertEqual(form.instance.price, Decimal('6.00')) self.assertIsNone(form.instance.quantity) self.assertIsNone(form.instance.pk) def test_confused_form(self): class ConfusedForm(forms.ModelForm): """ Using 'fields' *and* 'exclude'. Not sure why you'd want to do this, but uh, "be liberal in what you accept" and all. """ class Meta: model = Category fields = ['name', 'url'] exclude = ['url'] self.assertEqual(list(ConfusedForm.base_fields), ['name']) def test_mixmodel_form(self): class MixModelForm(BaseCategoryForm): """ Don't allow more than one 'model' definition in the inheritance hierarchy. Technically, it would generate a valid form, but the fact that the resulting save method won't deal with multiple objects is likely to trip up people not familiar with the mechanics. """ class Meta: model = Article fields = '__all__' # MixModelForm is now an Article-related thing, because MixModelForm.Meta # overrides BaseCategoryForm.Meta. self.assertEqual( list(MixModelForm.base_fields), ['headline', 'slug', 'pub_date', 'writer', 'article', 'categories', 'status'] ) def test_article_form(self): self.assertEqual( list(ArticleForm.base_fields), ['headline', 'slug', 'pub_date', 'writer', 'article', 'categories', 'status'] ) def test_bad_form(self): # First class with a Meta class wins... class BadForm(ArticleForm, BaseCategoryForm): pass self.assertEqual( list(BadForm.base_fields), ['headline', 'slug', 'pub_date', 'writer', 'article', 'categories', 'status'] ) def test_invalid_meta_model(self): class InvalidModelForm(forms.ModelForm): class Meta: pass # no model # Can't create new form msg = 'ModelForm has no model class specified.' with self.assertRaisesMessage(ValueError, msg): InvalidModelForm() # Even if you provide a model instance with self.assertRaisesMessage(ValueError, msg): InvalidModelForm(instance=Category) def test_subcategory_form(self): class SubCategoryForm(BaseCategoryForm): """ Subclassing without specifying a Meta on the class will use the parent's Meta (or the first parent in the MRO if there are multiple parent classes). """ pass self.assertEqual(list(SubCategoryForm.base_fields), ['name', 'slug', 'url']) def test_subclassmeta_form(self): class SomeCategoryForm(forms.ModelForm): checkbox = forms.BooleanField() class Meta: model = Category fields = '__all__' class SubclassMeta(SomeCategoryForm): """ We can also subclass the Meta inner class to change the fields list. """ class Meta(SomeCategoryForm.Meta): exclude = ['url'] self.assertHTMLEqual( str(SubclassMeta()), """<tr><th><label for="id_name">Name:</label></th> <td><input id="id_name" type="text" name="name" maxlength="20" required></td></tr> <tr><th><label for="id_slug">Slug:</label></th> <td><input id="id_slug" type="text" name="slug" maxlength="20" required></td></tr> <tr><th><label for="id_checkbox">Checkbox:</label></th> <td><input type="checkbox" name="checkbox" id="id_checkbox" required></td></tr>""" ) def test_orderfields_form(self): class OrderFields(forms.ModelForm): class Meta: model = Category fields = ['url', 'name'] self.assertEqual(list(OrderFields.base_fields), ['url', 'name']) self.assertHTMLEqual( str(OrderFields()), """<tr><th><label for="id_url">The URL:</label></th> <td><input id="id_url" type="text" name="url" maxlength="40" required></td></tr> <tr><th><label for="id_name">Name:</label></th> <td><input id="id_name" type="text" name="name" maxlength="20" required></td></tr>""" ) def test_orderfields2_form(self): class OrderFields2(forms.ModelForm): class Meta: model = Category fields = ['slug', 'url', 'name'] exclude = ['url'] self.assertEqual(list(OrderFields2.base_fields), ['slug', 'name']) def test_default_populated_on_optional_field(self): class PubForm(forms.ModelForm): mode = forms.CharField(max_length=255, required=False) class Meta: model = PublicationDefaults fields = ('mode',) # Empty data uses the model field default. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, 'di') self.assertEqual(m1._meta.get_field('mode').get_default(), 'di') # Blank data doesn't use the model field default. mf2 = PubForm({'mode': ''}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.mode, '') def test_default_not_populated_on_non_empty_value_in_cleaned_data(self): class PubForm(forms.ModelForm): mode = forms.CharField(max_length=255, required=False) mocked_mode = None def clean(self): self.cleaned_data['mode'] = self.mocked_mode return self.cleaned_data class Meta: model = PublicationDefaults fields = ('mode',) pub_form = PubForm({}) pub_form.mocked_mode = 'de' pub = pub_form.save(commit=False) self.assertEqual(pub.mode, 'de') # Default should be populated on an empty value in cleaned_data. default_mode = 'di' for empty_value in pub_form.fields['mode'].empty_values: with self.subTest(empty_value=empty_value): pub_form = PubForm({}) pub_form.mocked_mode = empty_value pub = pub_form.save(commit=False) self.assertEqual(pub.mode, default_mode) def test_default_not_populated_on_optional_checkbox_input(self): class PubForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ('active',) # Empty data doesn't use the model default because CheckboxInput # doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertIs(m1.active, False) self.assertIsInstance(mf1.fields['active'].widget, forms.CheckboxInput) self.assertIs(m1._meta.get_field('active').get_default(), True) def test_default_not_populated_on_checkboxselectmultiple(self): class PubForm(forms.ModelForm): mode = forms.CharField(required=False, widget=forms.CheckboxSelectMultiple) class Meta: model = PublicationDefaults fields = ('mode',) # Empty data doesn't use the model default because an unchecked # CheckboxSelectMultiple doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, '') self.assertEqual(m1._meta.get_field('mode').get_default(), 'di') def test_default_not_populated_on_selectmultiple(self): class PubForm(forms.ModelForm): mode = forms.CharField(required=False, widget=forms.SelectMultiple) class Meta: model = PublicationDefaults fields = ('mode',) # Empty data doesn't use the model default because an unselected # SelectMultiple doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, '') self.assertEqual(m1._meta.get_field('mode').get_default(), 'di') def test_prefixed_form_with_default_field(self): class PubForm(forms.ModelForm): prefix = 'form-prefix' class Meta: model = PublicationDefaults fields = ('mode',) mode = 'de' self.assertNotEqual(mode, PublicationDefaults._meta.get_field('mode').get_default()) mf1 = PubForm({'form-prefix-mode': mode}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, mode) def test_renderer_kwarg(self): custom = object() self.assertIs(ProductForm(renderer=custom).renderer, custom) def test_default_splitdatetime_field(self): class PubForm(forms.ModelForm): datetime_published = forms.SplitDateTimeField(required=False) class Meta: model = PublicationDefaults fields = ('datetime_published',) mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.datetime_published, datetime.datetime(2000, 1, 1)) mf2 = PubForm({'datetime_published_0': '2010-01-01', 'datetime_published_1': '0:00:00'}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.datetime_published, datetime.datetime(2010, 1, 1)) def test_default_filefield(self): class PubForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ('file',) mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.file.name, 'default.txt') mf2 = PubForm({}, {'file': SimpleUploadedFile('name', b'foo')}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.file.name, 'name') def test_default_selectdatewidget(self): class PubForm(forms.ModelForm): date_published = forms.DateField(required=False, widget=forms.SelectDateWidget) class Meta: model = PublicationDefaults fields = ('date_published',) mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.date_published, datetime.date.today()) mf2 = PubForm({'date_published_year': '2010', 'date_published_month': '1', 'date_published_day': '1'}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.date_published, datetime.date(2010, 1, 1)) class FieldOverridesByFormMetaForm(forms.ModelForm): class Meta: model = Category fields = ['name', 'url', 'slug'] widgets = { 'name': forms.Textarea, 'url': forms.TextInput(attrs={'class': 'url'}) } labels = { 'name': 'Title', } help_texts = { 'slug': 'Watch out! Letters, numbers, underscores and hyphens only.', } error_messages = { 'slug': { 'invalid': ( "Didn't you read the help text? " "We said letters, numbers, underscores and hyphens only!" ) } } field_classes = { 'url': forms.URLField, } class TestFieldOverridesByFormMeta(SimpleTestCase): def test_widget_overrides(self): form = FieldOverridesByFormMetaForm() self.assertHTMLEqual( str(form['name']), '<textarea id="id_name" rows="10" cols="40" name="name" maxlength="20" required></textarea>', ) self.assertHTMLEqual( str(form['url']), '<input id="id_url" type="text" class="url" name="url" maxlength="40" required>', ) self.assertHTMLEqual( str(form['slug']), '<input id="id_slug" type="text" name="slug" maxlength="20" required>', ) def test_label_overrides(self): form = FieldOverridesByFormMetaForm() self.assertHTMLEqual( str(form['name'].label_tag()), '<label for="id_name">Title:</label>', ) self.assertHTMLEqual( str(form['url'].label_tag()), '<label for="id_url">The URL:</label>', ) self.assertHTMLEqual( str(form['slug'].label_tag()), '<label for="id_slug">Slug:</label>', ) def test_help_text_overrides(self): form = FieldOverridesByFormMetaForm() self.assertEqual( form['slug'].help_text, 'Watch out! Letters, numbers, underscores and hyphens only.', ) def test_error_messages_overrides(self): form = FieldOverridesByFormMetaForm(data={ 'name': 'Category', 'url': 'http://www.example.com/category/', 'slug': '!%#*@', }) form.full_clean() error = [ "Didn't you read the help text? " "We said letters, numbers, underscores and hyphens only!", ] self.assertEqual(form.errors, {'slug': error}) def test_field_type_overrides(self): form = FieldOverridesByFormMetaForm() self.assertIs(Category._meta.get_field('url').__class__, models.CharField) self.assertIsInstance(form.fields['url'], forms.URLField) class IncompleteCategoryFormWithFields(forms.ModelForm): """ A form that replaces the model's url field with a custom one. This should prevent the model field's validation from being called. """ url = forms.CharField(required=False) class Meta: fields = ('name', 'slug') model = Category class IncompleteCategoryFormWithExclude(forms.ModelForm): """ A form that replaces the model's url field with a custom one. This should prevent the model field's validation from being called. """ url = forms.CharField(required=False) class Meta: exclude = ['url'] model = Category class ValidationTest(SimpleTestCase): def test_validates_with_replaced_field_not_specified(self): form = IncompleteCategoryFormWithFields(data={'name': 'some name', 'slug': 'some-slug'}) assert form.is_valid() def test_validates_with_replaced_field_excluded(self): form = IncompleteCategoryFormWithExclude(data={'name': 'some name', 'slug': 'some-slug'}) assert form.is_valid() def test_notrequired_overrides_notblank(self): form = CustomWriterForm({}) assert form.is_valid() class UniqueTest(TestCase): """ unique/unique_together validation. """ @classmethod def setUpTestData(cls): cls.writer = Writer.objects.create(name='Mike Royko') def test_simple_unique(self): form = ProductForm({'slug': 'teddy-bear-blue'}) self.assertTrue(form.is_valid()) obj = form.save() form = ProductForm({'slug': 'teddy-bear-blue'}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['slug'], ['Product with this Slug already exists.']) form = ProductForm({'slug': 'teddy-bear-blue'}, instance=obj) self.assertTrue(form.is_valid()) def test_unique_together(self): """ModelForm test of unique_together constraint""" form = PriceForm({'price': '6.00', 'quantity': '1'}) self.assertTrue(form.is_valid()) form.save() form = PriceForm({'price': '6.00', 'quantity': '1'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['__all__'], ['Price with this Price and Quantity already exists.']) def test_unique_together_exclusion(self): """ Forms don't validate unique_together constraints when only part of the constraint is included in the form's fields. This allows using form.save(commit=False) and then assigning the missing field(s) to the model instance. """ class BookForm(forms.ModelForm): class Meta: model = DerivedBook fields = ('isbn', 'suffix1') # The unique_together is on suffix1/suffix2 but only suffix1 is part # of the form. The fields must have defaults, otherwise they'll be # skipped by other logic. self.assertEqual(DerivedBook._meta.unique_together, (('suffix1', 'suffix2'),)) for name in ('suffix1', 'suffix2'): with self.subTest(name=name): field = DerivedBook._meta.get_field(name) self.assertEqual(field.default, 0) # The form fails validation with "Derived book with this Suffix1 and # Suffix2 already exists." if the unique_together validation isn't # skipped. DerivedBook.objects.create(isbn='12345') form = BookForm({'isbn': '56789', 'suffix1': '0'}) self.assertTrue(form.is_valid(), form.errors) def test_multiple_field_unique_together(self): """ When the same field is involved in multiple unique_together constraints, we need to make sure we don't remove the data for it before doing all the validation checking (not just failing after the first one). """ class TripleForm(forms.ModelForm): class Meta: model = Triple fields = '__all__' Triple.objects.create(left=1, middle=2, right=3) form = TripleForm({'left': '1', 'middle': '2', 'right': '3'}) self.assertFalse(form.is_valid()) form = TripleForm({'left': '1', 'middle': '3', 'right': '1'}) self.assertTrue(form.is_valid()) @skipUnlessDBFeature('supports_nullable_unique_constraints') def test_unique_null(self): title = 'I May Be Wrong But I Doubt It' form = BookForm({'title': title, 'author': self.writer.pk}) self.assertTrue(form.is_valid()) form.save() form = BookForm({'title': title, 'author': self.writer.pk}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['__all__'], ['Book with this Title and Author already exists.']) form = BookForm({'title': title}) self.assertTrue(form.is_valid()) form.save() form = BookForm({'title': title}) self.assertTrue(form.is_valid()) def test_inherited_unique(self): title = 'Boss' Book.objects.create(title=title, author=self.writer, special_id=1) form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'special_id': '1', 'isbn': '12345'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['special_id'], ['Book with this Special id already exists.']) def test_inherited_unique_together(self): title = 'Boss' form = BookForm({'title': title, 'author': self.writer.pk}) self.assertTrue(form.is_valid()) form.save() form = DerivedBookForm({'title': title, 'author': self.writer.pk, 'isbn': '12345'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['__all__'], ['Book with this Title and Author already exists.']) def test_abstract_inherited_unique(self): title = 'Boss' isbn = '12345' DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn) form = DerivedBookForm({ 'title': 'Other', 'author': self.writer.pk, 'isbn': isbn, 'suffix1': '1', 'suffix2': '2', }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['isbn'], ['Derived book with this Isbn already exists.']) def test_abstract_inherited_unique_together(self): title = 'Boss' isbn = '12345' DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn) form = DerivedBookForm({ 'title': 'Other', 'author': self.writer.pk, 'isbn': '9876', 'suffix1': '0', 'suffix2': '0' }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors['__all__'], ['Derived book with this Suffix1 and Suffix2 already exists.'], ) def test_explicitpk_unspecified(self): """Test for primary_key being in the form and failing validation.""" form = ExplicitPKForm({'key': '', 'desc': ''}) self.assertFalse(form.is_valid()) def test_explicitpk_unique(self): """Ensure keys and blank character strings are tested for uniqueness.""" form = ExplicitPKForm({'key': 'key1', 'desc': ''}) self.assertTrue(form.is_valid()) form.save() form = ExplicitPKForm({'key': 'key1', 'desc': ''}) self.assertFalse(form.is_valid()) if connection.features.interprets_empty_strings_as_nulls: self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['key'], ['Explicit pk with this Key already exists.']) else: self.assertEqual(len(form.errors), 3) self.assertEqual(form.errors['__all__'], ['Explicit pk with this Key and Desc already exists.']) self.assertEqual(form.errors['desc'], ['Explicit pk with this Desc already exists.']) self.assertEqual(form.errors['key'], ['Explicit pk with this Key already exists.']) def test_unique_for_date(self): p = Post.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['title'], ['Title must be unique for Posted date.']) form = PostForm({'title': "Work on Django 1.1 begins", 'posted': '2008-09-03'}) self.assertTrue(form.is_valid()) form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-04'}) self.assertTrue(form.is_valid()) form = PostForm({'slug': "Django 1.0", 'posted': '2008-01-01'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['slug'], ['Slug must be unique for Posted year.']) form = PostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.']) data = {'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", 'posted': '2008-09-03'} form = PostForm(data, instance=p) self.assertTrue(form.is_valid()) form = PostForm({'title': "Django 1.0 is released"}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['posted'], ['This field is required.']) def test_unique_for_date_in_exclude(self): """ If the date for unique_for_* constraints is excluded from the ModelForm (in this case 'posted' has editable=False, then the constraint should be ignored. """ class DateTimePostForm(forms.ModelForm): class Meta: model = DateTimePost fields = '__all__' DateTimePost.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.datetime(2008, 9, 3, 10, 10, 1), ) # 'title' has unique_for_date='posted' form = DateTimePostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertTrue(form.is_valid()) # 'slug' has unique_for_year='posted' form = DateTimePostForm({'slug': "Django 1.0", 'posted': '2008-01-01'}) self.assertTrue(form.is_valid()) # 'subtitle' has unique_for_month='posted' form = DateTimePostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) self.assertTrue(form.is_valid()) def test_inherited_unique_for_date(self): p = Post.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['title'], ['Title must be unique for Posted date.']) form = DerivedPostForm({'title': "Work on Django 1.1 begins", 'posted': '2008-09-03'}) self.assertTrue(form.is_valid()) form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-04'}) self.assertTrue(form.is_valid()) form = DerivedPostForm({'slug': "Django 1.0", 'posted': '2008-01-01'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['slug'], ['Slug must be unique for Posted year.']) form = DerivedPostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.']) data = {'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", 'posted': '2008-09-03'} form = DerivedPostForm(data, instance=p) self.assertTrue(form.is_valid()) def test_unique_for_date_with_nullable_date(self): class FlexDatePostForm(forms.ModelForm): class Meta: model = FlexibleDatePost fields = '__all__' p = FlexibleDatePost.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = FlexDatePostForm({'title': "Django 1.0 is released"}) self.assertTrue(form.is_valid()) form = FlexDatePostForm({'slug': "Django 1.0"}) self.assertTrue(form.is_valid()) form = FlexDatePostForm({'subtitle': "Finally"}) self.assertTrue(form.is_valid()) data = {'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0"} form = FlexDatePostForm(data, instance=p) self.assertTrue(form.is_valid()) def test_override_unique_message(self): class CustomProductForm(ProductForm): class Meta(ProductForm.Meta): error_messages = { 'slug': { 'unique': "%(model_name)s's %(field_label)s not unique.", } } Product.objects.create(slug='teddy-bear-blue') form = CustomProductForm({'slug': 'teddy-bear-blue'}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['slug'], ["Product's Slug not unique."]) def test_override_unique_together_message(self): class CustomPriceForm(PriceForm): class Meta(PriceForm.Meta): error_messages = { NON_FIELD_ERRORS: { 'unique_together': "%(model_name)s's %(field_labels)s not unique.", } } Price.objects.create(price=6.00, quantity=1) form = CustomPriceForm({'price': '6.00', 'quantity': '1'}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors[NON_FIELD_ERRORS], ["Price's Price and Quantity not unique."]) def test_override_unique_for_date_message(self): class CustomPostForm(PostForm): class Meta(PostForm.Meta): error_messages = { 'title': { 'unique_for_date': ( "%(model_name)s's %(field_label)s not unique " "for %(date_field_label)s date." ), } } Post.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = CustomPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['title'], ["Post's Title not unique for Posted date."]) class ModelFormBasicTests(TestCase): def create_basic_data(self): self.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment') self.c2 = Category.objects.create(name="It's a test", slug='its-test', url='test') self.c3 = Category.objects.create(name='Third test', slug='third-test', url='third') self.w_royko = Writer.objects.create(name='Mike Royko') self.w_woodward = Writer.objects.create(name='Bob Woodward') def test_base_form(self): self.assertEqual(Category.objects.count(), 0) f = BaseCategoryForm() self.assertHTMLEqual( str(f), """<tr><th><label for="id_name">Name:</label></th> <td><input id="id_name" type="text" name="name" maxlength="20" required></td></tr> <tr><th><label for="id_slug">Slug:</label></th> <td><input id="id_slug" type="text" name="slug" maxlength="20" required></td></tr> <tr><th><label for="id_url">The URL:</label></th> <td><input id="id_url" type="text" name="url" maxlength="40" required></td></tr>""" ) self.assertHTMLEqual( str(f.as_ul()), """<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="20" required></li> <li><label for="id_slug">Slug:</label> <input id="id_slug" type="text" name="slug" maxlength="20" required></li> <li><label for="id_url">The URL:</label> <input id="id_url" type="text" name="url" maxlength="40" required></li>""" ) self.assertHTMLEqual( str(f["name"]), """<input id="id_name" type="text" name="name" maxlength="20" required>""") def test_auto_id(self): f = BaseCategoryForm(auto_id=False) self.assertHTMLEqual( str(f.as_ul()), """<li>Name: <input type="text" name="name" maxlength="20" required></li> <li>Slug: <input type="text" name="slug" maxlength="20" required></li> <li>The URL: <input type="text" name="url" maxlength="40" required></li>""" ) def test_initial_values(self): self.create_basic_data() # Initial values can be provided for model forms f = ArticleForm( auto_id=False, initial={ 'headline': 'Your headline here', 'categories': [str(self.c1.id), str(self.c2.id)] }) self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="Your headline here" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" required></li> <li>Writer: <select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required></textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s" selected>Entertainment</option> <option value="%s" selected>It&#x27;s a test</option> <option value="%s">Third test</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk)) # When the ModelForm is passed an instance, that instance's current values are # inserted as 'initial' data in each Field. f = RoykoForm(auto_id=False, instance=self.w_royko) self.assertHTMLEqual( str(f), '''<tr><th>Name:</th><td><input type="text" name="name" value="Mike Royko" maxlength="50" required><br> <span class="helptext">Use both first and last names.</span></td></tr>''' ) art = Article.objects.create( headline='Test article', slug='test-article', pub_date=datetime.date(1988, 1, 4), writer=self.w_royko, article='Hello.' ) art_id_1 = art.id f = ArticleForm(auto_id=False, instance=art) self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="Test article" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" value="test-article" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li> <li>Writer: <select name="writer" required> <option value="">---------</option> <option value="%s">Bob Woodward</option> <option value="%s" selected>Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk)) f = ArticleForm({ 'headline': 'Test headline', 'slug': 'test-headline', 'pub_date': '1984-02-06', 'writer': str(self.w_royko.pk), 'article': 'Hello.' }, instance=art) self.assertEqual(f.errors, {}) self.assertTrue(f.is_valid()) test_art = f.save() self.assertEqual(test_art.id, art_id_1) test_art = Article.objects.get(id=art_id_1) self.assertEqual(test_art.headline, 'Test headline') def test_m2m_initial_callable(self): """ Regression for #10349: A callable can be provided as the initial value for an m2m field """ self.maxDiff = 1200 self.create_basic_data() # Set up a callable initial value def formfield_for_dbfield(db_field, **kwargs): if db_field.name == 'categories': kwargs['initial'] = lambda: Category.objects.all().order_by('name')[:2] return db_field.formfield(**kwargs) # Create a ModelForm, instantiate it, and check that the output is as expected ModelForm = modelform_factory( Article, fields=['headline', 'categories'], formfield_callback=formfield_for_dbfield, ) form = ModelForm() self.assertHTMLEqual( form.as_ul(), """<li><label for="id_headline">Headline:</label> <input id="id_headline" type="text" name="headline" maxlength="50" required></li> <li><label for="id_categories">Categories:</label> <select multiple name="categories" id="id_categories"> <option value="%d" selected>Entertainment</option> <option value="%d" selected>It&#x27;s a test</option> <option value="%d">Third test</option> </select></li>""" % (self.c1.pk, self.c2.pk, self.c3.pk)) def test_basic_creation(self): self.assertEqual(Category.objects.count(), 0) f = BaseCategoryForm({ 'name': 'Entertainment', 'slug': 'entertainment', 'url': 'entertainment', }) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['name'], 'Entertainment') self.assertEqual(f.cleaned_data['slug'], 'entertainment') self.assertEqual(f.cleaned_data['url'], 'entertainment') c1 = f.save() # Testing whether the same object is returned from the # ORM... not the fastest way... self.assertEqual(Category.objects.count(), 1) self.assertEqual(c1, Category.objects.all()[0]) self.assertEqual(c1.name, "Entertainment") def test_save_commit_false(self): # If you call save() with commit=False, then it will return an object that # hasn't yet been saved to the database. In this case, it's up to you to call # save() on the resulting model instance. f = BaseCategoryForm({'name': 'Third test', 'slug': 'third-test', 'url': 'third'}) self.assertTrue(f.is_valid()) c1 = f.save(commit=False) self.assertEqual(c1.name, "Third test") self.assertEqual(Category.objects.count(), 0) c1.save() self.assertEqual(Category.objects.count(), 1) def test_save_with_data_errors(self): # If you call save() with invalid data, you'll get a ValueError. f = BaseCategoryForm({'name': '', 'slug': 'not a slug!', 'url': 'foo'}) self.assertEqual(f.errors['name'], ['This field is required.']) self.assertEqual( f.errors['slug'], ['Enter a valid “slug” consisting of letters, numbers, underscores or hyphens.'] ) self.assertEqual(f.cleaned_data, {'url': 'foo'}) msg = "The Category could not be created because the data didn't validate." with self.assertRaisesMessage(ValueError, msg): f.save() f = BaseCategoryForm({'name': '', 'slug': '', 'url': 'foo'}) with self.assertRaisesMessage(ValueError, msg): f.save() def test_multi_fields(self): self.create_basic_data() self.maxDiff = None # ManyToManyFields are represented by a MultipleChoiceField, ForeignKeys and any # fields with the 'choices' attribute are represented by a ChoiceField. f = ArticleForm(auto_id=False) self.assertHTMLEqual( str(f), '''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" required></td></tr> <tr><th>Slug:</th><td><input type="text" name="slug" maxlength="50" required></td></tr> <tr><th>Pub date:</th><td><input type="text" name="pub_date" required></td></tr> <tr><th>Writer:</th><td><select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></td></tr> <tr><th>Article:</th><td><textarea rows="10" cols="40" name="article" required></textarea></td></tr> <tr><th>Categories:</th><td><select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select></td></tr> <tr><th>Status:</th><td><select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></td></tr>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk)) # Add some categories and test the many-to-many form output. new_art = Article.objects.create( article="Hello.", headline="New headline", slug="new-headline", pub_date=datetime.date(1988, 1, 4), writer=self.w_royko) new_art.categories.add(Category.objects.get(name='Entertainment')) self.assertQuerysetEqual(new_art.categories.all(), ["Entertainment"]) f = ArticleForm(auto_id=False, instance=new_art) self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li> <li>Writer: <select name="writer" required> <option value="">---------</option> <option value="%s">Bob Woodward</option> <option value="%s" selected>Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s" selected>Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk)) def test_subset_fields(self): # You can restrict a form to a subset of the complete list of fields # by providing a 'fields' argument. If you try to save a # model created with such a form, you need to ensure that the fields # that are _not_ on the form have default values, or are allowed to have # a value of None. If a field isn't specified on a form, the object created # from the form can't provide a value for that field! class PartialArticleForm(forms.ModelForm): class Meta: model = Article fields = ('headline', 'pub_date') f = PartialArticleForm(auto_id=False) self.assertHTMLEqual( str(f), '''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" required></td></tr> <tr><th>Pub date:</th><td><input type="text" name="pub_date" required></td></tr>''') class PartialArticleFormWithSlug(forms.ModelForm): class Meta: model = Article fields = ('headline', 'slug', 'pub_date') w_royko = Writer.objects.create(name='Mike Royko') art = Article.objects.create( article="Hello.", headline="New headline", slug="new-headline", pub_date=datetime.date(1988, 1, 4), writer=w_royko) f = PartialArticleFormWithSlug({ 'headline': 'New headline', 'slug': 'new-headline', 'pub_date': '1988-01-04' }, auto_id=False, instance=art) self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li>''' ) self.assertTrue(f.is_valid()) new_art = f.save() self.assertEqual(new_art.id, art.id) new_art = Article.objects.get(id=art.id) self.assertEqual(new_art.headline, 'New headline') def test_m2m_editing(self): self.create_basic_data() form_data = { 'headline': 'New headline', 'slug': 'new-headline', 'pub_date': '1988-01-04', 'writer': str(self.w_royko.pk), 'article': 'Hello.', 'categories': [str(self.c1.id), str(self.c2.id)] } # Create a new article, with categories, via the form. f = ArticleForm(form_data) new_art = f.save() new_art = Article.objects.get(id=new_art.id) art_id_1 = new_art.id self.assertQuerysetEqual(new_art.categories.order_by('name'), ["Entertainment", "It's a test"]) # Now, submit form data with no categories. This deletes the existing categories. form_data['categories'] = [] f = ArticleForm(form_data, instance=new_art) new_art = f.save() self.assertEqual(new_art.id, art_id_1) new_art = Article.objects.get(id=art_id_1) self.assertQuerysetEqual(new_art.categories.all(), []) # Create a new article, with no categories, via the form. f = ArticleForm(form_data) new_art = f.save() art_id_2 = new_art.id self.assertNotIn(art_id_2, (None, art_id_1)) new_art = Article.objects.get(id=art_id_2) self.assertQuerysetEqual(new_art.categories.all(), []) # Create a new article, with categories, via the form, but use commit=False. # The m2m data won't be saved until save_m2m() is invoked on the form. form_data['categories'] = [str(self.c1.id), str(self.c2.id)] f = ArticleForm(form_data) new_art = f.save(commit=False) # Manually save the instance new_art.save() art_id_3 = new_art.id self.assertNotIn(art_id_3, (None, art_id_1, art_id_2)) # The instance doesn't have m2m data yet new_art = Article.objects.get(id=art_id_3) self.assertQuerysetEqual(new_art.categories.all(), []) # Save the m2m data on the form f.save_m2m() self.assertQuerysetEqual(new_art.categories.order_by('name'), ["Entertainment", "It's a test"]) def test_custom_form_fields(self): # Here, we define a custom ModelForm. Because it happens to have the same fields as # the Category model, we can just call the form's save() to apply its changes to an # existing Category instance. class ShortCategory(forms.ModelForm): name = forms.CharField(max_length=5) slug = forms.CharField(max_length=5) url = forms.CharField(max_length=3) class Meta: model = Category fields = '__all__' cat = Category.objects.create(name='Third test') form = ShortCategory({'name': 'Third', 'slug': 'third', 'url': '3rd'}, instance=cat) self.assertEqual(form.save().name, 'Third') self.assertEqual(Category.objects.get(id=cat.id).name, 'Third') def test_runtime_choicefield_populated(self): self.maxDiff = None # Here, we demonstrate that choices for a ForeignKey ChoiceField are determined # at runtime, based on the data in the database when the form is displayed, not # the data in the database when the form is instantiated. self.create_basic_data() f = ArticleForm(auto_id=False) self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" required></li> <li>Writer: <select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required></textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select> </li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk)) c4 = Category.objects.create(name='Fourth', url='4th') w_bernstein = Writer.objects.create(name='Carl Bernstein') self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" required></li> <li>Writer: <select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Carl Bernstein</option> <option value="%s">Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required></textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> <option value="%s">Fourth</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>''' % (self.w_woodward.pk, w_bernstein.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk, c4.pk)) def test_recleaning_model_form_instance(self): """ Re-cleaning an instance that was added via a ModelForm shouldn't raise a pk uniqueness error. """ class AuthorForm(forms.ModelForm): class Meta: model = Author fields = '__all__' form = AuthorForm({'full_name': 'Bob'}) self.assertTrue(form.is_valid()) obj = form.save() obj.name = 'Alice' obj.full_clean() class ModelMultipleChoiceFieldTests(TestCase): @classmethod def setUpTestData(cls): cls.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment') cls.c2 = Category.objects.create(name="It's a test", slug='its-test', url='test') cls.c3 = Category.objects.create(name='Third', slug='third-test', url='third') def test_model_multiple_choice_field(self): f = forms.ModelMultipleChoiceField(Category.objects.all()) self.assertEqual(list(f.choices), [ (self.c1.pk, 'Entertainment'), (self.c2.pk, "It's a test"), (self.c3.pk, 'Third')]) with self.assertRaises(ValidationError): f.clean(None) with self.assertRaises(ValidationError): f.clean([]) self.assertQuerysetEqual(f.clean([self.c1.id]), ["Entertainment"]) self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"]) self.assertQuerysetEqual(f.clean([str(self.c1.id)]), ["Entertainment"]) self.assertQuerysetEqual( f.clean([str(self.c1.id), str(self.c2.id)]), ["Entertainment", "It's a test"], ordered=False ) self.assertQuerysetEqual( f.clean([self.c1.id, str(self.c2.id)]), ["Entertainment", "It's a test"], ordered=False ) self.assertQuerysetEqual( f.clean((self.c1.id, str(self.c2.id))), ["Entertainment", "It's a test"], ordered=False ) with self.assertRaises(ValidationError): f.clean(['100']) with self.assertRaises(ValidationError): f.clean('hello') with self.assertRaises(ValidationError): f.clean(['fail']) # Invalid types that require TypeError to be caught (#22808). with self.assertRaises(ValidationError): f.clean([['fail']]) with self.assertRaises(ValidationError): f.clean([{'foo': 'bar'}]) # Add a Category object *after* the ModelMultipleChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. # Note, we are using an id of 1006 here since tests that run before # this may create categories with primary keys up to 6. Use # a number that will not conflict. c6 = Category.objects.create(id=1006, name='Sixth', url='6th') self.assertQuerysetEqual(f.clean([c6.id]), ["Sixth"]) # Delete a Category object *after* the ModelMultipleChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. Category.objects.get(url='6th').delete() with self.assertRaises(ValidationError): f.clean([c6.id]) def test_model_multiple_choice_required_false(self): f = forms.ModelMultipleChoiceField(Category.objects.all(), required=False) self.assertIsInstance(f.clean([]), EmptyQuerySet) self.assertIsInstance(f.clean(()), EmptyQuerySet) with self.assertRaises(ValidationError): f.clean(['0']) with self.assertRaises(ValidationError): f.clean([str(self.c3.id), '0']) with self.assertRaises(ValidationError): f.clean([str(self.c1.id), '0']) # queryset can be changed after the field is created. f.queryset = Category.objects.exclude(name='Third') self.assertEqual(list(f.choices), [ (self.c1.pk, 'Entertainment'), (self.c2.pk, "It's a test")]) self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"]) with self.assertRaises(ValidationError): f.clean([self.c3.id]) with self.assertRaises(ValidationError): f.clean([str(self.c2.id), str(self.c3.id)]) f.queryset = Category.objects.all() f.label_from_instance = lambda obj: "multicategory " + str(obj) self.assertEqual(list(f.choices), [ (self.c1.pk, 'multicategory Entertainment'), (self.c2.pk, "multicategory It's a test"), (self.c3.pk, 'multicategory Third')]) def test_model_multiple_choice_number_of_queries(self): """ ModelMultipleChoiceField does O(1) queries instead of O(n) (#10156). """ persons = [Writer.objects.create(name="Person %s" % i) for i in range(30)] f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all()) self.assertNumQueries(1, f.clean, [p.pk for p in persons[1:11:2]]) def test_model_multiple_choice_run_validators(self): """ ModelMultipleChoiceField run given validators (#14144). """ for i in range(30): Writer.objects.create(name="Person %s" % i) self._validator_run = False def my_validator(value): self._validator_run = True f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all(), validators=[my_validator]) f.clean([p.pk for p in Writer.objects.all()[8:9]]) self.assertTrue(self._validator_run) def test_model_multiple_choice_show_hidden_initial(self): """ Test support of show_hidden_initial by ModelMultipleChoiceField. """ class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField(show_hidden_initial=True, queryset=Writer.objects.all()) person1 = Writer.objects.create(name="Person 1") person2 = Writer.objects.create(name="Person 2") form = WriterForm( initial={'persons': [person1, person2]}, data={ 'initial-persons': [str(person1.pk), str(person2.pk)], 'persons': [str(person1.pk), str(person2.pk)], }, ) self.assertTrue(form.is_valid()) self.assertFalse(form.has_changed()) form = WriterForm( initial={'persons': [person1, person2]}, data={ 'initial-persons': [str(person1.pk), str(person2.pk)], 'persons': [str(person2.pk)], }, ) self.assertTrue(form.is_valid()) self.assertTrue(form.has_changed()) def test_model_multiple_choice_field_22745(self): """ #22745 -- Make sure that ModelMultipleChoiceField with CheckboxSelectMultiple widget doesn't produce unnecessary db queries when accessing its BoundField's attrs. """ class ModelMultipleChoiceForm(forms.Form): categories = forms.ModelMultipleChoiceField(Category.objects.all(), widget=forms.CheckboxSelectMultiple) form = ModelMultipleChoiceForm() field = form['categories'] # BoundField template = Template('{{ field.name }}{{ field }}{{ field.help_text }}') with self.assertNumQueries(1): template.render(Context({'field': field})) def test_show_hidden_initial_changed_queries_efficiently(self): class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField( show_hidden_initial=True, queryset=Writer.objects.all()) writers = (Writer.objects.create(name=str(x)) for x in range(0, 50)) writer_pks = tuple(x.pk for x in writers) form = WriterForm(data={'initial-persons': writer_pks}) with self.assertNumQueries(1): self.assertTrue(form.has_changed()) def test_clean_does_deduplicate_values(self): class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField(queryset=Writer.objects.all()) person1 = Writer.objects.create(name="Person 1") form = WriterForm(data={}) queryset = form.fields['persons'].clean([str(person1.pk)] * 50) sql, params = queryset.query.sql_with_params() self.assertEqual(len(params), 1) def test_to_field_name_with_initial_data(self): class ArticleCategoriesForm(forms.ModelForm): categories = forms.ModelMultipleChoiceField(Category.objects.all(), to_field_name='slug') class Meta: model = Article fields = ['categories'] article = Article.objects.create( headline='Test article', slug='test-article', pub_date=datetime.date(1988, 1, 4), writer=Writer.objects.create(name='Test writer'), article='Hello.', ) article.categories.add(self.c2, self.c3) form = ArticleCategoriesForm(instance=article) self.assertCountEqual(form['categories'].value(), [self.c2.slug, self.c3.slug]) class ModelOneToOneFieldTests(TestCase): def test_modelform_onetoonefield(self): class ImprovedArticleForm(forms.ModelForm): class Meta: model = ImprovedArticle fields = '__all__' class ImprovedArticleWithParentLinkForm(forms.ModelForm): class Meta: model = ImprovedArticleWithParentLink fields = '__all__' self.assertEqual(list(ImprovedArticleForm.base_fields), ['article']) self.assertEqual(list(ImprovedArticleWithParentLinkForm.base_fields), []) def test_modelform_subclassed_model(self): class BetterWriterForm(forms.ModelForm): class Meta: # BetterWriter model is a subclass of Writer with an additional `score` field model = BetterWriter fields = '__all__' bw = BetterWriter.objects.create(name='Joe Better', score=10) self.assertEqual(sorted(model_to_dict(bw)), ['id', 'name', 'score', 'writer_ptr']) self.assertEqual(sorted(model_to_dict(bw, fields=[])), []) self.assertEqual(sorted(model_to_dict(bw, fields=['id', 'name'])), ['id', 'name']) self.assertEqual(sorted(model_to_dict(bw, exclude=[])), ['id', 'name', 'score', 'writer_ptr']) self.assertEqual(sorted(model_to_dict(bw, exclude=['id', 'name'])), ['score', 'writer_ptr']) form = BetterWriterForm({'name': 'Some Name', 'score': 12}) self.assertTrue(form.is_valid()) bw2 = form.save() self.assertEqual(bw2.score, 12) def test_onetoonefield(self): class WriterProfileForm(forms.ModelForm): class Meta: # WriterProfile has a OneToOneField to Writer model = WriterProfile fields = '__all__' self.w_royko = Writer.objects.create(name='Mike Royko') self.w_woodward = Writer.objects.create(name='Bob Woodward') form = WriterProfileForm() self.assertHTMLEqual( form.as_p(), '''<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></p> <p><label for="id_age">Age:</label> <input type="number" name="age" id="id_age" min="0" required></p>''' % ( self.w_woodward.pk, self.w_royko.pk, ) ) data = { 'writer': str(self.w_woodward.pk), 'age': '65', } form = WriterProfileForm(data) instance = form.save() self.assertEqual(str(instance), 'Bob Woodward is 65') form = WriterProfileForm(instance=instance) self.assertHTMLEqual( form.as_p(), '''<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer" required> <option value="">---------</option> <option value="%s" selected>Bob Woodward</option> <option value="%s">Mike Royko</option> </select></p> <p><label for="id_age">Age:</label> <input type="number" name="age" value="65" id="id_age" min="0" required></p>''' % ( self.w_woodward.pk, self.w_royko.pk, ) ) def test_assignment_of_none(self): class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ['publication', 'full_name'] publication = Publication.objects.create(title="Pravda", date_published=datetime.date(1991, 8, 22)) author = Author.objects.create(publication=publication, full_name='John Doe') form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author) self.assertTrue(form.is_valid()) self.assertIsNone(form.cleaned_data['publication']) author = form.save() # author object returned from form still retains original publication object # that's why we need to retrieve it from database again new_author = Author.objects.get(pk=author.pk) self.assertIsNone(new_author.publication) def test_assignment_of_none_null_false(self): class AuthorForm(forms.ModelForm): class Meta: model = Author1 fields = ['publication', 'full_name'] publication = Publication.objects.create(title="Pravda", date_published=datetime.date(1991, 8, 22)) author = Author1.objects.create(publication=publication, full_name='John Doe') form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author) self.assertFalse(form.is_valid()) class FileAndImageFieldTests(TestCase): def test_clean_false(self): """ If the ``clean`` method on a non-required FileField receives False as the data (meaning clear the field value), it returns False, regardless of the value of ``initial``. """ f = forms.FileField(required=False) self.assertIs(f.clean(False), False) self.assertIs(f.clean(False, 'initial'), False) def test_clean_false_required(self): """ If the ``clean`` method on a required FileField receives False as the data, it has the same effect as None: initial is returned if non-empty, otherwise the validation catches the lack of a required value. """ f = forms.FileField(required=True) self.assertEqual(f.clean(False, 'initial'), 'initial') with self.assertRaises(ValidationError): f.clean(False) def test_full_clear(self): """ Integration happy-path test that a model FileField can actually be set and cleared via a ModelForm. """ class DocumentForm(forms.ModelForm): class Meta: model = Document fields = '__all__' form = DocumentForm() self.assertIn('name="myfile"', str(form)) self.assertNotIn('myfile-clear', str(form)) form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', b'content')}) self.assertTrue(form.is_valid()) doc = form.save(commit=False) self.assertEqual(doc.myfile.name, 'something.txt') form = DocumentForm(instance=doc) self.assertIn('myfile-clear', str(form)) form = DocumentForm(instance=doc, data={'myfile-clear': 'true'}) doc = form.save(commit=False) self.assertFalse(doc.myfile) def test_clear_and_file_contradiction(self): """ If the user submits a new file upload AND checks the clear checkbox, they get a validation error, and the bound redisplay of the form still includes the current file and the clear checkbox. """ class DocumentForm(forms.ModelForm): class Meta: model = Document fields = '__all__' form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', b'content')}) self.assertTrue(form.is_valid()) doc = form.save(commit=False) form = DocumentForm( instance=doc, files={'myfile': SimpleUploadedFile('something.txt', b'content')}, data={'myfile-clear': 'true'}, ) self.assertTrue(not form.is_valid()) self.assertEqual(form.errors['myfile'], ['Please either submit a file or check the clear checkbox, not both.']) rendered = str(form) self.assertIn('something.txt', rendered) self.assertIn('myfile-clear', rendered) def test_render_empty_file_field(self): class DocumentForm(forms.ModelForm): class Meta: model = Document fields = '__all__' doc = Document.objects.create() form = DocumentForm(instance=doc) self.assertHTMLEqual( str(form['myfile']), '<input id="id_myfile" name="myfile" type="file">' ) def test_file_field_data(self): # Test conditions when files is either not given or empty. f = TextFileForm(data={'description': 'Assistance'}) self.assertFalse(f.is_valid()) f = TextFileForm(data={'description': 'Assistance'}, files={}) self.assertFalse(f.is_valid()) # Upload a file and ensure it all works as expected. f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test1.txt', b'hello world')}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.file.name, 'tests/test1.txt') instance.file.delete() # If the previous file has been deleted, the file name can be reused f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test1.txt', b'hello world')}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.file.name, 'tests/test1.txt') # Check if the max_length attribute has been inherited from the model. f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test-maxlength.txt', b'hello world')}, ) self.assertFalse(f.is_valid()) # Edit an instance that already has the file defined in the model. This will not # save the file again, but leave it exactly as it is. f = TextFileForm({'description': 'Assistance'}, instance=instance) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['file'].name, 'tests/test1.txt') instance = f.save() self.assertEqual(instance.file.name, 'tests/test1.txt') # Delete the current file since this is not done by Django. instance.file.delete() # Override the file by uploading a new one. f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test2.txt', b'hello world')}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, 'tests/test2.txt') # Delete the current file since this is not done by Django. instance.file.delete() instance.delete() def test_filefield_required_false(self): # Test the non-required FileField f = TextFileForm(data={'description': 'Assistance'}) f.fields['file'].required = False self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, '') f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test3.txt', b'hello world')}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, 'tests/test3.txt') # Instance can be edited w/out re-uploading the file and existing file should be preserved. f = TextFileForm({'description': 'New Description'}, instance=instance) f.fields['file'].required = False self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.description, 'New Description') self.assertEqual(instance.file.name, 'tests/test3.txt') # Delete the current file since this is not done by Django. instance.file.delete() instance.delete() def test_custom_file_field_save(self): """ Regression for #11149: save_form_data should be called only once """ class CFFForm(forms.ModelForm): class Meta: model = CustomFF fields = '__all__' # It's enough that the form saves without error -- the custom save routine will # generate an AssertionError if it is called more than once during save. form = CFFForm(data={'f': None}) form.save() def test_file_field_multiple_save(self): """ Simulate a file upload and check how many times Model.save() gets called. Test for bug #639. """ class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = '__all__' # Grab an image for testing. filename = os.path.join(os.path.dirname(__file__), 'test.png') with open(filename, "rb") as fp: img = fp.read() # Fake a POST QueryDict and FILES MultiValueDict. data = {'title': 'Testing'} files = {"image": SimpleUploadedFile('test.png', img, 'image/png')} form = PhotoForm(data=data, files=files) p = form.save() try: # Check the savecount stored on the object (see the model). self.assertEqual(p._savecount, 1) finally: # Delete the "uploaded" file to avoid clogging /tmp. p = Photo.objects.get() p.image.delete(save=False) def test_file_path_field_blank(self): """FilePathField(blank=True) includes the empty option.""" class FPForm(forms.ModelForm): class Meta: model = FilePathModel fields = '__all__' form = FPForm() self.assertEqual([name for _, name in form['path'].field.choices], ['---------', 'models.py']) @skipUnless(test_images, "Pillow not installed") def test_image_field(self): # ImageField and FileField are nearly identical, but they differ slightly when # it comes to validation. This specifically tests that #6302 is fixed for # both file fields and image fields. with open(os.path.join(os.path.dirname(__file__), 'test.png'), 'rb') as fp: image_data = fp.read() with open(os.path.join(os.path.dirname(__file__), 'test2.png'), 'rb') as fp: image_data2 = fp.read() f = ImageFileForm( data={'description': 'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['image']), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.image.name, 'tests/test.png') self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) f = ImageFileForm( data={'description': 'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['image']), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.image.name, 'tests/test.png') self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Edit an instance that already has the (required) image defined in the model. This will not # save the image again, but leave it exactly as it is. f = ImageFileForm(data={'description': 'Look, it changed'}, instance=instance) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['image'].name, 'tests/test.png') instance = f.save() self.assertEqual(instance.image.name, 'tests/test.png') self.assertEqual(instance.height, 16) self.assertEqual(instance.width, 16) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) # Override the file by uploading a new one. f = ImageFileForm( data={'description': 'Changed it'}, files={'image': SimpleUploadedFile('test2.png', image_data2)}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/test2.png') self.assertEqual(instance.height, 32) self.assertEqual(instance.width, 48) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) instance.delete() f = ImageFileForm( data={'description': 'Changed it'}, files={'image': SimpleUploadedFile('test2.png', image_data2)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/test2.png') self.assertEqual(instance.height, 32) self.assertEqual(instance.width, 48) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) instance.delete() # Test the non-required ImageField # Note: In Oracle, we expect a null ImageField to return '' instead of # None. if connection.features.interprets_empty_strings_as_nulls: expected_null_imagefield_repr = '' else: expected_null_imagefield_repr = None f = OptionalImageFileForm(data={'description': 'Test'}) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, expected_null_imagefield_repr) self.assertIsNone(instance.width) self.assertIsNone(instance.height) f = OptionalImageFileForm( data={'description': 'And a final one'}, files={'image': SimpleUploadedFile('test3.png', image_data)}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/test3.png') self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Editing the instance without re-uploading the image should not affect # the image or its width/height properties. f = OptionalImageFileForm({'description': 'New Description'}, instance=instance) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.description, 'New Description') self.assertEqual(instance.image.name, 'tests/test3.png') self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Delete the current file since this is not done by Django. instance.image.delete() instance.delete() f = OptionalImageFileForm( data={'description': 'And a final one'}, files={'image': SimpleUploadedFile('test4.png', image_data2)} ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/test4.png') self.assertEqual(instance.width, 48) self.assertEqual(instance.height, 32) instance.delete() # Test callable upload_to behavior that's dependent on the value of another field in the model f = ImageFileForm( data={'description': 'And a final one', 'path': 'foo'}, files={'image': SimpleUploadedFile('test4.png', image_data)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'foo/test4.png') instance.delete() # Editing an instance that has an image without an extension shouldn't # fail validation. First create: f = NoExtensionImageFileForm( data={'description': 'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/no_extension') # Then edit: f = NoExtensionImageFileForm(data={'description': 'Edited image'}, instance=instance) self.assertTrue(f.is_valid()) class ModelOtherFieldTests(SimpleTestCase): def test_big_integer_field(self): bif = BigIntForm({'biggie': '-9223372036854775808'}) self.assertTrue(bif.is_valid()) bif = BigIntForm({'biggie': '-9223372036854775809'}) self.assertFalse(bif.is_valid()) self.assertEqual( bif.errors, {'biggie': ['Ensure this value is greater than or equal to -9223372036854775808.']} ) bif = BigIntForm({'biggie': '9223372036854775807'}) self.assertTrue(bif.is_valid()) bif = BigIntForm({'biggie': '9223372036854775808'}) self.assertFalse(bif.is_valid()) self.assertEqual(bif.errors, {'biggie': ['Ensure this value is less than or equal to 9223372036854775807.']}) def test_url_on_modelform(self): "Check basic URL field validation on model forms" class HomepageForm(forms.ModelForm): class Meta: model = Homepage fields = '__all__' self.assertFalse(HomepageForm({'url': 'foo'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://example'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://example.'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://com.'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://localhost'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://example.com'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com:8000'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com/test'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com:8000/test'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://example.com/foo/bar'}).is_valid()) def test_modelform_non_editable_field(self): """ When explicitly including a non-editable field in a ModelForm, the error message should be explicit. """ # 'created', non-editable, is excluded by default self.assertNotIn('created', ArticleForm().fields) msg = "'created' cannot be specified for Article model form as it is a non-editable field" with self.assertRaisesMessage(FieldError, msg): class InvalidArticleForm(forms.ModelForm): class Meta: model = Article fields = ('headline', 'created') def test_http_prefixing(self): """ If the http:// prefix is omitted on form input, the field adds it again. (Refs #13613) """ class HomepageForm(forms.ModelForm): class Meta: model = Homepage fields = '__all__' form = HomepageForm({'url': 'example.com'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['url'], 'http://example.com') form = HomepageForm({'url': 'example.com/test'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['url'], 'http://example.com/test') class OtherModelFormTests(TestCase): def test_media_on_modelform(self): # Similar to a regular Form class you can define custom media to be used on # the ModelForm. f = ModelFormWithMedia() self.assertHTMLEqual( str(f.media), '''<link href="/some/form/css" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/some/form/javascript"></script>''' ) def test_choices_type(self): # Choices on CharField and IntegerField f = ArticleForm() with self.assertRaises(ValidationError): f.fields['status'].clean('42') f = ArticleStatusForm() with self.assertRaises(ValidationError): f.fields['status'].clean('z') def test_prefetch_related_queryset(self): """ ModelChoiceField should respect a prefetch_related() on its queryset. """ blue = Colour.objects.create(name='blue') red = Colour.objects.create(name='red') multicolor_item = ColourfulItem.objects.create() multicolor_item.colours.add(blue, red) red_item = ColourfulItem.objects.create() red_item.colours.add(red) class ColorModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return ', '.join(c.name for c in obj.colours.all()) field = ColorModelChoiceField(ColourfulItem.objects.prefetch_related('colours')) with self.assertNumQueries(3): # would be 4 if prefetch is ignored self.assertEqual(tuple(field.choices), ( ('', '---------'), (multicolor_item.pk, 'blue, red'), (red_item.pk, 'red'), )) def test_foreignkeys_which_use_to_field(self): apple = Inventory.objects.create(barcode=86, name='Apple') Inventory.objects.create(barcode=22, name='Pear') core = Inventory.objects.create(barcode=87, name='Core', parent=apple) field = forms.ModelChoiceField(Inventory.objects.all(), to_field_name='barcode') self.assertEqual(tuple(field.choices), ( ('', '---------'), (86, 'Apple'), (87, 'Core'), (22, 'Pear'))) form = InventoryForm(instance=core) self.assertHTMLEqual(str(form['parent']), '''<select name="parent" id="id_parent"> <option value="">---------</option> <option value="86" selected>Apple</option> <option value="87">Core</option> <option value="22">Pear</option> </select>''') data = model_to_dict(core) data['parent'] = '22' form = InventoryForm(data=data, instance=core) core = form.save() self.assertEqual(core.parent.name, 'Pear') class CategoryForm(forms.ModelForm): description = forms.CharField() class Meta: model = Category fields = ['description', 'url'] self.assertEqual(list(CategoryForm.base_fields), ['description', 'url']) self.assertHTMLEqual( str(CategoryForm()), '''<tr><th><label for="id_description">Description:</label></th> <td><input type="text" name="description" id="id_description" required></td></tr> <tr><th><label for="id_url">The URL:</label></th> <td><input id="id_url" type="text" name="url" maxlength="40" required></td></tr>''' ) # to_field_name should also work on ModelMultipleChoiceField ################## field = forms.ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode') self.assertEqual(tuple(field.choices), ((86, 'Apple'), (87, 'Core'), (22, 'Pear'))) self.assertQuerysetEqual(field.clean([86]), ['Apple']) form = SelectInventoryForm({'items': [87, 22]}) self.assertTrue(form.is_valid()) self.assertEqual(len(form.cleaned_data), 1) self.assertQuerysetEqual(form.cleaned_data['items'], ['Core', 'Pear']) def test_model_field_that_returns_none_to_exclude_itself_with_explicit_fields(self): self.assertEqual(list(CustomFieldForExclusionForm.base_fields), ['name']) self.assertHTMLEqual( str(CustomFieldForExclusionForm()), '''<tr><th><label for="id_name">Name:</label></th> <td><input id="id_name" type="text" name="name" maxlength="10" required></td></tr>''' ) def test_iterable_model_m2m(self): class ColourfulItemForm(forms.ModelForm): class Meta: model = ColourfulItem fields = '__all__' colour = Colour.objects.create(name='Blue') form = ColourfulItemForm() self.maxDiff = 1024 self.assertHTMLEqual( form.as_p(), """<p><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="50" required></p> <p><label for="id_colours">Colours:</label> <select multiple name="colours" id="id_colours" required> <option value="%(blue_pk)s">Blue</option> </select></p>""" % {'blue_pk': colour.pk}) def test_callable_field_default(self): class PublicationDefaultsForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ('title', 'date_published', 'mode', 'category') self.maxDiff = 2000 form = PublicationDefaultsForm() today_str = str(datetime.date.today()) self.assertHTMLEqual( form.as_p(), """ <p><label for="id_title">Title:</label> <input id="id_title" maxlength="30" name="title" type="text" required></p> <p><label for="id_date_published">Date published:</label> <input id="id_date_published" name="date_published" type="text" value="{0}" required> <input id="initial-id_date_published" name="initial-date_published" type="hidden" value="{0}"></p> <p><label for="id_mode">Mode:</label> <select id="id_mode" name="mode"> <option value="di" selected>direct</option> <option value="de">delayed</option></select> <input id="initial-id_mode" name="initial-mode" type="hidden" value="di"></p> <p><label for="id_category">Category:</label> <select id="id_category" name="category"> <option value="1">Games</option> <option value="2">Comics</option> <option value="3" selected>Novel</option></select> <input id="initial-id_category" name="initial-category" type="hidden" value="3"> """.format(today_str) ) empty_data = { 'title': '', 'date_published': today_str, 'initial-date_published': today_str, 'mode': 'di', 'initial-mode': 'di', 'category': '3', 'initial-category': '3', } bound_form = PublicationDefaultsForm(empty_data) self.assertFalse(bound_form.has_changed()) class ModelFormCustomErrorTests(SimpleTestCase): def test_custom_error_messages(self): data = {'name1': '@#$!!**@#$', 'name2': '@#$!!**@#$'} errors = CustomErrorMessageForm(data).errors self.assertHTMLEqual( str(errors['name1']), '<ul class="errorlist"><li>Form custom error message.</li></ul>' ) self.assertHTMLEqual( str(errors['name2']), '<ul class="errorlist"><li>Model custom error message.</li></ul>' ) def test_model_clean_error_messages(self): data = {'name1': 'FORBIDDEN_VALUE', 'name2': 'ABC'} form = CustomErrorMessageForm(data) self.assertFalse(form.is_valid()) self.assertHTMLEqual( str(form.errors['name1']), '<ul class="errorlist"><li>Model.clean() error messages.</li></ul>' ) data = {'name1': 'FORBIDDEN_VALUE2', 'name2': 'ABC'} form = CustomErrorMessageForm(data) self.assertFalse(form.is_valid()) self.assertHTMLEqual( str(form.errors['name1']), '<ul class="errorlist"><li>Model.clean() error messages (simpler syntax).</li></ul>' ) data = {'name1': 'GLOBAL_ERROR', 'name2': 'ABC'} form = CustomErrorMessageForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['__all__'], ['Global error message.']) class CustomCleanTests(TestCase): def test_override_clean(self): """ Regression for #12596: Calling super from ModelForm.clean() should be optional. """ class TripleFormWithCleanOverride(forms.ModelForm): class Meta: model = Triple fields = '__all__' def clean(self): if not self.cleaned_data['left'] == self.cleaned_data['right']: raise forms.ValidationError('Left and right should be equal') return self.cleaned_data form = TripleFormWithCleanOverride({'left': 1, 'middle': 2, 'right': 1}) self.assertTrue(form.is_valid()) # form.instance.left will be None if the instance was not constructed # by form.full_clean(). self.assertEqual(form.instance.left, 1) def test_model_form_clean_applies_to_model(self): """ Regression test for #12960. Make sure the cleaned_data returned from ModelForm.clean() is applied to the model instance. """ class CategoryForm(forms.ModelForm): class Meta: model = Category fields = '__all__' def clean(self): self.cleaned_data['name'] = self.cleaned_data['name'].upper() return self.cleaned_data data = {'name': 'Test', 'slug': 'test', 'url': '/test'} form = CategoryForm(data) category = form.save() self.assertEqual(category.name, 'TEST') class ModelFormInheritanceTests(SimpleTestCase): def test_form_subclass_inheritance(self): class Form(forms.Form): age = forms.IntegerField() class ModelForm(forms.ModelForm, Form): class Meta: model = Writer fields = '__all__' self.assertEqual(list(ModelForm().fields), ['name', 'age']) def test_field_removal(self): class ModelForm(forms.ModelForm): class Meta: model = Writer fields = '__all__' class Mixin: age = None class Form(forms.Form): age = forms.IntegerField() class Form2(forms.Form): foo = forms.IntegerField() self.assertEqual(list(ModelForm().fields), ['name']) self.assertEqual(list(type('NewForm', (Mixin, Form), {})().fields), []) self.assertEqual(list(type('NewForm', (Form2, Mixin, Form), {})().fields), ['foo']) self.assertEqual(list(type('NewForm', (Mixin, ModelForm, Form), {})().fields), ['name']) self.assertEqual(list(type('NewForm', (ModelForm, Mixin, Form), {})().fields), ['name']) self.assertEqual(list(type('NewForm', (ModelForm, Form, Mixin), {})().fields), ['name', 'age']) self.assertEqual(list(type('NewForm', (ModelForm, Form), {'age': None})().fields), ['name']) def test_field_removal_name_clashes(self): """ Form fields can be removed in subclasses by setting them to None (#22510). """ class MyForm(forms.ModelForm): media = forms.CharField() class Meta: model = Writer fields = '__all__' class SubForm(MyForm): media = None self.assertIn('media', MyForm().fields) self.assertNotIn('media', SubForm().fields) self.assertTrue(hasattr(MyForm, 'media')) self.assertTrue(hasattr(SubForm, 'media')) class StumpJokeForm(forms.ModelForm): class Meta: model = StumpJoke fields = '__all__' class CustomFieldWithQuerysetButNoLimitChoicesTo(forms.Field): queryset = 42 class StumpJokeWithCustomFieldForm(forms.ModelForm): custom = CustomFieldWithQuerysetButNoLimitChoicesTo() class Meta: model = StumpJoke fields = () class LimitChoicesToTests(TestCase): """ Tests the functionality of ``limit_choices_to``. """ @classmethod def setUpTestData(cls): cls.threepwood = Character.objects.create( username='threepwood', last_action=datetime.datetime.today() + datetime.timedelta(days=1), ) cls.marley = Character.objects.create( username='marley', last_action=datetime.datetime.today() - datetime.timedelta(days=1), ) def test_limit_choices_to_callable_for_fk_rel(self): """ A ForeignKey can use limit_choices_to as a callable (#2554). """ stumpjokeform = StumpJokeForm() self.assertSequenceEqual(stumpjokeform.fields['most_recently_fooled'].queryset, [self.threepwood]) def test_limit_choices_to_callable_for_m2m_rel(self): """ A ManyToManyField can use limit_choices_to as a callable (#2554). """ stumpjokeform = StumpJokeForm() self.assertSequenceEqual(stumpjokeform.fields['most_recently_fooled'].queryset, [self.threepwood]) def test_custom_field_with_queryset_but_no_limit_choices_to(self): """ A custom field with a `queryset` attribute but no `limit_choices_to` works (#23795). """ f = StumpJokeWithCustomFieldForm() self.assertEqual(f.fields['custom'].queryset, 42) def test_fields_for_model_applies_limit_choices_to(self): fields = fields_for_model(StumpJoke, ['has_fooled_today']) self.assertSequenceEqual(fields['has_fooled_today'].queryset, [self.threepwood]) def test_callable_called_each_time_form_is_instantiated(self): field = StumpJokeForm.base_fields['most_recently_fooled'] with mock.patch.object(field, 'limit_choices_to') as today_callable_dict: StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 1) StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 2) StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 3) class FormFieldCallbackTests(SimpleTestCase): def test_baseform_with_widgets_in_meta(self): """Regression for #13095: Using base forms with widgets defined in Meta should not raise errors.""" widget = forms.Textarea() class BaseForm(forms.ModelForm): class Meta: model = Person widgets = {'name': widget} fields = "__all__" Form = modelform_factory(Person, form=BaseForm) self.assertIsInstance(Form.base_fields['name'].widget, forms.Textarea) def test_factory_with_widget_argument(self): """ Regression for #15315: modelform_factory should accept widgets argument """ widget = forms.Textarea() # Without a widget should not set the widget to textarea Form = modelform_factory(Person, fields="__all__") self.assertNotEqual(Form.base_fields['name'].widget.__class__, forms.Textarea) # With a widget should not set the widget to textarea Form = modelform_factory(Person, fields="__all__", widgets={'name': widget}) self.assertEqual(Form.base_fields['name'].widget.__class__, forms.Textarea) def test_modelform_factory_without_fields(self): """ Regression for #19733 """ message = ( "Calling modelform_factory without defining 'fields' or 'exclude' " "explicitly is prohibited." ) with self.assertRaisesMessage(ImproperlyConfigured, message): modelform_factory(Person) def test_modelform_factory_with_all_fields(self): """ Regression for #19733 """ form = modelform_factory(Person, fields="__all__") self.assertEqual(list(form.base_fields), ["name"]) def test_custom_callback(self): """A custom formfield_callback is used if provided""" callback_args = [] def callback(db_field, **kwargs): callback_args.append((db_field, kwargs)) return db_field.formfield(**kwargs) widget = forms.Textarea() class BaseForm(forms.ModelForm): class Meta: model = Person widgets = {'name': widget} fields = "__all__" modelform_factory(Person, form=BaseForm, formfield_callback=callback) id_field, name_field = Person._meta.fields self.assertEqual(callback_args, [(id_field, {}), (name_field, {'widget': widget})]) def test_bad_callback(self): # A bad callback provided by user still gives an error with self.assertRaises(TypeError): modelform_factory(Person, fields="__all__", formfield_callback='not a function or callable') def test_inherit_after_custom_callback(self): def callback(db_field, **kwargs): if isinstance(db_field, models.CharField): return forms.CharField(widget=forms.Textarea) return db_field.formfield(**kwargs) class BaseForm(forms.ModelForm): class Meta: model = Person fields = '__all__' NewForm = modelform_factory(Person, form=BaseForm, formfield_callback=callback) class InheritedForm(NewForm): pass for name in NewForm.base_fields: self.assertEqual( type(InheritedForm.base_fields[name].widget), type(NewForm.base_fields[name].widget) ) class LocalizedModelFormTest(TestCase): def test_model_form_applies_localize_to_some_fields(self): class PartiallyLocalizedTripleForm(forms.ModelForm): class Meta: model = Triple localized_fields = ('left', 'right',) fields = '__all__' f = PartiallyLocalizedTripleForm({'left': 10, 'middle': 10, 'right': 10}) self.assertTrue(f.is_valid()) self.assertTrue(f.fields['left'].localize) self.assertFalse(f.fields['middle'].localize) self.assertTrue(f.fields['right'].localize) def test_model_form_applies_localize_to_all_fields(self): class FullyLocalizedTripleForm(forms.ModelForm): class Meta: model = Triple localized_fields = '__all__' fields = '__all__' f = FullyLocalizedTripleForm({'left': 10, 'middle': 10, 'right': 10}) self.assertTrue(f.is_valid()) self.assertTrue(f.fields['left'].localize) self.assertTrue(f.fields['middle'].localize) self.assertTrue(f.fields['right'].localize) def test_model_form_refuses_arbitrary_string(self): msg = ( "BrokenLocalizedTripleForm.Meta.localized_fields " "cannot be a string. Did you mean to type: ('foo',)?" ) with self.assertRaisesMessage(TypeError, msg): class BrokenLocalizedTripleForm(forms.ModelForm): class Meta: model = Triple localized_fields = "foo" class CustomMetaclass(ModelFormMetaclass): def __new__(cls, name, bases, attrs): new = super().__new__(cls, name, bases, attrs) new.base_fields = {} return new class CustomMetaclassForm(forms.ModelForm, metaclass=CustomMetaclass): pass class CustomMetaclassTestCase(SimpleTestCase): def test_modelform_factory_metaclass(self): new_cls = modelform_factory(Person, fields="__all__", form=CustomMetaclassForm) self.assertEqual(new_cls.base_fields, {}) class StrictAssignmentTests(SimpleTestCase): """ Should a model do anything special with __setattr__() or descriptors which raise a ValidationError, a model form should catch the error (#24706). """ def test_setattr_raises_validation_error_field_specific(self): """ A model ValidationError using the dict form should put the error message into the correct key of form.errors. """ form_class = modelform_factory(model=StrictAssignmentFieldSpecific, fields=['title']) form = form_class(data={'title': 'testing setattr'}, files=None) # This line turns on the ValidationError; it avoids the model erroring # when its own __init__() is called when creating form.instance. form.instance._should_error = True self.assertFalse(form.is_valid()) self.assertEqual(form.errors, { 'title': ['Cannot set attribute', 'This field cannot be blank.'] }) def test_setattr_raises_validation_error_non_field(self): """ A model ValidationError not using the dict form should put the error message into __all__ (i.e. non-field errors) on the form. """ form_class = modelform_factory(model=StrictAssignmentAll, fields=['title']) form = form_class(data={'title': 'testing setattr'}, files=None) # This line turns on the ValidationError; it avoids the model erroring # when its own __init__() is called when creating form.instance. form.instance._should_error = True self.assertFalse(form.is_valid()) self.assertEqual(form.errors, { '__all__': ['Cannot set attribute'], 'title': ['This field cannot be blank.'] }) class ModelToDictTests(TestCase): def test_many_to_many(self): """Data for a ManyToManyField is a list rather than a lazy QuerySet.""" blue = Colour.objects.create(name='blue') red = Colour.objects.create(name='red') item = ColourfulItem.objects.create() item.colours.set([blue]) data = model_to_dict(item)['colours'] self.assertEqual(data, [blue]) item.colours.set([red]) # If data were a QuerySet, it would be reevaluated here and give "red" # instead of the original value. self.assertEqual(data, [blue])
f550eead7fbcf3be16d187ae1f8b462f11eb370bf9778fbe60669521b222f40e
from django import forms from django.core.exceptions import ValidationError from django.test import TestCase from .models import UUIDPK class UUIDPKForm(forms.ModelForm): class Meta: model = UUIDPK fields = '__all__' class ModelFormBaseTest(TestCase): def test_create_save_error(self): form = UUIDPKForm({}) self.assertFalse(form.is_valid()) msg = "The UUIDPK could not be created because the data didn't validate." with self.assertRaisesMessage(ValueError, msg): form.save() def test_update_save_error(self): obj = UUIDPK.objects.create(name='foo') form = UUIDPKForm({}, instance=obj) self.assertFalse(form.is_valid()) msg = "The UUIDPK could not be changed because the data didn't validate." with self.assertRaisesMessage(ValueError, msg): form.save() def test_model_multiple_choice_field_uuid_pk(self): f = forms.ModelMultipleChoiceField(UUIDPK.objects.all()) with self.assertRaisesMessage(ValidationError, '“invalid_uuid” is not a valid UUID.'): f.clean(['invalid_uuid'])
4258000cead2fe202e0173b98eac8e729514de07308cd2f3f0733bd483bba921
import os import pathlib from unittest import mock, skipUnless from django.conf import settings from django.contrib.gis.geoip2 import HAS_GEOIP2 from django.contrib.gis.geos import GEOSGeometry from django.test import SimpleTestCase if HAS_GEOIP2: from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception # Note: Requires both the GeoIP country and city datasets. # The GEOIP_DATA path should be the only setting set (the directory # should contain links or the actual database files 'GeoLite2-City.mmdb' and # 'GeoLite2-City.mmdb'. @skipUnless( HAS_GEOIP2 and getattr(settings, "GEOIP_PATH", None), "GeoIP is required along with the GEOIP_PATH setting." ) class GeoIPTest(SimpleTestCase): addr = '75.41.39.1' fqdn = 'tmc.edu' def test01_init(self): "GeoIP initialization." g1 = GeoIP2() # Everything inferred from GeoIP path path = settings.GEOIP_PATH g2 = GeoIP2(path, 0) # Passing in data path explicitly. g3 = GeoIP2.open(path, 0) # MaxMind Python API syntax. # path accepts str and pathlib.Path. if isinstance(path, str): g4 = GeoIP2(pathlib.Path(path)) else: g4 = GeoIP2(str(path)) for g in (g1, g2, g3, g4): self.assertTrue(g._country) self.assertTrue(g._city) # Only passing in the location of one database. city = os.path.join(path, 'GeoLite2-City.mmdb') cntry = os.path.join(path, 'GeoLite2-Country.mmdb') g4 = GeoIP2(city, country='') self.assertIsNone(g4._country) g5 = GeoIP2(cntry, city='') self.assertIsNone(g5._city) # Improper parameters. bad_params = (23, 'foo', 15.23) for bad in bad_params: with self.assertRaises(GeoIP2Exception): GeoIP2(cache=bad) if isinstance(bad, str): e = GeoIP2Exception else: e = TypeError with self.assertRaises(e): GeoIP2(bad, 0) def test_no_database_file(self): invalid_path = os.path.join(os.path.dirname(__file__), 'data') msg = 'Could not load a database from %s.' % invalid_path with self.assertRaisesMessage(GeoIP2Exception, msg): GeoIP2(invalid_path) def test02_bad_query(self): "GeoIP query parameter checking." cntry_g = GeoIP2(city='<foo>') # No city database available, these calls should fail. with self.assertRaises(GeoIP2Exception): cntry_g.city('tmc.edu') with self.assertRaises(GeoIP2Exception): cntry_g.coords('tmc.edu') # Non-string query should raise TypeError with self.assertRaises(TypeError): cntry_g.country_code(17) with self.assertRaises(TypeError): cntry_g.country_name(GeoIP2) @mock.patch('socket.gethostbyname') def test03_country(self, gethostbyname): "GeoIP country querying methods." gethostbyname.return_value = '128.249.1.1' g = GeoIP2(city='<foo>') for query in (self.fqdn, self.addr): self.assertEqual( 'US', g.country_code(query), 'Failed for func country_code and query %s' % query ) self.assertEqual( 'United States', g.country_name(query), 'Failed for func country_name and query %s' % query ) self.assertEqual( {'country_code': 'US', 'country_name': 'United States'}, g.country(query) ) @mock.patch('socket.gethostbyname') def test04_city(self, gethostbyname): "GeoIP city querying methods." gethostbyname.return_value = '75.41.39.1' g = GeoIP2(country='<foo>') for query in (self.fqdn, self.addr): # Country queries should still work. self.assertEqual( 'US', g.country_code(query), 'Failed for func country_code and query %s' % query ) self.assertEqual( 'United States', g.country_name(query), 'Failed for func country_name and query %s' % query ) self.assertEqual( {'country_code': 'US', 'country_name': 'United States'}, g.country(query) ) # City information dictionary. d = g.city(query) self.assertEqual('NA', d['continent_code']) self.assertEqual('North America', d['continent_name']) self.assertEqual('US', d['country_code']) self.assertEqual('Dallas', d['city']) self.assertEqual('TX', d['region']) self.assertEqual('America/Chicago', d['time_zone']) self.assertFalse(d['is_in_european_union']) geom = g.geos(query) self.assertIsInstance(geom, GEOSGeometry) for e1, e2 in (geom.tuple, g.coords(query), g.lon_lat(query), g.lat_lon(query)): self.assertIsInstance(e1, float) self.assertIsInstance(e2, float) def test06_ipv6_query(self): "GeoIP can lookup IPv6 addresses." g = GeoIP2() d = g.city('2002:81ed:c9a5::81ed:c9a5') # IPv6 address for www.nhm.ku.edu self.assertEqual('US', d['country_code']) self.assertEqual('Lawrence', d['city']) self.assertEqual('KS', d['region']) def test_repr(self): path = settings.GEOIP_PATH g = GeoIP2(path=path) meta = g._reader.metadata() version = '%s.%s' % (meta.binary_format_major_version, meta.binary_format_minor_version) country_path = g._country_file city_path = g._city_file expected = '<GeoIP2 [v%(version)s] _country_file="%(country)s", _city_file="%(city)s">' % { 'version': version, 'country': country_path, 'city': city_path, } self.assertEqual(repr(g), expected) @mock.patch('socket.gethostbyname', return_value='expected') def test_check_query(self, gethostbyname): g = GeoIP2() self.assertEqual(g._check_query('127.0.0.1'), '127.0.0.1') self.assertEqual(g._check_query('2002:81ed:c9a5::81ed:c9a5'), '2002:81ed:c9a5::81ed:c9a5') self.assertEqual(g._check_query('invalid-ip-address'), 'expected')
976a2a4ed8b57c591b6a7e61c7e775e54285e0783b702df6ef2cd15cb547af67
import re from django.contrib.gis import forms from django.contrib.gis.forms import BaseGeometryWidget, OpenLayersWidget from django.contrib.gis.geos import GEOSGeometry from django.forms import ValidationError from django.test import SimpleTestCase, override_settings from django.utils.html import escape class GeometryFieldTest(SimpleTestCase): def test_init(self): "Testing GeometryField initialization with defaults." fld = forms.GeometryField() for bad_default in ('blah', 3, 'FoO', None, 0): with self.subTest(bad_default=bad_default): with self.assertRaises(ValidationError): fld.clean(bad_default) def test_srid(self): "Testing GeometryField with a SRID set." # Input that doesn't specify the SRID is assumed to be in the SRID # of the input field. fld = forms.GeometryField(srid=4326) geom = fld.clean('POINT(5 23)') self.assertEqual(4326, geom.srid) # Making the field in a different SRID from that of the geometry, and # asserting it transforms. fld = forms.GeometryField(srid=32140) tol = 0.0000001 xform_geom = GEOSGeometry('POINT (951640.547328465 4219369.26171664)', srid=32140) # The cleaned geometry is transformed to 32140 (the widget map_srid is 3857). cleaned_geom = fld.clean('SRID=3857;POINT (-10615777.40976205 3473169.895707852)') self.assertEqual(cleaned_geom.srid, 32140) self.assertTrue(xform_geom.equals_exact(cleaned_geom, tol)) def test_null(self): "Testing GeometryField's handling of null (None) geometries." # Form fields, by default, are required (`required=True`) fld = forms.GeometryField() with self.assertRaisesMessage(forms.ValidationError, "No geometry value provided."): fld.clean(None) # This will clean None as a geometry (See #10660). fld = forms.GeometryField(required=False) self.assertIsNone(fld.clean(None)) def test_geom_type(self): "Testing GeometryField's handling of different geometry types." # By default, all geometry types are allowed. fld = forms.GeometryField() for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'): with self.subTest(wkt=wkt): # to_python() uses the SRID of OpenLayersWidget if the # converted value doesn't have an SRID. self.assertEqual(GEOSGeometry(wkt, srid=fld.widget.map_srid), fld.clean(wkt)) pnt_fld = forms.GeometryField(geom_type='POINT') self.assertEqual(GEOSGeometry('POINT(5 23)', srid=pnt_fld.widget.map_srid), pnt_fld.clean('POINT(5 23)')) # a WKT for any other geom_type will be properly transformed by `to_python` self.assertEqual( GEOSGeometry('LINESTRING(0 0, 1 1)', srid=pnt_fld.widget.map_srid), pnt_fld.to_python('LINESTRING(0 0, 1 1)') ) # but rejected by `clean` with self.assertRaises(forms.ValidationError): pnt_fld.clean('LINESTRING(0 0, 1 1)') def test_to_python(self): """ to_python() either returns a correct GEOSGeometry object or a ValidationError. """ good_inputs = [ 'POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)', ] bad_inputs = [ 'POINT(5)', 'MULTI POLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'BLAH(0 0, 1 1)', '{"type": "FeatureCollection", "features": [' '{"geometry": {"type": "Point", "coordinates": [508375, 148905]}, "type": "Feature"}]}', ] fld = forms.GeometryField() # to_python returns the same GEOSGeometry for a WKT for geo_input in good_inputs: with self.subTest(geo_input=geo_input): self.assertEqual(GEOSGeometry(geo_input, srid=fld.widget.map_srid), fld.to_python(geo_input)) # but raises a ValidationError for any other string for geo_input in bad_inputs: with self.subTest(geo_input=geo_input): with self.assertRaises(forms.ValidationError): fld.to_python(geo_input) def test_to_python_different_map_srid(self): f = forms.GeometryField(widget=OpenLayersWidget) json = '{ "type": "Point", "coordinates": [ 5.0, 23.0 ] }' self.assertEqual(GEOSGeometry('POINT(5 23)', srid=f.widget.map_srid), f.to_python(json)) def test_field_with_text_widget(self): class PointForm(forms.Form): pt = forms.PointField(srid=4326, widget=forms.TextInput) form = PointForm() cleaned_pt = form.fields['pt'].clean('POINT(5 23)') self.assertEqual(cleaned_pt, GEOSGeometry('POINT(5 23)', srid=4326)) self.assertEqual(4326, cleaned_pt.srid) with self.assertRaisesMessage(ValidationError, 'Invalid geometry value.'): form.fields['pt'].clean('POINT(5)') point = GEOSGeometry('SRID=4326;POINT(5 23)') form = PointForm(data={'pt': 'POINT(5 23)'}, initial={'pt': point}) self.assertFalse(form.has_changed()) def test_field_string_value(self): """ Initialization of a geometry field with a valid/empty/invalid string. Only the invalid string should trigger an error log entry. """ class PointForm(forms.Form): pt1 = forms.PointField(srid=4326) pt2 = forms.PointField(srid=4326) pt3 = forms.PointField(srid=4326) form = PointForm({ 'pt1': 'SRID=4326;POINT(7.3 44)', # valid 'pt2': '', # empty 'pt3': 'PNT(0)', # invalid }) with self.assertLogs('django.contrib.gis', 'ERROR') as logger_calls: output = str(form) # The first point can't use assertInHTML() due to non-deterministic # ordering of the rendered dictionary. pt1_serialized = re.search(r'<textarea [^>]*>({[^<]+})<', output).groups()[0] pt1_json = pt1_serialized.replace('&quot;', '"') pt1_expected = GEOSGeometry(form.data['pt1']).transform(3857, clone=True) self.assertJSONEqual(pt1_json, pt1_expected.json) self.assertInHTML( '<textarea id="id_pt2" class="vSerializedField required" cols="150"' ' rows="10" name="pt2"></textarea>', output ) self.assertInHTML( '<textarea id="id_pt3" class="vSerializedField required" cols="150"' ' rows="10" name="pt3"></textarea>', output ) # Only the invalid PNT(0) triggers an error log entry. # Deserialization is called in form clean and in widget rendering. self.assertEqual(len(logger_calls.records), 2) self.assertEqual( logger_calls.records[0].getMessage(), "Error creating geometry from value 'PNT(0)' (String input " "unrecognized as WKT EWKT, and HEXEWKB.)" ) class SpecializedFieldTest(SimpleTestCase): def setUp(self): self.geometries = { 'point': GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)"), 'multipoint': GEOSGeometry("SRID=4326;MULTIPOINT(" "(13.18634033203125 14.504356384277344)," "(13.207969665527 14.490966796875)," "(13.177070617675 14.454917907714))"), 'linestring': GEOSGeometry("SRID=4326;LINESTRING(" "-8.26171875 -0.52734375," "-7.734375 4.21875," "6.85546875 3.779296875," "5.44921875 -3.515625)"), 'multilinestring': GEOSGeometry("SRID=4326;MULTILINESTRING(" "(-16.435546875 -2.98828125," "-17.2265625 2.98828125," "-0.703125 3.515625," "-1.494140625 -3.33984375)," "(-8.0859375 -5.9765625," "8.525390625 -8.7890625," "12.392578125 -0.87890625," "10.01953125 7.646484375))"), 'polygon': GEOSGeometry("SRID=4326;POLYGON(" "(-1.669921875 6.240234375," "-3.8671875 -0.615234375," "5.9765625 -3.955078125," "18.193359375 3.955078125," "9.84375 9.4921875," "-1.669921875 6.240234375))"), 'multipolygon': GEOSGeometry("SRID=4326;MULTIPOLYGON(" "((-17.578125 13.095703125," "-17.2265625 10.8984375," "-13.974609375 10.1953125," "-13.359375 12.744140625," "-15.732421875 13.7109375," "-17.578125 13.095703125))," "((-8.525390625 5.537109375," "-8.876953125 2.548828125," "-5.888671875 1.93359375," "-5.09765625 4.21875," "-6.064453125 6.240234375," "-8.525390625 5.537109375)))"), 'geometrycollection': GEOSGeometry("SRID=4326;GEOMETRYCOLLECTION(" "POINT(5.625 -0.263671875)," "POINT(6.767578125 -3.603515625)," "POINT(8.525390625 0.087890625)," "POINT(8.0859375 -2.13134765625)," "LINESTRING(" "6.273193359375 -1.175537109375," "5.77880859375 -1.812744140625," "7.27294921875 -2.230224609375," "7.657470703125 -1.25244140625))"), } def assertMapWidget(self, form_instance): """ Make sure the MapWidget js is passed in the form media and a MapWidget is actually created """ self.assertTrue(form_instance.is_valid()) rendered = form_instance.as_p() self.assertIn('new MapWidget(options);', rendered) self.assertIn('map_srid: 3857,', rendered) self.assertIn('gis/js/OLMapWidget.js', str(form_instance.media)) def assertTextarea(self, geom, rendered): """Makes sure the wkt and a textarea are in the content""" self.assertIn('<textarea ', rendered) self.assertIn('required', rendered) ogr = geom.ogr ogr.transform(3857) self.assertIn(escape(ogr.json), rendered) # map_srid in openlayers.html template must not be localized. @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True) def test_pointfield(self): class PointForm(forms.Form): p = forms.PointField() geom = self.geometries['point'] form = PointForm(data={'p': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(PointForm().is_valid()) invalid = PointForm(data={'p': 'some invalid geom'}) self.assertFalse(invalid.is_valid()) self.assertIn('Invalid geometry value', str(invalid.errors)) for invalid in [geo for key, geo in self.geometries.items() if key != 'point']: self.assertFalse(PointForm(data={'p': invalid.wkt}).is_valid()) def test_multipointfield(self): class PointForm(forms.Form): p = forms.MultiPointField() geom = self.geometries['multipoint'] form = PointForm(data={'p': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(PointForm().is_valid()) for invalid in [geo for key, geo in self.geometries.items() if key != 'multipoint']: self.assertFalse(PointForm(data={'p': invalid.wkt}).is_valid()) def test_linestringfield(self): class LineStringForm(forms.Form): f = forms.LineStringField() geom = self.geometries['linestring'] form = LineStringForm(data={'f': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(LineStringForm().is_valid()) for invalid in [geo for key, geo in self.geometries.items() if key != 'linestring']: self.assertFalse(LineStringForm(data={'p': invalid.wkt}).is_valid()) def test_multilinestringfield(self): class LineStringForm(forms.Form): f = forms.MultiLineStringField() geom = self.geometries['multilinestring'] form = LineStringForm(data={'f': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(LineStringForm().is_valid()) for invalid in [geo for key, geo in self.geometries.items() if key != 'multilinestring']: self.assertFalse(LineStringForm(data={'p': invalid.wkt}).is_valid()) def test_polygonfield(self): class PolygonForm(forms.Form): p = forms.PolygonField() geom = self.geometries['polygon'] form = PolygonForm(data={'p': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(PolygonForm().is_valid()) for invalid in [geo for key, geo in self.geometries.items() if key != 'polygon']: self.assertFalse(PolygonForm(data={'p': invalid.wkt}).is_valid()) def test_multipolygonfield(self): class PolygonForm(forms.Form): p = forms.MultiPolygonField() geom = self.geometries['multipolygon'] form = PolygonForm(data={'p': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(PolygonForm().is_valid()) for invalid in [geo for key, geo in self.geometries.items() if key != 'multipolygon']: self.assertFalse(PolygonForm(data={'p': invalid.wkt}).is_valid()) def test_geometrycollectionfield(self): class GeometryForm(forms.Form): g = forms.GeometryCollectionField() geom = self.geometries['geometrycollection'] form = GeometryForm(data={'g': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(GeometryForm().is_valid()) for invalid in [geo for key, geo in self.geometries.items() if key != 'geometrycollection']: self.assertFalse(GeometryForm(data={'g': invalid.wkt}).is_valid()) class OSMWidgetTest(SimpleTestCase): def setUp(self): self.geometries = { 'point': GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)"), } def test_osm_widget(self): class PointForm(forms.Form): p = forms.PointField(widget=forms.OSMWidget) geom = self.geometries['point'] form = PointForm(data={'p': geom}) rendered = form.as_p() self.assertIn("ol.source.OSM()", rendered) self.assertIn("id: 'id_p',", rendered) def test_default_lat_lon(self): self.assertEqual(forms.OSMWidget.default_lon, 5) self.assertEqual(forms.OSMWidget.default_lat, 47) self.assertEqual(forms.OSMWidget.default_zoom, 12) class PointForm(forms.Form): p = forms.PointField( widget=forms.OSMWidget(attrs={ 'default_lon': 20, 'default_lat': 30, 'default_zoom': 17, }), ) form = PointForm() rendered = form.as_p() self.assertIn("options['default_lon'] = 20;", rendered) self.assertIn("options['default_lat'] = 30;", rendered) self.assertIn("options['default_zoom'] = 17;", rendered) class GeometryWidgetTests(SimpleTestCase): def test_get_context_attrs(self): """The Widget.get_context() attrs argument overrides self.attrs.""" widget = BaseGeometryWidget(attrs={'geom_type': 'POINT'}) context = widget.get_context('point', None, attrs={'geom_type': 'POINT2'}) self.assertEqual(context['geom_type'], 'POINT2') def test_subwidgets(self): widget = forms.BaseGeometryWidget() self.assertEqual( list(widget.subwidgets('name', 'value')), [{ 'is_hidden': False, 'attrs': { 'map_srid': 4326, 'map_width': 600, 'geom_type': 'GEOMETRY', 'map_height': 400, 'display_raw': False, }, 'name': 'name', 'template_name': '', 'value': 'value', 'required': False, }] ) def test_custom_serialization_widget(self): class CustomGeometryWidget(forms.BaseGeometryWidget): template_name = 'gis/openlayers.html' deserialize_called = 0 def serialize(self, value): return value.json if value else '' def deserialize(self, value): self.deserialize_called += 1 return GEOSGeometry(value) class PointForm(forms.Form): p = forms.PointField(widget=CustomGeometryWidget) point = GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)") form = PointForm(data={'p': point}) self.assertIn(escape(point.json), form.as_p()) CustomGeometryWidget.called = 0 widget = form.fields['p'].widget # Force deserialize use due to a string value self.assertIn(escape(point.json), widget.render('p', point.json)) self.assertEqual(widget.deserialize_called, 1) form = PointForm(data={'p': point.json}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['p'].srid, 4326)
5c24869b73905595c87c8e3c3cd3fa5c68576d7857ade45f139ce584e7e73659
from math import ceil from django.db import IntegrityError, connection, models from django.db.models.deletion import Collector from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from .models import ( MR, A, Avatar, Base, Child, HiddenUser, HiddenUserProfile, M, M2MFrom, M2MTo, MRNull, Origin, Parent, R, RChild, RChildChild, Referrer, S, T, User, create_a, get_default_r, ) class OnDeleteTests(TestCase): def setUp(self): self.DEFAULT = get_default_r() def test_auto(self): a = create_a('auto') a.auto.delete() self.assertFalse(A.objects.filter(name='auto').exists()) def test_non_callable(self): msg = 'on_delete must be callable.' with self.assertRaisesMessage(TypeError, msg): models.ForeignKey('self', on_delete=None) with self.assertRaisesMessage(TypeError, msg): models.OneToOneField('self', on_delete=None) def test_auto_nullable(self): a = create_a('auto_nullable') a.auto_nullable.delete() self.assertFalse(A.objects.filter(name='auto_nullable').exists()) def test_setvalue(self): a = create_a('setvalue') a.setvalue.delete() a = A.objects.get(pk=a.pk) self.assertEqual(self.DEFAULT, a.setvalue.pk) def test_setnull(self): a = create_a('setnull') a.setnull.delete() a = A.objects.get(pk=a.pk) self.assertIsNone(a.setnull) def test_setdefault(self): a = create_a('setdefault') a.setdefault.delete() a = A.objects.get(pk=a.pk) self.assertEqual(self.DEFAULT, a.setdefault.pk) def test_setdefault_none(self): a = create_a('setdefault_none') a.setdefault_none.delete() a = A.objects.get(pk=a.pk) self.assertIsNone(a.setdefault_none) def test_cascade(self): a = create_a('cascade') a.cascade.delete() self.assertFalse(A.objects.filter(name='cascade').exists()) def test_cascade_nullable(self): a = create_a('cascade_nullable') a.cascade_nullable.delete() self.assertFalse(A.objects.filter(name='cascade_nullable').exists()) def test_protect(self): a = create_a('protect') msg = ( "Cannot delete some instances of model 'R' because they are " "referenced through a protected foreign key: 'A.protect'" ) with self.assertRaisesMessage(IntegrityError, msg): a.protect.delete() def test_do_nothing(self): # Testing DO_NOTHING is a bit harder: It would raise IntegrityError for a normal model, # so we connect to pre_delete and set the fk to a known value. replacement_r = R.objects.create() def check_do_nothing(sender, **kwargs): obj = kwargs['instance'] obj.donothing_set.update(donothing=replacement_r) models.signals.pre_delete.connect(check_do_nothing) a = create_a('do_nothing') a.donothing.delete() a = A.objects.get(pk=a.pk) self.assertEqual(replacement_r, a.donothing) models.signals.pre_delete.disconnect(check_do_nothing) def test_do_nothing_qscount(self): """ A models.DO_NOTHING relation doesn't trigger a query. """ b = Base.objects.create() with self.assertNumQueries(1): # RelToBase should not be queried. b.delete() self.assertEqual(Base.objects.count(), 0) def test_inheritance_cascade_up(self): child = RChild.objects.create() child.delete() self.assertFalse(R.objects.filter(pk=child.pk).exists()) def test_inheritance_cascade_down(self): child = RChild.objects.create() parent = child.r_ptr parent.delete() self.assertFalse(RChild.objects.filter(pk=child.pk).exists()) def test_cascade_from_child(self): a = create_a('child') a.child.delete() self.assertFalse(A.objects.filter(name='child').exists()) self.assertFalse(R.objects.filter(pk=a.child_id).exists()) def test_cascade_from_parent(self): a = create_a('child') R.objects.get(pk=a.child_id).delete() self.assertFalse(A.objects.filter(name='child').exists()) self.assertFalse(RChild.objects.filter(pk=a.child_id).exists()) def test_setnull_from_child(self): a = create_a('child_setnull') a.child_setnull.delete() self.assertFalse(R.objects.filter(pk=a.child_setnull_id).exists()) a = A.objects.get(pk=a.pk) self.assertIsNone(a.child_setnull) def test_setnull_from_parent(self): a = create_a('child_setnull') R.objects.get(pk=a.child_setnull_id).delete() self.assertFalse(RChild.objects.filter(pk=a.child_setnull_id).exists()) a = A.objects.get(pk=a.pk) self.assertIsNone(a.child_setnull) def test_o2o_setnull(self): a = create_a('o2o_setnull') a.o2o_setnull.delete() a = A.objects.get(pk=a.pk) self.assertIsNone(a.o2o_setnull) class DeletionTests(TestCase): def test_m2m(self): m = M.objects.create() r = R.objects.create() MR.objects.create(m=m, r=r) r.delete() self.assertFalse(MR.objects.exists()) r = R.objects.create() MR.objects.create(m=m, r=r) m.delete() self.assertFalse(MR.objects.exists()) m = M.objects.create() r = R.objects.create() m.m2m.add(r) r.delete() through = M._meta.get_field('m2m').remote_field.through self.assertFalse(through.objects.exists()) r = R.objects.create() m.m2m.add(r) m.delete() self.assertFalse(through.objects.exists()) m = M.objects.create() r = R.objects.create() MRNull.objects.create(m=m, r=r) r.delete() self.assertFalse(not MRNull.objects.exists()) self.assertFalse(m.m2m_through_null.exists()) def test_bulk(self): s = S.objects.create(r=R.objects.create()) for i in range(2 * GET_ITERATOR_CHUNK_SIZE): T.objects.create(s=s) # 1 (select related `T` instances) # + 1 (select related `U` instances) # + 2 (delete `T` instances in batches) # + 1 (delete `s`) self.assertNumQueries(5, s.delete) self.assertFalse(S.objects.exists()) def test_instance_update(self): deleted = [] related_setnull_sets = [] def pre_delete(sender, **kwargs): obj = kwargs['instance'] deleted.append(obj) if isinstance(obj, R): related_setnull_sets.append([a.pk for a in obj.setnull_set.all()]) models.signals.pre_delete.connect(pre_delete) a = create_a('update_setnull') a.setnull.delete() a = create_a('update_cascade') a.cascade.delete() for obj in deleted: self.assertIsNone(obj.pk) for pk_list in related_setnull_sets: for a in A.objects.filter(id__in=pk_list): self.assertIsNone(a.setnull) models.signals.pre_delete.disconnect(pre_delete) def test_deletion_order(self): pre_delete_order = [] post_delete_order = [] def log_post_delete(sender, **kwargs): pre_delete_order.append((sender, kwargs['instance'].pk)) def log_pre_delete(sender, **kwargs): post_delete_order.append((sender, kwargs['instance'].pk)) models.signals.post_delete.connect(log_post_delete) models.signals.pre_delete.connect(log_pre_delete) r = R.objects.create(pk=1) s1 = S.objects.create(pk=1, r=r) s2 = S.objects.create(pk=2, r=r) T.objects.create(pk=1, s=s1) T.objects.create(pk=2, s=s2) RChild.objects.create(r_ptr=r) r.delete() self.assertEqual( pre_delete_order, [(T, 2), (T, 1), (RChild, 1), (S, 2), (S, 1), (R, 1)] ) self.assertEqual( post_delete_order, [(T, 1), (T, 2), (RChild, 1), (S, 1), (S, 2), (R, 1)] ) models.signals.post_delete.disconnect(log_post_delete) models.signals.pre_delete.disconnect(log_pre_delete) def test_relational_post_delete_signals_happen_before_parent_object(self): deletions = [] def log_post_delete(instance, **kwargs): self.assertTrue(R.objects.filter(pk=instance.r_id)) self.assertIs(type(instance), S) deletions.append(instance.id) r = R.objects.create(pk=1) S.objects.create(pk=1, r=r) models.signals.post_delete.connect(log_post_delete, sender=S) try: r.delete() finally: models.signals.post_delete.disconnect(log_post_delete) self.assertEqual(len(deletions), 1) self.assertEqual(deletions[0], 1) @skipUnlessDBFeature("can_defer_constraint_checks") def test_can_defer_constraint_checks(self): u = User.objects.create( avatar=Avatar.objects.create() ) a = Avatar.objects.get(pk=u.avatar_id) # 1 query to find the users for the avatar. # 1 query to delete the user # 1 query to delete the avatar # The important thing is that when we can defer constraint checks there # is no need to do an UPDATE on User.avatar to null it out. # Attach a signal to make sure we will not do fast_deletes. calls = [] def noop(*args, **kwargs): calls.append('') models.signals.post_delete.connect(noop, sender=User) self.assertNumQueries(3, a.delete) self.assertFalse(User.objects.exists()) self.assertFalse(Avatar.objects.exists()) self.assertEqual(len(calls), 1) models.signals.post_delete.disconnect(noop, sender=User) @skipIfDBFeature("can_defer_constraint_checks") def test_cannot_defer_constraint_checks(self): u = User.objects.create( avatar=Avatar.objects.create() ) # Attach a signal to make sure we will not do fast_deletes. calls = [] def noop(*args, **kwargs): calls.append('') models.signals.post_delete.connect(noop, sender=User) a = Avatar.objects.get(pk=u.avatar_id) # The below doesn't make sense... Why do we need to null out # user.avatar if we are going to delete the user immediately after it, # and there are no more cascades. # 1 query to find the users for the avatar. # 1 query to delete the user # 1 query to null out user.avatar, because we can't defer the constraint # 1 query to delete the avatar self.assertNumQueries(4, a.delete) self.assertFalse(User.objects.exists()) self.assertFalse(Avatar.objects.exists()) self.assertEqual(len(calls), 1) models.signals.post_delete.disconnect(noop, sender=User) def test_hidden_related(self): r = R.objects.create() h = HiddenUser.objects.create(r=r) HiddenUserProfile.objects.create(user=h) r.delete() self.assertEqual(HiddenUserProfile.objects.count(), 0) def test_large_delete(self): TEST_SIZE = 2000 objs = [Avatar() for i in range(0, TEST_SIZE)] Avatar.objects.bulk_create(objs) # Calculate the number of queries needed. batch_size = connection.ops.bulk_batch_size(['pk'], objs) # The related fetches are done in batches. batches = ceil(len(objs) / batch_size) # One query for Avatar.objects.all() and then one related fast delete for # each batch. fetches_to_mem = 1 + batches # The Avatar objects are going to be deleted in batches of GET_ITERATOR_CHUNK_SIZE queries = fetches_to_mem + TEST_SIZE // GET_ITERATOR_CHUNK_SIZE self.assertNumQueries(queries, Avatar.objects.all().delete) self.assertFalse(Avatar.objects.exists()) def test_large_delete_related(self): TEST_SIZE = 2000 s = S.objects.create(r=R.objects.create()) for i in range(TEST_SIZE): T.objects.create(s=s) batch_size = max(connection.ops.bulk_batch_size(['pk'], range(TEST_SIZE)), 1) # TEST_SIZE / batch_size (select related `T` instances) # + 1 (select related `U` instances) # + TEST_SIZE / GET_ITERATOR_CHUNK_SIZE (delete `T` instances in batches) # + 1 (delete `s`) expected_num_queries = ceil(TEST_SIZE / batch_size) expected_num_queries += ceil(TEST_SIZE / GET_ITERATOR_CHUNK_SIZE) + 2 self.assertNumQueries(expected_num_queries, s.delete) self.assertFalse(S.objects.exists()) self.assertFalse(T.objects.exists()) def test_delete_with_keeping_parents(self): child = RChild.objects.create() parent_id = child.r_ptr_id child.delete(keep_parents=True) self.assertFalse(RChild.objects.filter(id=child.id).exists()) self.assertTrue(R.objects.filter(id=parent_id).exists()) def test_delete_with_keeping_parents_relationships(self): child = RChild.objects.create() parent_id = child.r_ptr_id parent_referent_id = S.objects.create(r=child.r_ptr).pk child.delete(keep_parents=True) self.assertFalse(RChild.objects.filter(id=child.id).exists()) self.assertTrue(R.objects.filter(id=parent_id).exists()) self.assertTrue(S.objects.filter(pk=parent_referent_id).exists()) childchild = RChildChild.objects.create() parent_id = childchild.rchild_ptr.r_ptr_id child_id = childchild.rchild_ptr_id parent_referent_id = S.objects.create(r=childchild.rchild_ptr.r_ptr).pk childchild.delete(keep_parents=True) self.assertFalse(RChildChild.objects.filter(id=childchild.id).exists()) self.assertTrue(RChild.objects.filter(id=child_id).exists()) self.assertTrue(R.objects.filter(id=parent_id).exists()) self.assertTrue(S.objects.filter(pk=parent_referent_id).exists()) def test_queryset_delete_returns_num_rows(self): """ QuerySet.delete() should return the number of deleted rows and a dictionary with the number of deletions for each object type. """ Avatar.objects.bulk_create([Avatar(desc='a'), Avatar(desc='b'), Avatar(desc='c')]) avatars_count = Avatar.objects.count() deleted, rows_count = Avatar.objects.all().delete() self.assertEqual(deleted, avatars_count) # more complex example with multiple object types r = R.objects.create() h1 = HiddenUser.objects.create(r=r) HiddenUser.objects.create(r=r) HiddenUserProfile.objects.create(user=h1) existed_objs = { R._meta.label: R.objects.count(), HiddenUser._meta.label: HiddenUser.objects.count(), A._meta.label: A.objects.count(), MR._meta.label: MR.objects.count(), HiddenUserProfile._meta.label: HiddenUserProfile.objects.count(), } deleted, deleted_objs = R.objects.all().delete() for k, v in existed_objs.items(): self.assertEqual(deleted_objs[k], v) def test_model_delete_returns_num_rows(self): """ Model.delete() should return the number of deleted rows and a dictionary with the number of deletions for each object type. """ r = R.objects.create() h1 = HiddenUser.objects.create(r=r) h2 = HiddenUser.objects.create(r=r) HiddenUser.objects.create(r=r) HiddenUserProfile.objects.create(user=h1) HiddenUserProfile.objects.create(user=h2) m1 = M.objects.create() m2 = M.objects.create() MR.objects.create(r=r, m=m1) r.m_set.add(m1) r.m_set.add(m2) r.save() existed_objs = { R._meta.label: R.objects.count(), HiddenUser._meta.label: HiddenUser.objects.count(), A._meta.label: A.objects.count(), MR._meta.label: MR.objects.count(), HiddenUserProfile._meta.label: HiddenUserProfile.objects.count(), M.m2m.through._meta.label: M.m2m.through.objects.count(), } deleted, deleted_objs = r.delete() self.assertEqual(deleted, sum(existed_objs.values())) for k, v in existed_objs.items(): self.assertEqual(deleted_objs[k], v) def test_proxied_model_duplicate_queries(self): """ #25685 - Deleting instances of a model with existing proxy classes should not issue multiple queries during cascade deletion of referring models. """ avatar = Avatar.objects.create() # One query for the Avatar table and a second for the User one. with self.assertNumQueries(2): avatar.delete() def test_only_referenced_fields_selected(self): """ Only referenced fields are selected during cascade deletion SELECT unless deletion signals are connected. """ origin = Origin.objects.create() expected_sql = str( Referrer.objects.only( # Both fields are referenced by SecondReferrer. 'id', 'unique_field', ).filter(origin__in=[origin]).query ) with self.assertNumQueries(2) as ctx: origin.delete() self.assertEqual(ctx.captured_queries[0]['sql'], expected_sql) def receiver(instance, **kwargs): pass # All fields are selected if deletion signals are connected. for signal_name in ('pre_delete', 'post_delete'): with self.subTest(signal=signal_name): origin = Origin.objects.create() signal = getattr(models.signals, signal_name) signal.connect(receiver, sender=Referrer) with self.assertNumQueries(2) as ctx: origin.delete() self.assertIn( connection.ops.quote_name('large_field'), ctx.captured_queries[0]['sql'], ) signal.disconnect(receiver, sender=Referrer) class FastDeleteTests(TestCase): def test_fast_delete_fk(self): u = User.objects.create( avatar=Avatar.objects.create() ) a = Avatar.objects.get(pk=u.avatar_id) # 1 query to fast-delete the user # 1 query to delete the avatar self.assertNumQueries(2, a.delete) self.assertFalse(User.objects.exists()) self.assertFalse(Avatar.objects.exists()) def test_fast_delete_m2m(self): t = M2MTo.objects.create() f = M2MFrom.objects.create() f.m2m.add(t) # 1 to delete f, 1 to fast-delete m2m for f self.assertNumQueries(2, f.delete) def test_fast_delete_revm2m(self): t = M2MTo.objects.create() f = M2MFrom.objects.create() f.m2m.add(t) # 1 to delete t, 1 to fast-delete t's m_set self.assertNumQueries(2, f.delete) def test_fast_delete_qs(self): u1 = User.objects.create() u2 = User.objects.create() self.assertNumQueries(1, User.objects.filter(pk=u1.pk).delete) self.assertEqual(User.objects.count(), 1) self.assertTrue(User.objects.filter(pk=u2.pk).exists()) def test_fast_delete_instance_set_pk_none(self): u = User.objects.create() # User can be fast-deleted. collector = Collector(using='default') self.assertTrue(collector.can_fast_delete(u)) u.delete() self.assertIsNone(u.pk) def test_fast_delete_joined_qs(self): a = Avatar.objects.create(desc='a') User.objects.create(avatar=a) u2 = User.objects.create() expected_queries = 1 if connection.features.update_can_self_select else 2 self.assertNumQueries(expected_queries, User.objects.filter(avatar__desc='a').delete) self.assertEqual(User.objects.count(), 1) self.assertTrue(User.objects.filter(pk=u2.pk).exists()) def test_fast_delete_inheritance(self): c = Child.objects.create() p = Parent.objects.create() # 1 for self, 1 for parent self.assertNumQueries(2, c.delete) self.assertFalse(Child.objects.exists()) self.assertEqual(Parent.objects.count(), 1) self.assertEqual(Parent.objects.filter(pk=p.pk).count(), 1) # 1 for self delete, 1 for fast delete of empty "child" qs. self.assertNumQueries(2, p.delete) self.assertFalse(Parent.objects.exists()) # 1 for self delete, 1 for fast delete of empty "child" qs. c = Child.objects.create() p = c.parent_ptr self.assertNumQueries(2, p.delete) self.assertFalse(Parent.objects.exists()) self.assertFalse(Child.objects.exists()) def test_fast_delete_large_batch(self): User.objects.bulk_create(User() for i in range(0, 2000)) # No problems here - we aren't going to cascade, so we will fast # delete the objects in a single query. self.assertNumQueries(1, User.objects.all().delete) a = Avatar.objects.create(desc='a') User.objects.bulk_create(User(avatar=a) for i in range(0, 2000)) # We don't hit parameter amount limits for a, so just one query for # that + fast delete of the related objs. self.assertNumQueries(2, a.delete) self.assertEqual(User.objects.count(), 0) def test_fast_delete_empty_no_update_can_self_select(self): """ #25932 - Fast deleting on backends that don't have the `no_update_can_self_select` feature should work even if the specified filter doesn't match any row. """ with self.assertNumQueries(1): self.assertEqual( User.objects.filter(avatar__desc='missing').delete(), (0, {'delete.User': 0}) ) def test_fast_delete_combined_relationships(self): # The cascading fast-delete of SecondReferrer should be combined # in a single DELETE WHERE referrer_id OR unique_field. origin = Origin.objects.create() referer = Referrer.objects.create(origin=origin, unique_field=42) with self.assertNumQueries(2): referer.delete()
2e815308781d39aa5566e60a03331c33522d76de77f5b7db8b5c6abe875bafe8
from unittest import mock from django.core.checks import Error, Warning as DjangoWarning from django.db import connection, models from django.db.models.fields.related import ForeignObject from django.test.testcases import SimpleTestCase from django.test.utils import isolate_apps, override_settings @isolate_apps('invalid_models_tests') class RelativeFieldTests(SimpleTestCase): def test_valid_foreign_key_without_accessor(self): class Target(models.Model): # There would be a clash if Model.field installed an accessor. model = models.IntegerField() class Model(models.Model): field = models.ForeignKey(Target, models.CASCADE, related_name='+') field = Model._meta.get_field('field') self.assertEqual(field.check(), []) def test_foreign_key_to_missing_model(self): # Model names are resolved when a model is being created, so we cannot # test relative fields in isolation and we need to attach them to a # model. class Model(models.Model): foreign_key = models.ForeignKey('Rel1', models.CASCADE) field = Model._meta.get_field('foreign_key') self.assertEqual(field.check(), [ Error( "Field defines a relation with model 'Rel1', " "which is either not installed, or is abstract.", obj=field, id='fields.E300', ), ]) @isolate_apps('invalid_models_tests') def test_foreign_key_to_isolate_apps_model(self): """ #25723 - Referenced model registration lookup should be run against the field's model registry. """ class OtherModel(models.Model): pass class Model(models.Model): foreign_key = models.ForeignKey('OtherModel', models.CASCADE) field = Model._meta.get_field('foreign_key') self.assertEqual(field.check(from_model=Model), []) def test_many_to_many_to_missing_model(self): class Model(models.Model): m2m = models.ManyToManyField("Rel2") field = Model._meta.get_field('m2m') self.assertEqual(field.check(from_model=Model), [ Error( "Field defines a relation with model 'Rel2', " "which is either not installed, or is abstract.", obj=field, id='fields.E300', ), ]) @isolate_apps('invalid_models_tests') def test_many_to_many_to_isolate_apps_model(self): """ #25723 - Referenced model registration lookup should be run against the field's model registry. """ class OtherModel(models.Model): pass class Model(models.Model): m2m = models.ManyToManyField('OtherModel') field = Model._meta.get_field('m2m') self.assertEqual(field.check(from_model=Model), []) def test_many_to_many_with_limit_choices_auto_created_no_warning(self): class Model(models.Model): name = models.CharField(max_length=20) class ModelM2M(models.Model): m2m = models.ManyToManyField(Model, limit_choices_to={'name': 'test_name'}) self.assertEqual(ModelM2M.check(), []) def test_many_to_many_with_useless_options(self): class Model(models.Model): name = models.CharField(max_length=20) class ModelM2M(models.Model): m2m = models.ManyToManyField( Model, null=True, validators=[lambda x: x], limit_choices_to={'name': 'test_name'}, through='ThroughModel', through_fields=('modelm2m', 'model'), ) class ThroughModel(models.Model): model = models.ForeignKey('Model', models.CASCADE) modelm2m = models.ForeignKey('ModelM2M', models.CASCADE) field = ModelM2M._meta.get_field('m2m') self.assertEqual(ModelM2M.check(), [ DjangoWarning( 'null has no effect on ManyToManyField.', obj=field, id='fields.W340', ), DjangoWarning( 'ManyToManyField does not support validators.', obj=field, id='fields.W341', ), DjangoWarning( 'limit_choices_to has no effect on ManyToManyField ' 'with a through model.', obj=field, id='fields.W343', ), ]) def test_ambiguous_relationship_model(self): class Person(models.Model): pass class Group(models.Model): field = models.ManyToManyField('Person', through="AmbiguousRelationship", related_name='tertiary') class AmbiguousRelationship(models.Model): # Too much foreign keys to Person. first_person = models.ForeignKey(Person, models.CASCADE, related_name="first") second_person = models.ForeignKey(Person, models.CASCADE, related_name="second") second_model = models.ForeignKey(Group, models.CASCADE) field = Group._meta.get_field('field') self.assertEqual(field.check(from_model=Group), [ Error( "The model is used as an intermediate model by " "'invalid_models_tests.Group.field', but it has more than one " "foreign key to 'Person', which is ambiguous. You must specify " "which foreign key Django should use via the through_fields " "keyword argument.", hint=( 'If you want to create a recursive relationship, use ' 'ForeignKey("self", symmetrical=False, through="AmbiguousRelationship").' ), obj=field, id='fields.E335', ), ]) def test_relationship_model_with_foreign_key_to_wrong_model(self): class WrongModel(models.Model): pass class Person(models.Model): pass class Group(models.Model): members = models.ManyToManyField('Person', through="InvalidRelationship") class InvalidRelationship(models.Model): person = models.ForeignKey(Person, models.CASCADE) wrong_foreign_key = models.ForeignKey(WrongModel, models.CASCADE) # The last foreign key should point to Group model. field = Group._meta.get_field('members') self.assertEqual(field.check(from_model=Group), [ Error( "The model is used as an intermediate model by " "'invalid_models_tests.Group.members', but it does not " "have a foreign key to 'Group' or 'Person'.", obj=InvalidRelationship, id='fields.E336', ), ]) def test_relationship_model_missing_foreign_key(self): class Person(models.Model): pass class Group(models.Model): members = models.ManyToManyField('Person', through="InvalidRelationship") class InvalidRelationship(models.Model): group = models.ForeignKey(Group, models.CASCADE) # No foreign key to Person field = Group._meta.get_field('members') self.assertEqual(field.check(from_model=Group), [ Error( "The model is used as an intermediate model by " "'invalid_models_tests.Group.members', but it does not have " "a foreign key to 'Group' or 'Person'.", obj=InvalidRelationship, id='fields.E336', ), ]) def test_missing_relationship_model(self): class Person(models.Model): pass class Group(models.Model): members = models.ManyToManyField('Person', through="MissingM2MModel") field = Group._meta.get_field('members') self.assertEqual(field.check(from_model=Group), [ Error( "Field specifies a many-to-many relation through model " "'MissingM2MModel', which has not been installed.", obj=field, id='fields.E331', ), ]) def test_missing_relationship_model_on_model_check(self): class Person(models.Model): pass class Group(models.Model): members = models.ManyToManyField('Person', through='MissingM2MModel') self.assertEqual(Group.check(), [ Error( "Field specifies a many-to-many relation through model " "'MissingM2MModel', which has not been installed.", obj=Group._meta.get_field('members'), id='fields.E331', ), ]) @isolate_apps('invalid_models_tests') def test_many_to_many_through_isolate_apps_model(self): """ #25723 - Through model registration lookup should be run against the field's model registry. """ class GroupMember(models.Model): person = models.ForeignKey('Person', models.CASCADE) group = models.ForeignKey('Group', models.CASCADE) class Person(models.Model): pass class Group(models.Model): members = models.ManyToManyField('Person', through='GroupMember') field = Group._meta.get_field('members') self.assertEqual(field.check(from_model=Group), []) def test_too_many_foreign_keys_in_self_referential_model(self): class Person(models.Model): friends = models.ManyToManyField('self', through="InvalidRelationship", symmetrical=False) class InvalidRelationship(models.Model): first = models.ForeignKey(Person, models.CASCADE, related_name="rel_from_set_2") second = models.ForeignKey(Person, models.CASCADE, related_name="rel_to_set_2") third = models.ForeignKey(Person, models.CASCADE, related_name="too_many_by_far") field = Person._meta.get_field('friends') self.assertEqual(field.check(from_model=Person), [ Error( "The model is used as an intermediate model by " "'invalid_models_tests.Person.friends', but it has more than two " "foreign keys to 'Person', which is ambiguous. You must specify " "which two foreign keys Django should use via the through_fields " "keyword argument.", hint='Use through_fields to specify which two foreign keys Django should use.', obj=InvalidRelationship, id='fields.E333', ), ]) def test_foreign_key_to_abstract_model(self): class AbstractModel(models.Model): class Meta: abstract = True class Model(models.Model): rel_string_foreign_key = models.ForeignKey('AbstractModel', models.CASCADE) rel_class_foreign_key = models.ForeignKey(AbstractModel, models.CASCADE) fields = [ Model._meta.get_field('rel_string_foreign_key'), Model._meta.get_field('rel_class_foreign_key'), ] expected_error = Error( "Field defines a relation with model 'AbstractModel', " "which is either not installed, or is abstract.", id='fields.E300', ) for field in fields: expected_error.obj = field self.assertEqual(field.check(), [expected_error]) def test_m2m_to_abstract_model(self): class AbstractModel(models.Model): class Meta: abstract = True class Model(models.Model): rel_string_m2m = models.ManyToManyField('AbstractModel') rel_class_m2m = models.ManyToManyField(AbstractModel) fields = [ Model._meta.get_field('rel_string_m2m'), Model._meta.get_field('rel_class_m2m'), ] expected_error = Error( "Field defines a relation with model 'AbstractModel', " "which is either not installed, or is abstract.", id='fields.E300', ) for field in fields: expected_error.obj = field self.assertEqual(field.check(from_model=Model), [expected_error]) def test_unique_m2m(self): class Person(models.Model): name = models.CharField(max_length=5) class Group(models.Model): members = models.ManyToManyField('Person', unique=True) field = Group._meta.get_field('members') self.assertEqual(field.check(from_model=Group), [ Error( 'ManyToManyFields cannot be unique.', obj=field, id='fields.E330', ), ]) def test_foreign_key_to_non_unique_field(self): class Target(models.Model): bad = models.IntegerField() # No unique=True class Model(models.Model): foreign_key = models.ForeignKey('Target', models.CASCADE, to_field='bad') field = Model._meta.get_field('foreign_key') self.assertEqual(field.check(), [ Error( "'Target.bad' must set unique=True because it is referenced by a foreign key.", obj=field, id='fields.E311', ), ]) def test_foreign_key_to_non_unique_field_under_explicit_model(self): class Target(models.Model): bad = models.IntegerField() class Model(models.Model): field = models.ForeignKey(Target, models.CASCADE, to_field='bad') field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "'Target.bad' must set unique=True because it is referenced by a foreign key.", obj=field, id='fields.E311', ), ]) def test_foreign_object_to_non_unique_fields(self): class Person(models.Model): # Note that both fields are not unique. country_id = models.IntegerField() city_id = models.IntegerField() class MMembership(models.Model): person_country_id = models.IntegerField() person_city_id = models.IntegerField() person = models.ForeignObject( Person, on_delete=models.CASCADE, from_fields=['person_country_id', 'person_city_id'], to_fields=['country_id', 'city_id'], ) field = MMembership._meta.get_field('person') self.assertEqual(field.check(), [ Error( "No subset of the fields 'country_id', 'city_id' on model 'Person' is unique.", hint=( "Add unique=True on any of those fields or add at least " "a subset of them to a unique_together constraint." ), obj=field, id='fields.E310', ) ]) def test_on_delete_set_null_on_non_nullable_field(self): class Person(models.Model): pass class Model(models.Model): foreign_key = models.ForeignKey('Person', models.SET_NULL) field = Model._meta.get_field('foreign_key') self.assertEqual(field.check(), [ Error( 'Field specifies on_delete=SET_NULL, but cannot be null.', hint='Set null=True argument on the field, or change the on_delete rule.', obj=field, id='fields.E320', ), ]) def test_on_delete_set_default_without_default_value(self): class Person(models.Model): pass class Model(models.Model): foreign_key = models.ForeignKey('Person', models.SET_DEFAULT) field = Model._meta.get_field('foreign_key') self.assertEqual(field.check(), [ Error( 'Field specifies on_delete=SET_DEFAULT, but has no default value.', hint='Set a default value, or change the on_delete rule.', obj=field, id='fields.E321', ), ]) def test_nullable_primary_key(self): class Model(models.Model): field = models.IntegerField(primary_key=True, null=True) field = Model._meta.get_field('field') with mock.patch.object(connection.features, 'interprets_empty_strings_as_nulls', False): results = field.check() self.assertEqual(results, [ Error( 'Primary keys must not have null=True.', hint='Set null=False on the field, or remove primary_key=True argument.', obj=field, id='fields.E007', ), ]) def test_not_swapped_model(self): class SwappableModel(models.Model): # A model that can be, but isn't swapped out. References to this # model should *not* raise any validation error. class Meta: swappable = 'TEST_SWAPPABLE_MODEL' class Model(models.Model): explicit_fk = models.ForeignKey( SwappableModel, models.CASCADE, related_name='explicit_fk', ) implicit_fk = models.ForeignKey( 'invalid_models_tests.SwappableModel', models.CASCADE, related_name='implicit_fk', ) explicit_m2m = models.ManyToManyField(SwappableModel, related_name='explicit_m2m') implicit_m2m = models.ManyToManyField( 'invalid_models_tests.SwappableModel', related_name='implicit_m2m', ) explicit_fk = Model._meta.get_field('explicit_fk') self.assertEqual(explicit_fk.check(), []) implicit_fk = Model._meta.get_field('implicit_fk') self.assertEqual(implicit_fk.check(), []) explicit_m2m = Model._meta.get_field('explicit_m2m') self.assertEqual(explicit_m2m.check(from_model=Model), []) implicit_m2m = Model._meta.get_field('implicit_m2m') self.assertEqual(implicit_m2m.check(from_model=Model), []) @override_settings(TEST_SWAPPED_MODEL='invalid_models_tests.Replacement') def test_referencing_to_swapped_model(self): class Replacement(models.Model): pass class SwappedModel(models.Model): class Meta: swappable = 'TEST_SWAPPED_MODEL' class Model(models.Model): explicit_fk = models.ForeignKey( SwappedModel, models.CASCADE, related_name='explicit_fk', ) implicit_fk = models.ForeignKey( 'invalid_models_tests.SwappedModel', models.CASCADE, related_name='implicit_fk', ) explicit_m2m = models.ManyToManyField(SwappedModel, related_name='explicit_m2m') implicit_m2m = models.ManyToManyField( 'invalid_models_tests.SwappedModel', related_name='implicit_m2m', ) fields = [ Model._meta.get_field('explicit_fk'), Model._meta.get_field('implicit_fk'), Model._meta.get_field('explicit_m2m'), Model._meta.get_field('implicit_m2m'), ] expected_error = Error( ("Field defines a relation with the model " "'invalid_models_tests.SwappedModel', which has been swapped out."), hint="Update the relation to point at 'settings.TEST_SWAPPED_MODEL'.", id='fields.E301', ) for field in fields: expected_error.obj = field self.assertEqual(field.check(from_model=Model), [expected_error]) def test_related_field_has_invalid_related_name(self): digit = 0 illegal_non_alphanumeric = '!' whitespace = '\t' invalid_related_names = [ '%s_begins_with_digit' % digit, '%s_begins_with_illegal_non_alphanumeric' % illegal_non_alphanumeric, '%s_begins_with_whitespace' % whitespace, 'contains_%s_illegal_non_alphanumeric' % illegal_non_alphanumeric, 'contains_%s_whitespace' % whitespace, 'ends_with_with_illegal_non_alphanumeric_%s' % illegal_non_alphanumeric, 'ends_with_whitespace_%s' % whitespace, 'with', # a Python keyword 'related_name\n', '', ',', # non-ASCII ] class Parent(models.Model): pass for invalid_related_name in invalid_related_names: Child = type('Child%s' % invalid_related_name, (models.Model,), { 'parent': models.ForeignKey('Parent', models.CASCADE, related_name=invalid_related_name), '__module__': Parent.__module__, }) field = Child._meta.get_field('parent') self.assertEqual(Child.check(), [ Error( "The name '%s' is invalid related_name for field Child%s.parent" % (invalid_related_name, invalid_related_name), hint="Related name must be a valid Python identifier or end with a '+'", obj=field, id='fields.E306', ), ]) def test_related_field_has_valid_related_name(self): lowercase = 'a' uppercase = 'A' digit = 0 related_names = [ '%s_starts_with_lowercase' % lowercase, '%s_tarts_with_uppercase' % uppercase, '_starts_with_underscore', 'contains_%s_digit' % digit, 'ends_with_plus+', '_+', '+', '試', '試驗+', ] class Parent(models.Model): pass for related_name in related_names: Child = type('Child%s' % related_name, (models.Model,), { 'parent': models.ForeignKey('Parent', models.CASCADE, related_name=related_name), '__module__': Parent.__module__, }) self.assertEqual(Child.check(), []) def test_to_fields_exist(self): class Parent(models.Model): pass class Child(models.Model): a = models.PositiveIntegerField() b = models.PositiveIntegerField() parent = ForeignObject( Parent, on_delete=models.SET_NULL, from_fields=('a', 'b'), to_fields=('a', 'b'), ) field = Child._meta.get_field('parent') self.assertEqual(field.check(), [ Error( "The to_field 'a' doesn't exist on the related model 'invalid_models_tests.Parent'.", obj=field, id='fields.E312', ), Error( "The to_field 'b' doesn't exist on the related model 'invalid_models_tests.Parent'.", obj=field, id='fields.E312', ), ]) def test_to_fields_not_checked_if_related_model_doesnt_exist(self): class Child(models.Model): a = models.PositiveIntegerField() b = models.PositiveIntegerField() parent = ForeignObject( 'invalid_models_tests.Parent', on_delete=models.SET_NULL, from_fields=('a', 'b'), to_fields=('a', 'b'), ) field = Child._meta.get_field('parent') self.assertEqual(field.check(), [ Error( "Field defines a relation with model 'invalid_models_tests.Parent', " "which is either not installed, or is abstract.", id='fields.E300', obj=field, ), ]) def test_invalid_related_query_name(self): class Target(models.Model): pass class Model(models.Model): first = models.ForeignKey(Target, models.CASCADE, related_name='contains__double') second = models.ForeignKey(Target, models.CASCADE, related_query_name='ends_underscore_') self.assertEqual(Model.check(), [ Error( "Reverse query name 'contains__double' must not contain '__'.", hint=("Add or change a related_name or related_query_name " "argument for this field."), obj=Model._meta.get_field('first'), id='fields.E309', ), Error( "Reverse query name 'ends_underscore_' must not end with an " "underscore.", hint=("Add or change a related_name or related_query_name " "argument for this field."), obj=Model._meta.get_field('second'), id='fields.E308', ), ]) @isolate_apps('invalid_models_tests') class AccessorClashTests(SimpleTestCase): def test_fk_to_integer(self): self._test_accessor_clash( target=models.IntegerField(), relative=models.ForeignKey('Target', models.CASCADE)) def test_fk_to_fk(self): self._test_accessor_clash( target=models.ForeignKey('Another', models.CASCADE), relative=models.ForeignKey('Target', models.CASCADE)) def test_fk_to_m2m(self): self._test_accessor_clash( target=models.ManyToManyField('Another'), relative=models.ForeignKey('Target', models.CASCADE)) def test_m2m_to_integer(self): self._test_accessor_clash( target=models.IntegerField(), relative=models.ManyToManyField('Target')) def test_m2m_to_fk(self): self._test_accessor_clash( target=models.ForeignKey('Another', models.CASCADE), relative=models.ManyToManyField('Target')) def test_m2m_to_m2m(self): self._test_accessor_clash( target=models.ManyToManyField('Another'), relative=models.ManyToManyField('Target')) def _test_accessor_clash(self, target, relative): class Another(models.Model): pass class Target(models.Model): model_set = target class Model(models.Model): rel = relative self.assertEqual(Model.check(), [ Error( "Reverse accessor for 'Model.rel' clashes with field name 'Target.model_set'.", hint=("Rename field 'Target.model_set', or add/change " "a related_name argument to the definition " "for field 'Model.rel'."), obj=Model._meta.get_field('rel'), id='fields.E302', ), ]) def test_clash_between_accessors(self): class Target(models.Model): pass class Model(models.Model): foreign = models.ForeignKey(Target, models.CASCADE) m2m = models.ManyToManyField(Target) self.assertEqual(Model.check(), [ Error( "Reverse accessor for 'Model.foreign' clashes with reverse accessor for 'Model.m2m'.", hint=( "Add or change a related_name argument to the definition " "for 'Model.foreign' or 'Model.m2m'." ), obj=Model._meta.get_field('foreign'), id='fields.E304', ), Error( "Reverse accessor for 'Model.m2m' clashes with reverse accessor for 'Model.foreign'.", hint=( "Add or change a related_name argument to the definition " "for 'Model.m2m' or 'Model.foreign'." ), obj=Model._meta.get_field('m2m'), id='fields.E304', ), ]) def test_m2m_to_m2m_with_inheritance(self): """ Ref #22047. """ class Target(models.Model): pass class Model(models.Model): children = models.ManyToManyField('Child', related_name="m2m_clash", related_query_name="no_clash") class Parent(models.Model): m2m_clash = models.ManyToManyField('Target') class Child(Parent): pass self.assertEqual(Model.check(), [ Error( "Reverse accessor for 'Model.children' clashes with field name 'Child.m2m_clash'.", hint=( "Rename field 'Child.m2m_clash', or add/change a related_name " "argument to the definition for field 'Model.children'." ), obj=Model._meta.get_field('children'), id='fields.E302', ) ]) def test_no_clash_for_hidden_related_name(self): class Stub(models.Model): pass class ManyToManyRel(models.Model): thing1 = models.ManyToManyField(Stub, related_name='+') thing2 = models.ManyToManyField(Stub, related_name='+') class FKRel(models.Model): thing1 = models.ForeignKey(Stub, models.CASCADE, related_name='+') thing2 = models.ForeignKey(Stub, models.CASCADE, related_name='+') self.assertEqual(ManyToManyRel.check(), []) self.assertEqual(FKRel.check(), []) @isolate_apps('invalid_models_tests') class ReverseQueryNameClashTests(SimpleTestCase): def test_fk_to_integer(self): self._test_reverse_query_name_clash( target=models.IntegerField(), relative=models.ForeignKey('Target', models.CASCADE)) def test_fk_to_fk(self): self._test_reverse_query_name_clash( target=models.ForeignKey('Another', models.CASCADE), relative=models.ForeignKey('Target', models.CASCADE)) def test_fk_to_m2m(self): self._test_reverse_query_name_clash( target=models.ManyToManyField('Another'), relative=models.ForeignKey('Target', models.CASCADE)) def test_m2m_to_integer(self): self._test_reverse_query_name_clash( target=models.IntegerField(), relative=models.ManyToManyField('Target')) def test_m2m_to_fk(self): self._test_reverse_query_name_clash( target=models.ForeignKey('Another', models.CASCADE), relative=models.ManyToManyField('Target')) def test_m2m_to_m2m(self): self._test_reverse_query_name_clash( target=models.ManyToManyField('Another'), relative=models.ManyToManyField('Target')) def _test_reverse_query_name_clash(self, target, relative): class Another(models.Model): pass class Target(models.Model): model = target class Model(models.Model): rel = relative self.assertEqual(Model.check(), [ Error( "Reverse query name for 'Model.rel' clashes with field name 'Target.model'.", hint=( "Rename field 'Target.model', or add/change a related_name " "argument to the definition for field 'Model.rel'." ), obj=Model._meta.get_field('rel'), id='fields.E303', ), ]) @isolate_apps('invalid_models_tests') class ExplicitRelatedNameClashTests(SimpleTestCase): def test_fk_to_integer(self): self._test_explicit_related_name_clash( target=models.IntegerField(), relative=models.ForeignKey('Target', models.CASCADE, related_name='clash')) def test_fk_to_fk(self): self._test_explicit_related_name_clash( target=models.ForeignKey('Another', models.CASCADE), relative=models.ForeignKey('Target', models.CASCADE, related_name='clash')) def test_fk_to_m2m(self): self._test_explicit_related_name_clash( target=models.ManyToManyField('Another'), relative=models.ForeignKey('Target', models.CASCADE, related_name='clash')) def test_m2m_to_integer(self): self._test_explicit_related_name_clash( target=models.IntegerField(), relative=models.ManyToManyField('Target', related_name='clash')) def test_m2m_to_fk(self): self._test_explicit_related_name_clash( target=models.ForeignKey('Another', models.CASCADE), relative=models.ManyToManyField('Target', related_name='clash')) def test_m2m_to_m2m(self): self._test_explicit_related_name_clash( target=models.ManyToManyField('Another'), relative=models.ManyToManyField('Target', related_name='clash')) def _test_explicit_related_name_clash(self, target, relative): class Another(models.Model): pass class Target(models.Model): clash = target class Model(models.Model): rel = relative self.assertEqual(Model.check(), [ Error( "Reverse accessor for 'Model.rel' clashes with field name 'Target.clash'.", hint=( "Rename field 'Target.clash', or add/change a related_name " "argument to the definition for field 'Model.rel'." ), obj=Model._meta.get_field('rel'), id='fields.E302', ), Error( "Reverse query name for 'Model.rel' clashes with field name 'Target.clash'.", hint=( "Rename field 'Target.clash', or add/change a related_name " "argument to the definition for field 'Model.rel'." ), obj=Model._meta.get_field('rel'), id='fields.E303', ), ]) @isolate_apps('invalid_models_tests') class ExplicitRelatedQueryNameClashTests(SimpleTestCase): def test_fk_to_integer(self, related_name=None): self._test_explicit_related_query_name_clash( target=models.IntegerField(), relative=models.ForeignKey( 'Target', models.CASCADE, related_name=related_name, related_query_name='clash', ) ) def test_hidden_fk_to_integer(self, related_name=None): self.test_fk_to_integer(related_name='+') def test_fk_to_fk(self, related_name=None): self._test_explicit_related_query_name_clash( target=models.ForeignKey('Another', models.CASCADE), relative=models.ForeignKey( 'Target', models.CASCADE, related_name=related_name, related_query_name='clash', ) ) def test_hidden_fk_to_fk(self): self.test_fk_to_fk(related_name='+') def test_fk_to_m2m(self, related_name=None): self._test_explicit_related_query_name_clash( target=models.ManyToManyField('Another'), relative=models.ForeignKey( 'Target', models.CASCADE, related_name=related_name, related_query_name='clash', ) ) def test_hidden_fk_to_m2m(self): self.test_fk_to_m2m(related_name='+') def test_m2m_to_integer(self, related_name=None): self._test_explicit_related_query_name_clash( target=models.IntegerField(), relative=models.ManyToManyField('Target', related_name=related_name, related_query_name='clash')) def test_hidden_m2m_to_integer(self): self.test_m2m_to_integer(related_name='+') def test_m2m_to_fk(self, related_name=None): self._test_explicit_related_query_name_clash( target=models.ForeignKey('Another', models.CASCADE), relative=models.ManyToManyField('Target', related_name=related_name, related_query_name='clash')) def test_hidden_m2m_to_fk(self): self.test_m2m_to_fk(related_name='+') def test_m2m_to_m2m(self, related_name=None): self._test_explicit_related_query_name_clash( target=models.ManyToManyField('Another'), relative=models.ManyToManyField( 'Target', related_name=related_name, related_query_name='clash', ) ) def test_hidden_m2m_to_m2m(self): self.test_m2m_to_m2m(related_name='+') def _test_explicit_related_query_name_clash(self, target, relative): class Another(models.Model): pass class Target(models.Model): clash = target class Model(models.Model): rel = relative self.assertEqual(Model.check(), [ Error( "Reverse query name for 'Model.rel' clashes with field name 'Target.clash'.", hint=( "Rename field 'Target.clash', or add/change a related_name " "argument to the definition for field 'Model.rel'." ), obj=Model._meta.get_field('rel'), id='fields.E303', ), ]) @isolate_apps('invalid_models_tests') class SelfReferentialM2MClashTests(SimpleTestCase): def test_clash_between_accessors(self): class Model(models.Model): first_m2m = models.ManyToManyField('self', symmetrical=False) second_m2m = models.ManyToManyField('self', symmetrical=False) self.assertEqual(Model.check(), [ Error( "Reverse accessor for 'Model.first_m2m' clashes with reverse accessor for 'Model.second_m2m'.", hint=( "Add or change a related_name argument to the definition " "for 'Model.first_m2m' or 'Model.second_m2m'." ), obj=Model._meta.get_field('first_m2m'), id='fields.E304', ), Error( "Reverse accessor for 'Model.second_m2m' clashes with reverse accessor for 'Model.first_m2m'.", hint=( "Add or change a related_name argument to the definition " "for 'Model.second_m2m' or 'Model.first_m2m'." ), obj=Model._meta.get_field('second_m2m'), id='fields.E304', ), ]) def test_accessor_clash(self): class Model(models.Model): model_set = models.ManyToManyField("self", symmetrical=False) self.assertEqual(Model.check(), [ Error( "Reverse accessor for 'Model.model_set' clashes with field name 'Model.model_set'.", hint=( "Rename field 'Model.model_set', or add/change a related_name " "argument to the definition for field 'Model.model_set'." ), obj=Model._meta.get_field('model_set'), id='fields.E302', ), ]) def test_reverse_query_name_clash(self): class Model(models.Model): model = models.ManyToManyField("self", symmetrical=False) self.assertEqual(Model.check(), [ Error( "Reverse query name for 'Model.model' clashes with field name 'Model.model'.", hint=( "Rename field 'Model.model', or add/change a related_name " "argument to the definition for field 'Model.model'." ), obj=Model._meta.get_field('model'), id='fields.E303', ), ]) def test_clash_under_explicit_related_name(self): class Model(models.Model): clash = models.IntegerField() m2m = models.ManyToManyField("self", symmetrical=False, related_name='clash') self.assertEqual(Model.check(), [ Error( "Reverse accessor for 'Model.m2m' clashes with field name 'Model.clash'.", hint=( "Rename field 'Model.clash', or add/change a related_name " "argument to the definition for field 'Model.m2m'." ), obj=Model._meta.get_field('m2m'), id='fields.E302', ), Error( "Reverse query name for 'Model.m2m' clashes with field name 'Model.clash'.", hint=( "Rename field 'Model.clash', or add/change a related_name " "argument to the definition for field 'Model.m2m'." ), obj=Model._meta.get_field('m2m'), id='fields.E303', ), ]) def test_valid_model(self): class Model(models.Model): first = models.ManyToManyField("self", symmetrical=False, related_name='first_accessor') second = models.ManyToManyField("self", symmetrical=False, related_name='second_accessor') self.assertEqual(Model.check(), []) @isolate_apps('invalid_models_tests') class SelfReferentialFKClashTests(SimpleTestCase): def test_accessor_clash(self): class Model(models.Model): model_set = models.ForeignKey("Model", models.CASCADE) self.assertEqual(Model.check(), [ Error( "Reverse accessor for 'Model.model_set' clashes with field name 'Model.model_set'.", hint=( "Rename field 'Model.model_set', or add/change " "a related_name argument to the definition " "for field 'Model.model_set'." ), obj=Model._meta.get_field('model_set'), id='fields.E302', ), ]) def test_reverse_query_name_clash(self): class Model(models.Model): model = models.ForeignKey("Model", models.CASCADE) self.assertEqual(Model.check(), [ Error( "Reverse query name for 'Model.model' clashes with field name 'Model.model'.", hint=( "Rename field 'Model.model', or add/change a related_name " "argument to the definition for field 'Model.model'." ), obj=Model._meta.get_field('model'), id='fields.E303', ), ]) def test_clash_under_explicit_related_name(self): class Model(models.Model): clash = models.CharField(max_length=10) foreign = models.ForeignKey("Model", models.CASCADE, related_name='clash') self.assertEqual(Model.check(), [ Error( "Reverse accessor for 'Model.foreign' clashes with field name 'Model.clash'.", hint=( "Rename field 'Model.clash', or add/change a related_name " "argument to the definition for field 'Model.foreign'." ), obj=Model._meta.get_field('foreign'), id='fields.E302', ), Error( "Reverse query name for 'Model.foreign' clashes with field name 'Model.clash'.", hint=( "Rename field 'Model.clash', or add/change a related_name " "argument to the definition for field 'Model.foreign'." ), obj=Model._meta.get_field('foreign'), id='fields.E303', ), ]) @isolate_apps('invalid_models_tests') class ComplexClashTests(SimpleTestCase): # New tests should not be included here, because this is a single, # self-contained sanity check, not a test of everything. def test_complex_clash(self): class Target(models.Model): tgt_safe = models.CharField(max_length=10) clash = models.CharField(max_length=10) model = models.CharField(max_length=10) clash1_set = models.CharField(max_length=10) class Model(models.Model): src_safe = models.CharField(max_length=10) foreign_1 = models.ForeignKey(Target, models.CASCADE, related_name='id') foreign_2 = models.ForeignKey(Target, models.CASCADE, related_name='src_safe') m2m_1 = models.ManyToManyField(Target, related_name='id') m2m_2 = models.ManyToManyField(Target, related_name='src_safe') self.assertEqual(Model.check(), [ Error( "Reverse accessor for 'Model.foreign_1' clashes with field name 'Target.id'.", hint=("Rename field 'Target.id', or add/change a related_name " "argument to the definition for field 'Model.foreign_1'."), obj=Model._meta.get_field('foreign_1'), id='fields.E302', ), Error( "Reverse query name for 'Model.foreign_1' clashes with field name 'Target.id'.", hint=("Rename field 'Target.id', or add/change a related_name " "argument to the definition for field 'Model.foreign_1'."), obj=Model._meta.get_field('foreign_1'), id='fields.E303', ), Error( "Reverse accessor for 'Model.foreign_1' clashes with reverse accessor for 'Model.m2m_1'.", hint=("Add or change a related_name argument to " "the definition for 'Model.foreign_1' or 'Model.m2m_1'."), obj=Model._meta.get_field('foreign_1'), id='fields.E304', ), Error( "Reverse query name for 'Model.foreign_1' clashes with reverse query name for 'Model.m2m_1'.", hint=("Add or change a related_name argument to " "the definition for 'Model.foreign_1' or 'Model.m2m_1'."), obj=Model._meta.get_field('foreign_1'), id='fields.E305', ), Error( "Reverse accessor for 'Model.foreign_2' clashes with reverse accessor for 'Model.m2m_2'.", hint=("Add or change a related_name argument " "to the definition for 'Model.foreign_2' or 'Model.m2m_2'."), obj=Model._meta.get_field('foreign_2'), id='fields.E304', ), Error( "Reverse query name for 'Model.foreign_2' clashes with reverse query name for 'Model.m2m_2'.", hint=("Add or change a related_name argument to " "the definition for 'Model.foreign_2' or 'Model.m2m_2'."), obj=Model._meta.get_field('foreign_2'), id='fields.E305', ), Error( "Reverse accessor for 'Model.m2m_1' clashes with field name 'Target.id'.", hint=("Rename field 'Target.id', or add/change a related_name " "argument to the definition for field 'Model.m2m_1'."), obj=Model._meta.get_field('m2m_1'), id='fields.E302', ), Error( "Reverse query name for 'Model.m2m_1' clashes with field name 'Target.id'.", hint=("Rename field 'Target.id', or add/change a related_name " "argument to the definition for field 'Model.m2m_1'."), obj=Model._meta.get_field('m2m_1'), id='fields.E303', ), Error( "Reverse accessor for 'Model.m2m_1' clashes with reverse accessor for 'Model.foreign_1'.", hint=("Add or change a related_name argument to the definition " "for 'Model.m2m_1' or 'Model.foreign_1'."), obj=Model._meta.get_field('m2m_1'), id='fields.E304', ), Error( "Reverse query name for 'Model.m2m_1' clashes with reverse query name for 'Model.foreign_1'.", hint=("Add or change a related_name argument to " "the definition for 'Model.m2m_1' or 'Model.foreign_1'."), obj=Model._meta.get_field('m2m_1'), id='fields.E305', ), Error( "Reverse accessor for 'Model.m2m_2' clashes with reverse accessor for 'Model.foreign_2'.", hint=("Add or change a related_name argument to the definition " "for 'Model.m2m_2' or 'Model.foreign_2'."), obj=Model._meta.get_field('m2m_2'), id='fields.E304', ), Error( "Reverse query name for 'Model.m2m_2' clashes with reverse query name for 'Model.foreign_2'.", hint=("Add or change a related_name argument to the definition " "for 'Model.m2m_2' or 'Model.foreign_2'."), obj=Model._meta.get_field('m2m_2'), id='fields.E305', ), ]) @isolate_apps('invalid_models_tests') class M2mThroughFieldsTests(SimpleTestCase): def test_m2m_field_argument_validation(self): """ ManyToManyField accepts the ``through_fields`` kwarg only if an intermediary table is specified. """ class Fan(models.Model): pass with self.assertRaisesMessage(ValueError, 'Cannot specify through_fields without a through model'): models.ManyToManyField(Fan, through_fields=('f1', 'f2')) def test_invalid_order(self): """ Mixing up the order of link fields to ManyToManyField.through_fields triggers validation errors. """ class Fan(models.Model): pass class Event(models.Model): invitees = models.ManyToManyField(Fan, through='Invitation', through_fields=('invitee', 'event')) class Invitation(models.Model): event = models.ForeignKey(Event, models.CASCADE) invitee = models.ForeignKey(Fan, models.CASCADE) inviter = models.ForeignKey(Fan, models.CASCADE, related_name='+') field = Event._meta.get_field('invitees') self.assertEqual(field.check(from_model=Event), [ Error( "'Invitation.invitee' is not a foreign key to 'Event'.", hint="Did you mean one of the following foreign keys to 'Event': event?", obj=field, id='fields.E339', ), Error( "'Invitation.event' is not a foreign key to 'Fan'.", hint="Did you mean one of the following foreign keys to 'Fan': invitee, inviter?", obj=field, id='fields.E339', ), ]) def test_invalid_field(self): """ Providing invalid field names to ManyToManyField.through_fields triggers validation errors. """ class Fan(models.Model): pass class Event(models.Model): invitees = models.ManyToManyField( Fan, through='Invitation', through_fields=('invalid_field_1', 'invalid_field_2'), ) class Invitation(models.Model): event = models.ForeignKey(Event, models.CASCADE) invitee = models.ForeignKey(Fan, models.CASCADE) inviter = models.ForeignKey(Fan, models.CASCADE, related_name='+') field = Event._meta.get_field('invitees') self.assertEqual(field.check(from_model=Event), [ Error( "The intermediary model 'invalid_models_tests.Invitation' has no field 'invalid_field_1'.", hint="Did you mean one of the following foreign keys to 'Event': event?", obj=field, id='fields.E338', ), Error( "The intermediary model 'invalid_models_tests.Invitation' has no field 'invalid_field_2'.", hint="Did you mean one of the following foreign keys to 'Fan': invitee, inviter?", obj=field, id='fields.E338', ), ]) def test_explicit_field_names(self): """ If ``through_fields`` kwarg is given, it must specify both link fields of the intermediary table. """ class Fan(models.Model): pass class Event(models.Model): invitees = models.ManyToManyField(Fan, through='Invitation', through_fields=(None, 'invitee')) class Invitation(models.Model): event = models.ForeignKey(Event, models.CASCADE) invitee = models.ForeignKey(Fan, models.CASCADE) inviter = models.ForeignKey(Fan, models.CASCADE, related_name='+') field = Event._meta.get_field('invitees') self.assertEqual(field.check(from_model=Event), [ Error( "Field specifies 'through_fields' but does not provide the names " "of the two link fields that should be used for the relation " "through model 'invalid_models_tests.Invitation'.", hint="Make sure you specify 'through_fields' as through_fields=('field1', 'field2')", obj=field, id='fields.E337', ), ]) def test_superset_foreign_object(self): class Parent(models.Model): a = models.PositiveIntegerField() b = models.PositiveIntegerField() c = models.PositiveIntegerField() class Meta: unique_together = (('a', 'b', 'c'),) class Child(models.Model): a = models.PositiveIntegerField() b = models.PositiveIntegerField() value = models.CharField(max_length=255) parent = ForeignObject( Parent, on_delete=models.SET_NULL, from_fields=('a', 'b'), to_fields=('a', 'b'), related_name='children', ) field = Child._meta.get_field('parent') self.assertEqual(field.check(from_model=Child), [ Error( "No subset of the fields 'a', 'b' on model 'Parent' is unique.", hint=( "Add unique=True on any of those fields or add at least " "a subset of them to a unique_together constraint." ), obj=field, id='fields.E310', ), ]) def test_intersection_foreign_object(self): class Parent(models.Model): a = models.PositiveIntegerField() b = models.PositiveIntegerField() c = models.PositiveIntegerField() d = models.PositiveIntegerField() class Meta: unique_together = (('a', 'b', 'c'),) class Child(models.Model): a = models.PositiveIntegerField() b = models.PositiveIntegerField() d = models.PositiveIntegerField() value = models.CharField(max_length=255) parent = ForeignObject( Parent, on_delete=models.SET_NULL, from_fields=('a', 'b', 'd'), to_fields=('a', 'b', 'd'), related_name='children', ) field = Child._meta.get_field('parent') self.assertEqual(field.check(from_model=Child), [ Error( "No subset of the fields 'a', 'b', 'd' on model 'Parent' is unique.", hint=( "Add unique=True on any of those fields or add at least " "a subset of them to a unique_together constraint." ), obj=field, id='fields.E310', ), ])
3b4671f6944c62648c050c27f76f85fa6d751b2eda35e82b498dd92e471f8696
import unittest from django.conf import settings from django.core.checks import Error, Warning from django.core.checks.model_checks import _check_lazy_references from django.core.exceptions import ImproperlyConfigured from django.db import connection, connections, models from django.db.models.functions import Lower from django.db.models.signals import post_init from django.test import SimpleTestCase from django.test.utils import isolate_apps, override_settings, register_lookup def get_max_column_name_length(): allowed_len = None db_alias = None for db in settings.DATABASES: connection = connections[db] max_name_length = connection.ops.max_name_length() if max_name_length is not None and not connection.features.truncates_names: if allowed_len is None or max_name_length < allowed_len: allowed_len = max_name_length db_alias = db return (allowed_len, db_alias) @isolate_apps('invalid_models_tests') class IndexTogetherTests(SimpleTestCase): def test_non_iterable(self): class Model(models.Model): class Meta: index_together = 42 self.assertEqual(Model.check(), [ Error( "'index_together' must be a list or tuple.", obj=Model, id='models.E008', ), ]) def test_non_list(self): class Model(models.Model): class Meta: index_together = 'not-a-list' self.assertEqual(Model.check(), [ Error( "'index_together' must be a list or tuple.", obj=Model, id='models.E008', ), ]) def test_list_containing_non_iterable(self): class Model(models.Model): class Meta: index_together = [('a', 'b'), 42] self.assertEqual(Model.check(), [ Error( "All 'index_together' elements must be lists or tuples.", obj=Model, id='models.E009', ), ]) def test_pointing_to_missing_field(self): class Model(models.Model): class Meta: index_together = [['missing_field']] self.assertEqual(Model.check(), [ Error( "'index_together' refers to the nonexistent field 'missing_field'.", obj=Model, id='models.E012', ), ]) def test_pointing_to_non_local_field(self): class Foo(models.Model): field1 = models.IntegerField() class Bar(Foo): field2 = models.IntegerField() class Meta: index_together = [['field2', 'field1']] self.assertEqual(Bar.check(), [ Error( "'index_together' refers to field 'field1' which is not " "local to model 'Bar'.", hint='This issue may be caused by multi-table inheritance.', obj=Bar, id='models.E016', ), ]) def test_pointing_to_m2m_field(self): class Model(models.Model): m2m = models.ManyToManyField('self') class Meta: index_together = [['m2m']] self.assertEqual(Model.check(), [ Error( "'index_together' refers to a ManyToManyField 'm2m', but " "ManyToManyFields are not permitted in 'index_together'.", obj=Model, id='models.E013', ), ]) def test_pointing_to_fk(self): class Foo(models.Model): pass class Bar(models.Model): foo_1 = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name='bar_1') foo_2 = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name='bar_2') class Meta: index_together = [['foo_1_id', 'foo_2']] self.assertEqual(Bar.check(), []) # unique_together tests are very similar to index_together tests. @isolate_apps('invalid_models_tests') class UniqueTogetherTests(SimpleTestCase): def test_non_iterable(self): class Model(models.Model): class Meta: unique_together = 42 self.assertEqual(Model.check(), [ Error( "'unique_together' must be a list or tuple.", obj=Model, id='models.E010', ), ]) def test_list_containing_non_iterable(self): class Model(models.Model): one = models.IntegerField() two = models.IntegerField() class Meta: unique_together = [('a', 'b'), 42] self.assertEqual(Model.check(), [ Error( "All 'unique_together' elements must be lists or tuples.", obj=Model, id='models.E011', ), ]) def test_non_list(self): class Model(models.Model): class Meta: unique_together = 'not-a-list' self.assertEqual(Model.check(), [ Error( "'unique_together' must be a list or tuple.", obj=Model, id='models.E010', ), ]) def test_valid_model(self): class Model(models.Model): one = models.IntegerField() two = models.IntegerField() class Meta: # unique_together can be a simple tuple unique_together = ('one', 'two') self.assertEqual(Model.check(), []) def test_pointing_to_missing_field(self): class Model(models.Model): class Meta: unique_together = [['missing_field']] self.assertEqual(Model.check(), [ Error( "'unique_together' refers to the nonexistent field 'missing_field'.", obj=Model, id='models.E012', ), ]) def test_pointing_to_m2m(self): class Model(models.Model): m2m = models.ManyToManyField('self') class Meta: unique_together = [['m2m']] self.assertEqual(Model.check(), [ Error( "'unique_together' refers to a ManyToManyField 'm2m', but " "ManyToManyFields are not permitted in 'unique_together'.", obj=Model, id='models.E013', ), ]) def test_pointing_to_fk(self): class Foo(models.Model): pass class Bar(models.Model): foo_1 = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name='bar_1') foo_2 = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name='bar_2') class Meta: unique_together = [['foo_1_id', 'foo_2']] self.assertEqual(Bar.check(), []) @isolate_apps('invalid_models_tests') class IndexesTests(SimpleTestCase): def test_pointing_to_missing_field(self): class Model(models.Model): class Meta: indexes = [models.Index(fields=['missing_field'], name='name')] self.assertEqual(Model.check(), [ Error( "'indexes' refers to the nonexistent field 'missing_field'.", obj=Model, id='models.E012', ), ]) def test_pointing_to_m2m_field(self): class Model(models.Model): m2m = models.ManyToManyField('self') class Meta: indexes = [models.Index(fields=['m2m'], name='name')] self.assertEqual(Model.check(), [ Error( "'indexes' refers to a ManyToManyField 'm2m', but " "ManyToManyFields are not permitted in 'indexes'.", obj=Model, id='models.E013', ), ]) def test_pointing_to_non_local_field(self): class Foo(models.Model): field1 = models.IntegerField() class Bar(Foo): field2 = models.IntegerField() class Meta: indexes = [models.Index(fields=['field2', 'field1'], name='name')] self.assertEqual(Bar.check(), [ Error( "'indexes' refers to field 'field1' which is not local to " "model 'Bar'.", hint='This issue may be caused by multi-table inheritance.', obj=Bar, id='models.E016', ), ]) def test_pointing_to_fk(self): class Foo(models.Model): pass class Bar(models.Model): foo_1 = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name='bar_1') foo_2 = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name='bar_2') class Meta: indexes = [models.Index(fields=['foo_1_id', 'foo_2'], name='index_name')] self.assertEqual(Bar.check(), []) def test_name_constraints(self): class Model(models.Model): class Meta: indexes = [ models.Index(fields=['id'], name='_index_name'), models.Index(fields=['id'], name='5index_name'), ] self.assertEqual(Model.check(), [ Error( "The index name '%sindex_name' cannot start with an " "underscore or a number." % prefix, obj=Model, id='models.E033', ) for prefix in ('_', '5') ]) def test_max_name_length(self): index_name = 'x' * 31 class Model(models.Model): class Meta: indexes = [models.Index(fields=['id'], name=index_name)] self.assertEqual(Model.check(), [ Error( "The index name '%s' cannot be longer than 30 characters." % index_name, obj=Model, id='models.E034', ), ]) @isolate_apps('invalid_models_tests') class FieldNamesTests(SimpleTestCase): def test_ending_with_underscore(self): class Model(models.Model): field_ = models.CharField(max_length=10) m2m_ = models.ManyToManyField('self') self.assertEqual(Model.check(), [ Error( 'Field names must not end with an underscore.', obj=Model._meta.get_field('field_'), id='fields.E001', ), Error( 'Field names must not end with an underscore.', obj=Model._meta.get_field('m2m_'), id='fields.E001', ), ]) max_column_name_length, column_limit_db_alias = get_max_column_name_length() @unittest.skipIf(max_column_name_length is None, "The database doesn't have a column name length limit.") def test_M2M_long_column_name(self): """ #13711 -- Model check for long M2M column names when database has column name length limits. """ allowed_len, db_alias = get_max_column_name_length() # A model with very long name which will be used to set relations to. class VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz(models.Model): title = models.CharField(max_length=11) # Main model for which checks will be performed. class ModelWithLongField(models.Model): m2m_field = models.ManyToManyField( VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, related_name='rn1', ) m2m_field2 = models.ManyToManyField( VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, related_name='rn2', through='m2msimple', ) m2m_field3 = models.ManyToManyField( VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, related_name='rn3', through='m2mcomplex', ) fk = models.ForeignKey( VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, models.CASCADE, related_name='rn4', ) # Models used for setting `through` in M2M field. class m2msimple(models.Model): id2 = models.ForeignKey(ModelWithLongField, models.CASCADE) class m2mcomplex(models.Model): id2 = models.ForeignKey(ModelWithLongField, models.CASCADE) long_field_name = 'a' * (self.max_column_name_length + 1) models.ForeignKey( VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, models.CASCADE, ).contribute_to_class(m2msimple, long_field_name) models.ForeignKey( VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, models.CASCADE, db_column=long_field_name ).contribute_to_class(m2mcomplex, long_field_name) errors = ModelWithLongField.check() # First error because of M2M field set on the model with long name. m2m_long_name = "verylongmodelnamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz_id" if self.max_column_name_length > len(m2m_long_name): # Some databases support names longer than the test name. expected = [] else: expected = [ Error( 'Autogenerated column name too long for M2M field "%s". ' 'Maximum length is "%s" for database "%s".' % (m2m_long_name, self.max_column_name_length, self.column_limit_db_alias), hint="Use 'through' to create a separate model for " "M2M and then set column_name using 'db_column'.", obj=ModelWithLongField, id='models.E019', ) ] # Second error because the FK specified in the `through` model # `m2msimple` has auto-generated name longer than allowed. # There will be no check errors in the other M2M because it # specifies db_column for the FK in `through` model even if the actual # name is longer than the limits of the database. expected.append( Error( 'Autogenerated column name too long for M2M field "%s_id". ' 'Maximum length is "%s" for database "%s".' % (long_field_name, self.max_column_name_length, self.column_limit_db_alias), hint="Use 'through' to create a separate model for " "M2M and then set column_name using 'db_column'.", obj=ModelWithLongField, id='models.E019', ) ) self.assertEqual(errors, expected) @unittest.skipIf(max_column_name_length is None, "The database doesn't have a column name length limit.") def test_local_field_long_column_name(self): """ #13711 -- Model check for long column names when database does not support long names. """ allowed_len, db_alias = get_max_column_name_length() class ModelWithLongField(models.Model): title = models.CharField(max_length=11) long_field_name = 'a' * (self.max_column_name_length + 1) long_field_name2 = 'b' * (self.max_column_name_length + 1) models.CharField(max_length=11).contribute_to_class(ModelWithLongField, long_field_name) models.CharField(max_length=11, db_column='vlmn').contribute_to_class(ModelWithLongField, long_field_name2) self.assertEqual(ModelWithLongField.check(), [ Error( 'Autogenerated column name too long for field "%s". ' 'Maximum length is "%s" for database "%s".' % (long_field_name, self.max_column_name_length, self.column_limit_db_alias), hint="Set the column name manually using 'db_column'.", obj=ModelWithLongField, id='models.E018', ) ]) def test_including_separator(self): class Model(models.Model): some__field = models.IntegerField() self.assertEqual(Model.check(), [ Error( 'Field names must not contain "__".', obj=Model._meta.get_field('some__field'), id='fields.E002', ) ]) def test_pk(self): class Model(models.Model): pk = models.IntegerField() self.assertEqual(Model.check(), [ Error( "'pk' is a reserved word that cannot be used as a field name.", obj=Model._meta.get_field('pk'), id='fields.E003', ) ]) def test_db_column_clash(self): class Model(models.Model): foo = models.IntegerField() bar = models.IntegerField(db_column='foo') self.assertEqual(Model.check(), [ Error( "Field 'bar' has column name 'foo' that is used by " "another field.", hint="Specify a 'db_column' for the field.", obj=Model, id='models.E007', ) ]) @isolate_apps('invalid_models_tests') class ShadowingFieldsTests(SimpleTestCase): def test_field_name_clash_with_child_accessor(self): class Parent(models.Model): pass class Child(Parent): child = models.CharField(max_length=100) self.assertEqual(Child.check(), [ Error( "The field 'child' clashes with the field " "'child' from model 'invalid_models_tests.parent'.", obj=Child._meta.get_field('child'), id='models.E006', ) ]) def test_multiinheritance_clash(self): class Mother(models.Model): clash = models.IntegerField() class Father(models.Model): clash = models.IntegerField() class Child(Mother, Father): # Here we have two clashed: id (automatic field) and clash, because # both parents define these fields. pass self.assertEqual(Child.check(), [ Error( "The field 'id' from parent model " "'invalid_models_tests.mother' clashes with the field 'id' " "from parent model 'invalid_models_tests.father'.", obj=Child, id='models.E005', ), Error( "The field 'clash' from parent model " "'invalid_models_tests.mother' clashes with the field 'clash' " "from parent model 'invalid_models_tests.father'.", obj=Child, id='models.E005', ) ]) def test_inheritance_clash(self): class Parent(models.Model): f_id = models.IntegerField() class Target(models.Model): # This field doesn't result in a clash. f_id = models.IntegerField() class Child(Parent): # This field clashes with parent "f_id" field. f = models.ForeignKey(Target, models.CASCADE) self.assertEqual(Child.check(), [ Error( "The field 'f' clashes with the field 'f_id' " "from model 'invalid_models_tests.parent'.", obj=Child._meta.get_field('f'), id='models.E006', ) ]) def test_multigeneration_inheritance(self): class GrandParent(models.Model): clash = models.IntegerField() class Parent(GrandParent): pass class Child(Parent): pass class GrandChild(Child): clash = models.IntegerField() self.assertEqual(GrandChild.check(), [ Error( "The field 'clash' clashes with the field 'clash' " "from model 'invalid_models_tests.grandparent'.", obj=GrandChild._meta.get_field('clash'), id='models.E006', ) ]) def test_id_clash(self): class Target(models.Model): pass class Model(models.Model): fk = models.ForeignKey(Target, models.CASCADE) fk_id = models.IntegerField() self.assertEqual(Model.check(), [ Error( "The field 'fk_id' clashes with the field 'fk' from model " "'invalid_models_tests.model'.", obj=Model._meta.get_field('fk_id'), id='models.E006', ) ]) @isolate_apps('invalid_models_tests') class OtherModelTests(SimpleTestCase): def test_unique_primary_key(self): invalid_id = models.IntegerField(primary_key=False) class Model(models.Model): id = invalid_id self.assertEqual(Model.check(), [ Error( "'id' can only be used as a field name if the field also sets " "'primary_key=True'.", obj=Model, id='models.E004', ), ]) def test_ordering_non_iterable(self): class Model(models.Model): class Meta: ordering = 'missing_field' self.assertEqual(Model.check(), [ Error( "'ordering' must be a tuple or list " "(even if you want to order by only one field).", obj=Model, id='models.E014', ), ]) def test_just_ordering_no_errors(self): class Model(models.Model): order = models.PositiveIntegerField() class Meta: ordering = ['order'] self.assertEqual(Model.check(), []) def test_just_order_with_respect_to_no_errors(self): class Question(models.Model): pass class Answer(models.Model): question = models.ForeignKey(Question, models.CASCADE) class Meta: order_with_respect_to = 'question' self.assertEqual(Answer.check(), []) def test_ordering_with_order_with_respect_to(self): class Question(models.Model): pass class Answer(models.Model): question = models.ForeignKey(Question, models.CASCADE) order = models.IntegerField() class Meta: order_with_respect_to = 'question' ordering = ['order'] self.assertEqual(Answer.check(), [ Error( "'ordering' and 'order_with_respect_to' cannot be used together.", obj=Answer, id='models.E021', ), ]) def test_non_valid(self): class RelationModel(models.Model): pass class Model(models.Model): relation = models.ManyToManyField(RelationModel) class Meta: ordering = ['relation'] self.assertEqual(Model.check(), [ Error( "'ordering' refers to the nonexistent field, related field, " "or lookup 'relation'.", obj=Model, id='models.E015', ), ]) def test_ordering_pointing_to_missing_field(self): class Model(models.Model): class Meta: ordering = ('missing_field',) self.assertEqual(Model.check(), [ Error( "'ordering' refers to the nonexistent field, related field, " "or lookup 'missing_field'.", obj=Model, id='models.E015', ) ]) def test_ordering_pointing_to_missing_foreignkey_field(self): class Model(models.Model): missing_fk_field = models.IntegerField() class Meta: ordering = ('missing_fk_field_id',) self.assertEqual(Model.check(), [ Error( "'ordering' refers to the nonexistent field, related field, " "or lookup 'missing_fk_field_id'.", obj=Model, id='models.E015', ) ]) def test_ordering_pointing_to_missing_related_field(self): class Model(models.Model): test = models.IntegerField() class Meta: ordering = ('missing_related__id',) self.assertEqual(Model.check(), [ Error( "'ordering' refers to the nonexistent field, related field, " "or lookup 'missing_related__id'.", obj=Model, id='models.E015', ) ]) def test_ordering_pointing_to_missing_related_model_field(self): class Parent(models.Model): pass class Child(models.Model): parent = models.ForeignKey(Parent, models.CASCADE) class Meta: ordering = ('parent__missing_field',) self.assertEqual(Child.check(), [ Error( "'ordering' refers to the nonexistent field, related field, " "or lookup 'parent__missing_field'.", obj=Child, id='models.E015', ) ]) def test_ordering_pointing_to_non_related_field(self): class Child(models.Model): parent = models.IntegerField() class Meta: ordering = ('parent__missing_field',) self.assertEqual(Child.check(), [ Error( "'ordering' refers to the nonexistent field, related field, " "or lookup 'parent__missing_field'.", obj=Child, id='models.E015', ) ]) def test_ordering_pointing_to_two_related_model_field(self): class Parent2(models.Model): pass class Parent1(models.Model): parent2 = models.ForeignKey(Parent2, models.CASCADE) class Child(models.Model): parent1 = models.ForeignKey(Parent1, models.CASCADE) class Meta: ordering = ('parent1__parent2__missing_field',) self.assertEqual(Child.check(), [ Error( "'ordering' refers to the nonexistent field, related field, " "or lookup 'parent1__parent2__missing_field'.", obj=Child, id='models.E015', ) ]) def test_ordering_pointing_multiple_times_to_model_fields(self): class Parent(models.Model): field1 = models.CharField(max_length=100) field2 = models.CharField(max_length=100) class Child(models.Model): parent = models.ForeignKey(Parent, models.CASCADE) class Meta: ordering = ('parent__field1__field2',) self.assertEqual(Child.check(), [ Error( "'ordering' refers to the nonexistent field, related field, " "or lookup 'parent__field1__field2'.", obj=Child, id='models.E015', ) ]) def test_ordering_allows_registered_lookups(self): class Model(models.Model): test = models.CharField(max_length=100) class Meta: ordering = ('test__lower',) with register_lookup(models.CharField, Lower): self.assertEqual(Model.check(), []) def test_ordering_pointing_to_related_model_pk(self): class Parent(models.Model): pass class Child(models.Model): parent = models.ForeignKey(Parent, models.CASCADE) class Meta: ordering = ('parent__pk',) self.assertEqual(Child.check(), []) def test_ordering_pointing_to_foreignkey_field(self): class Parent(models.Model): pass class Child(models.Model): parent = models.ForeignKey(Parent, models.CASCADE) class Meta: ordering = ('parent_id',) self.assertFalse(Child.check()) def test_name_beginning_with_underscore(self): class _Model(models.Model): pass self.assertEqual(_Model.check(), [ Error( "The model name '_Model' cannot start or end with an underscore " "as it collides with the query lookup syntax.", obj=_Model, id='models.E023', ) ]) def test_name_ending_with_underscore(self): class Model_(models.Model): pass self.assertEqual(Model_.check(), [ Error( "The model name 'Model_' cannot start or end with an underscore " "as it collides with the query lookup syntax.", obj=Model_, id='models.E023', ) ]) def test_name_contains_double_underscores(self): class Test__Model(models.Model): pass self.assertEqual(Test__Model.check(), [ Error( "The model name 'Test__Model' cannot contain double underscores " "as it collides with the query lookup syntax.", obj=Test__Model, id='models.E024', ) ]) def test_property_and_related_field_accessor_clash(self): class Model(models.Model): fk = models.ForeignKey('self', models.CASCADE) @property def fk_id(self): pass self.assertEqual(Model.check(), [ Error( "The property 'fk_id' clashes with a related field accessor.", obj=Model, id='models.E025', ) ]) def test_single_primary_key(self): class Model(models.Model): foo = models.IntegerField(primary_key=True) bar = models.IntegerField(primary_key=True) self.assertEqual(Model.check(), [ Error( "The model cannot have more than one field with 'primary_key=True'.", obj=Model, id='models.E026', ) ]) @override_settings(TEST_SWAPPED_MODEL_BAD_VALUE='not-a-model') def test_swappable_missing_app_name(self): class Model(models.Model): class Meta: swappable = 'TEST_SWAPPED_MODEL_BAD_VALUE' self.assertEqual(Model.check(), [ Error( "'TEST_SWAPPED_MODEL_BAD_VALUE' is not of the form 'app_label.app_name'.", id='models.E001', ), ]) @override_settings(TEST_SWAPPED_MODEL_BAD_MODEL='not_an_app.Target') def test_swappable_missing_app(self): class Model(models.Model): class Meta: swappable = 'TEST_SWAPPED_MODEL_BAD_MODEL' self.assertEqual(Model.check(), [ Error( "'TEST_SWAPPED_MODEL_BAD_MODEL' references 'not_an_app.Target', " 'which has not been installed, or is abstract.', id='models.E002', ), ]) def test_two_m2m_through_same_relationship(self): class Person(models.Model): pass class Group(models.Model): primary = models.ManyToManyField(Person, through='Membership', related_name='primary') secondary = models.ManyToManyField(Person, through='Membership', related_name='secondary') class Membership(models.Model): person = models.ForeignKey(Person, models.CASCADE) group = models.ForeignKey(Group, models.CASCADE) self.assertEqual(Group.check(), [ Error( "The model has two identical many-to-many relations through " "the intermediate model 'invalid_models_tests.Membership'.", obj=Group, id='models.E003', ) ]) def test_two_m2m_through_same_model_with_different_through_fields(self): class Country(models.Model): pass class ShippingMethod(models.Model): to_countries = models.ManyToManyField( Country, through='ShippingMethodPrice', through_fields=('method', 'to_country'), ) from_countries = models.ManyToManyField( Country, through='ShippingMethodPrice', through_fields=('method', 'from_country'), related_name='+', ) class ShippingMethodPrice(models.Model): method = models.ForeignKey(ShippingMethod, models.CASCADE) to_country = models.ForeignKey(Country, models.CASCADE) from_country = models.ForeignKey(Country, models.CASCADE) self.assertEqual(ShippingMethod.check(), []) def test_missing_parent_link(self): msg = 'Add parent_link=True to invalid_models_tests.ParkingLot.parent.' with self.assertRaisesMessage(ImproperlyConfigured, msg): class Place(models.Model): pass class ParkingLot(Place): parent = models.OneToOneField(Place, models.CASCADE) def test_m2m_table_name_clash(self): class Foo(models.Model): bar = models.ManyToManyField('Bar', db_table='myapp_bar') class Meta: db_table = 'myapp_foo' class Bar(models.Model): class Meta: db_table = 'myapp_bar' self.assertEqual(Foo.check(), [ Error( "The field's intermediary table 'myapp_bar' clashes with the " "table name of 'invalid_models_tests.Bar'.", obj=Foo._meta.get_field('bar'), id='fields.E340', ) ]) def test_m2m_field_table_name_clash(self): class Foo(models.Model): pass class Bar(models.Model): foos = models.ManyToManyField(Foo, db_table='clash') class Baz(models.Model): foos = models.ManyToManyField(Foo, db_table='clash') self.assertEqual(Bar.check() + Baz.check(), [ Error( "The field's intermediary table 'clash' clashes with the " "table name of 'invalid_models_tests.Baz.foos'.", obj=Bar._meta.get_field('foos'), id='fields.E340', ), Error( "The field's intermediary table 'clash' clashes with the " "table name of 'invalid_models_tests.Bar.foos'.", obj=Baz._meta.get_field('foos'), id='fields.E340', ) ]) def test_m2m_autogenerated_table_name_clash(self): class Foo(models.Model): class Meta: db_table = 'bar_foos' class Bar(models.Model): # The autogenerated `db_table` will be bar_foos. foos = models.ManyToManyField(Foo) class Meta: db_table = 'bar' self.assertEqual(Bar.check(), [ Error( "The field's intermediary table 'bar_foos' clashes with the " "table name of 'invalid_models_tests.Foo'.", obj=Bar._meta.get_field('foos'), id='fields.E340', ) ]) def test_m2m_unmanaged_shadow_models_not_checked(self): class A1(models.Model): pass class C1(models.Model): mm_a = models.ManyToManyField(A1, db_table='d1') # Unmanaged models that shadow the above models. Reused table names # shouldn't be flagged by any checks. class A2(models.Model): class Meta: managed = False class C2(models.Model): mm_a = models.ManyToManyField(A2, through='Intermediate') class Meta: managed = False class Intermediate(models.Model): a2 = models.ForeignKey(A2, models.CASCADE, db_column='a1_id') c2 = models.ForeignKey(C2, models.CASCADE, db_column='c1_id') class Meta: db_table = 'd1' managed = False self.assertEqual(C1.check(), []) self.assertEqual(C2.check(), []) def test_m2m_to_concrete_and_proxy_allowed(self): class A(models.Model): pass class Through(models.Model): a = models.ForeignKey('A', models.CASCADE) c = models.ForeignKey('C', models.CASCADE) class ThroughProxy(Through): class Meta: proxy = True class C(models.Model): mm_a = models.ManyToManyField(A, through=Through) mm_aproxy = models.ManyToManyField(A, through=ThroughProxy, related_name='proxied_m2m') self.assertEqual(C.check(), []) @isolate_apps('django.contrib.auth', kwarg_name='apps') def test_lazy_reference_checks(self, apps): class DummyModel(models.Model): author = models.ForeignKey('Author', models.CASCADE) class Meta: app_label = 'invalid_models_tests' class DummyClass: def __call__(self, **kwargs): pass def dummy_method(self): pass def dummy_function(*args, **kwargs): pass apps.lazy_model_operation(dummy_function, ('auth', 'imaginarymodel')) apps.lazy_model_operation(dummy_function, ('fanciful_app', 'imaginarymodel')) post_init.connect(dummy_function, sender='missing-app.Model', apps=apps) post_init.connect(DummyClass(), sender='missing-app.Model', apps=apps) post_init.connect(DummyClass().dummy_method, sender='missing-app.Model', apps=apps) self.assertEqual(_check_lazy_references(apps), [ Error( "%r contains a lazy reference to auth.imaginarymodel, " "but app 'auth' doesn't provide model 'imaginarymodel'." % dummy_function, obj=dummy_function, id='models.E022', ), Error( "%r contains a lazy reference to fanciful_app.imaginarymodel, " "but app 'fanciful_app' isn't installed." % dummy_function, obj=dummy_function, id='models.E022', ), Error( "An instance of class 'DummyClass' was connected to " "the 'post_init' signal with a lazy reference to the sender " "'missing-app.model', but app 'missing-app' isn't installed.", hint=None, obj='invalid_models_tests.test_models', id='signals.E001', ), Error( "Bound method 'DummyClass.dummy_method' was connected to the " "'post_init' signal with a lazy reference to the sender " "'missing-app.model', but app 'missing-app' isn't installed.", hint=None, obj='invalid_models_tests.test_models', id='signals.E001', ), Error( "The field invalid_models_tests.DummyModel.author was declared " "with a lazy reference to 'invalid_models_tests.author', but app " "'invalid_models_tests' isn't installed.", hint=None, obj=DummyModel.author.field, id='fields.E307', ), Error( "The function 'dummy_function' was connected to the 'post_init' " "signal with a lazy reference to the sender " "'missing-app.model', but app 'missing-app' isn't installed.", hint=None, obj='invalid_models_tests.test_models', id='signals.E001', ), ]) @isolate_apps('invalid_models_tests') class ConstraintsTests(SimpleTestCase): def test_check_constraints(self): class Model(models.Model): age = models.IntegerField() class Meta: constraints = [models.CheckConstraint(check=models.Q(age__gte=18), name='is_adult')] errors = Model.check() warn = Warning( '%s does not support check constraints.' % connection.display_name, hint=( "A constraint won't be created. Silence this warning if you " "don't care about it." ), obj=Model, id='models.W027', ) expected = [] if connection.features.supports_table_check_constraints else [warn, warn] self.assertCountEqual(errors, expected) def test_check_constraints_required_db_features(self): class Model(models.Model): age = models.IntegerField() class Meta: required_db_features = {'supports_table_check_constraints'} constraints = [models.CheckConstraint(check=models.Q(age__gte=18), name='is_adult')] self.assertEqual(Model.check(), [])
541da126124a37f7704ee36ec7676315945ff53e64c14e9baf95c6e7f396f627
import unittest from django.core.checks import Error, Warning as DjangoWarning from django.db import connection, models from django.test import SimpleTestCase, TestCase, skipIfDBFeature from django.test.utils import isolate_apps, override_settings from django.utils.functional import lazy from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ @isolate_apps('invalid_models_tests') class AutoFieldTests(SimpleTestCase): def test_valid_case(self): class Model(models.Model): id = models.AutoField(primary_key=True) field = Model._meta.get_field('id') self.assertEqual(field.check(), []) def test_primary_key(self): # primary_key must be True. Refs #12467. class Model(models.Model): field = models.AutoField(primary_key=False) # Prevent Django from autocreating `id` AutoField, which would # result in an error, because a model must have exactly one # AutoField. another = models.IntegerField(primary_key=True) field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( 'AutoFields must set primary_key=True.', obj=field, id='fields.E100', ), ]) def test_max_length_warning(self): class Model(models.Model): auto = models.AutoField(primary_key=True, max_length=2) field = Model._meta.get_field('auto') self.assertEqual(field.check(), [ DjangoWarning( "'max_length' is ignored when used with %s." % field.__class__.__name__, hint="Remove 'max_length' from field", obj=field, id='fields.W122', ), ]) @isolate_apps('invalid_models_tests') class BinaryFieldTests(SimpleTestCase): def test_valid_default_value(self): class Model(models.Model): field1 = models.BinaryField(default=b'test') field2 = models.BinaryField(default=None) for field_name in ('field1', 'field2'): field = Model._meta.get_field(field_name) self.assertEqual(field.check(), []) def test_str_default_value(self): class Model(models.Model): field = models.BinaryField(default='test') field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "BinaryField's default cannot be a string. Use bytes content " "instead.", obj=field, id='fields.E170', ), ]) @isolate_apps('invalid_models_tests') class CharFieldTests(SimpleTestCase): def test_valid_field(self): class Model(models.Model): field = models.CharField( max_length=255, choices=[ ('1', 'item1'), ('2', 'item2'), ], db_index=True, ) field = Model._meta.get_field('field') self.assertEqual(field.check(), []) def test_missing_max_length(self): class Model(models.Model): field = models.CharField() field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "CharFields must define a 'max_length' attribute.", obj=field, id='fields.E120', ), ]) def test_negative_max_length(self): class Model(models.Model): field = models.CharField(max_length=-1) field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "'max_length' must be a positive integer.", obj=field, id='fields.E121', ), ]) def test_bad_max_length_value(self): class Model(models.Model): field = models.CharField(max_length="bad") field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "'max_length' must be a positive integer.", obj=field, id='fields.E121', ), ]) def test_str_max_length_value(self): class Model(models.Model): field = models.CharField(max_length='20') field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "'max_length' must be a positive integer.", obj=field, id='fields.E121', ), ]) def test_str_max_length_type(self): class Model(models.Model): field = models.CharField(max_length=True) field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "'max_length' must be a positive integer.", obj=field, id='fields.E121' ), ]) def test_non_iterable_choices(self): class Model(models.Model): field = models.CharField(max_length=10, choices='bad') field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "'choices' must be an iterable (e.g., a list or tuple).", obj=field, id='fields.E004', ), ]) def test_non_iterable_choices_two_letters(self): """Two letters isn't a valid choice pair.""" class Model(models.Model): field = models.CharField(max_length=10, choices=['ab']) field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "'choices' must be an iterable containing (actual value, " "human readable name) tuples.", obj=field, id='fields.E005', ), ]) def test_iterable_of_iterable_choices(self): class ThingItem: def __init__(self, value, display): self.value = value self.display = display def __iter__(self): return iter((self.value, self.display)) def __len__(self): return 2 class Things: def __iter__(self): return iter((ThingItem(1, 2), ThingItem(3, 4))) class ThingWithIterableChoices(models.Model): thing = models.CharField(max_length=100, blank=True, choices=Things()) self.assertEqual(ThingWithIterableChoices._meta.get_field('thing').check(), []) def test_choices_containing_non_pairs(self): class Model(models.Model): field = models.CharField(max_length=10, choices=[(1, 2, 3), (1, 2, 3)]) class Model2(models.Model): field = models.IntegerField(choices=[0]) for model in (Model, Model2): with self.subTest(model.__name__): field = model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "'choices' must be an iterable containing (actual " "value, human readable name) tuples.", obj=field, id='fields.E005', ), ]) def test_choices_containing_lazy(self): class Model(models.Model): field = models.CharField(max_length=10, choices=[['1', _('1')], ['2', _('2')]]) self.assertEqual(Model._meta.get_field('field').check(), []) def test_lazy_choices(self): class Model(models.Model): field = models.CharField(max_length=10, choices=lazy(lambda: [[1, '1'], [2, '2']], tuple)()) self.assertEqual(Model._meta.get_field('field').check(), []) def test_choices_named_group(self): class Model(models.Model): field = models.CharField( max_length=10, choices=[ ['knights', [['L', 'Lancelot'], ['G', 'Galahad']]], ['wizards', [['T', 'Tim the Enchanter']]], ['R', 'Random character'], ], ) self.assertEqual(Model._meta.get_field('field').check(), []) def test_choices_named_group_non_pairs(self): class Model(models.Model): field = models.CharField( max_length=10, choices=[['knights', [['L', 'Lancelot', 'Du Lac']]]], ) field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "'choices' must be an iterable containing (actual value, " "human readable name) tuples.", obj=field, id='fields.E005', ), ]) def test_choices_named_group_bad_structure(self): class Model(models.Model): field = models.CharField( max_length=10, choices=[ ['knights', [ ['Noble', [['G', 'Galahad']]], ['Combative', [['L', 'Lancelot']]], ]], ], ) field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "'choices' must be an iterable containing (actual value, " "human readable name) tuples.", obj=field, id='fields.E005', ), ]) def test_choices_named_group_lazy(self): class Model(models.Model): field = models.CharField( max_length=10, choices=[ [_('knights'), [['L', _('Lancelot')], ['G', _('Galahad')]]], ['R', _('Random character')], ], ) self.assertEqual(Model._meta.get_field('field').check(), []) def test_choices_in_max_length(self): class Model(models.Model): field = models.CharField( max_length=2, choices=[ ('ABC', 'Value Too Long!'), ('OK', 'Good') ], ) group = models.CharField( max_length=2, choices=[ ('Nested', [('OK', 'Good'), ('Longer', 'Longer')]), ('Grouped', [('Bad', 'Bad')]), ], ) for name, choice_max_length in (('field', 3), ('group', 6)): with self.subTest(name): field = Model._meta.get_field(name) self.assertEqual(field.check(), [ Error( "'max_length' is too small to fit the longest value " "in 'choices' (%d characters)." % choice_max_length, obj=field, id='fields.E009', ), ]) def test_bad_db_index_value(self): class Model(models.Model): field = models.CharField(max_length=10, db_index='bad') field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "'db_index' must be None, True or False.", obj=field, id='fields.E006', ), ]) def test_bad_validators(self): class Model(models.Model): field = models.CharField(max_length=10, validators=[True]) field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "All 'validators' must be callable.", hint=( "validators[0] (True) isn't a function or instance of a " "validator class." ), obj=field, id='fields.E008', ), ]) @unittest.skipUnless(connection.vendor == 'mysql', "Test valid only for MySQL") def test_too_long_char_field_under_mysql(self): from django.db.backends.mysql.validation import DatabaseValidation class Model(models.Model): field = models.CharField(unique=True, max_length=256) field = Model._meta.get_field('field') validator = DatabaseValidation(connection=connection) self.assertEqual(validator.check_field(field), [ Error( 'MySQL does not allow unique CharFields to have a max_length > 255.', obj=field, id='mysql.E001', ) ]) @isolate_apps('invalid_models_tests') class DateFieldTests(SimpleTestCase): maxDiff = None def test_auto_now_and_auto_now_add_raise_error(self): class Model(models.Model): field0 = models.DateTimeField(auto_now=True, auto_now_add=True, default=now) field1 = models.DateTimeField(auto_now=True, auto_now_add=False, default=now) field2 = models.DateTimeField(auto_now=False, auto_now_add=True, default=now) field3 = models.DateTimeField(auto_now=True, auto_now_add=True, default=None) expected = [] checks = [] for i in range(4): field = Model._meta.get_field('field%d' % i) expected.append(Error( "The options auto_now, auto_now_add, and default " "are mutually exclusive. Only one of these options " "may be present.", obj=field, id='fields.E160', )) checks.extend(field.check()) self.assertEqual(checks, expected) def test_fix_default_value(self): class Model(models.Model): field_dt = models.DateField(default=now()) field_d = models.DateField(default=now().date()) field_now = models.DateField(default=now) field_dt = Model._meta.get_field('field_dt') field_d = Model._meta.get_field('field_d') field_now = Model._meta.get_field('field_now') errors = field_dt.check() errors.extend(field_d.check()) errors.extend(field_now.check()) # doesn't raise a warning self.assertEqual(errors, [ DjangoWarning( 'Fixed default value provided.', hint='It seems you set a fixed date / time / datetime ' 'value as default for this field. This may not be ' 'what you want. If you want to have the current date ' 'as default, use `django.utils.timezone.now`', obj=field_dt, id='fields.W161', ), DjangoWarning( 'Fixed default value provided.', hint='It seems you set a fixed date / time / datetime ' 'value as default for this field. This may not be ' 'what you want. If you want to have the current date ' 'as default, use `django.utils.timezone.now`', obj=field_d, id='fields.W161', ) ]) @override_settings(USE_TZ=True) def test_fix_default_value_tz(self): self.test_fix_default_value() @isolate_apps('invalid_models_tests') class DateTimeFieldTests(SimpleTestCase): maxDiff = None def test_fix_default_value(self): class Model(models.Model): field_dt = models.DateTimeField(default=now()) field_d = models.DateTimeField(default=now().date()) field_now = models.DateTimeField(default=now) field_dt = Model._meta.get_field('field_dt') field_d = Model._meta.get_field('field_d') field_now = Model._meta.get_field('field_now') errors = field_dt.check() errors.extend(field_d.check()) errors.extend(field_now.check()) # doesn't raise a warning self.assertEqual(errors, [ DjangoWarning( 'Fixed default value provided.', hint='It seems you set a fixed date / time / datetime ' 'value as default for this field. This may not be ' 'what you want. If you want to have the current date ' 'as default, use `django.utils.timezone.now`', obj=field_dt, id='fields.W161', ), DjangoWarning( 'Fixed default value provided.', hint='It seems you set a fixed date / time / datetime ' 'value as default for this field. This may not be ' 'what you want. If you want to have the current date ' 'as default, use `django.utils.timezone.now`', obj=field_d, id='fields.W161', ) ]) @override_settings(USE_TZ=True) def test_fix_default_value_tz(self): self.test_fix_default_value() @isolate_apps('invalid_models_tests') class DecimalFieldTests(SimpleTestCase): def test_required_attributes(self): class Model(models.Model): field = models.DecimalField() field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "DecimalFields must define a 'decimal_places' attribute.", obj=field, id='fields.E130', ), Error( "DecimalFields must define a 'max_digits' attribute.", obj=field, id='fields.E132', ), ]) def test_negative_max_digits_and_decimal_places(self): class Model(models.Model): field = models.DecimalField(max_digits=-1, decimal_places=-1) field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "'decimal_places' must be a non-negative integer.", obj=field, id='fields.E131', ), Error( "'max_digits' must be a positive integer.", obj=field, id='fields.E133', ), ]) def test_bad_values_of_max_digits_and_decimal_places(self): class Model(models.Model): field = models.DecimalField(max_digits="bad", decimal_places="bad") field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "'decimal_places' must be a non-negative integer.", obj=field, id='fields.E131', ), Error( "'max_digits' must be a positive integer.", obj=field, id='fields.E133', ), ]) def test_decimal_places_greater_than_max_digits(self): class Model(models.Model): field = models.DecimalField(max_digits=9, decimal_places=10) field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "'max_digits' must be greater or equal to 'decimal_places'.", obj=field, id='fields.E134', ), ]) def test_valid_field(self): class Model(models.Model): field = models.DecimalField(max_digits=10, decimal_places=10) field = Model._meta.get_field('field') self.assertEqual(field.check(), []) @isolate_apps('invalid_models_tests') class FileFieldTests(SimpleTestCase): def test_valid_default_case(self): class Model(models.Model): field = models.FileField() self.assertEqual(Model._meta.get_field('field').check(), []) def test_valid_case(self): class Model(models.Model): field = models.FileField(upload_to='somewhere') field = Model._meta.get_field('field') self.assertEqual(field.check(), []) def test_primary_key(self): class Model(models.Model): field = models.FileField(primary_key=False, upload_to='somewhere') field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "'primary_key' is not a valid argument for a FileField.", obj=field, id='fields.E201', ) ]) def test_upload_to_starts_with_slash(self): class Model(models.Model): field = models.FileField(upload_to='/somewhere') field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "FileField's 'upload_to' argument must be a relative path, not " "an absolute path.", obj=field, id='fields.E202', hint='Remove the leading slash.', ) ]) def test_upload_to_callable_not_checked(self): def callable(instance, filename): return '/' + filename class Model(models.Model): field = models.FileField(upload_to=callable) field = Model._meta.get_field('field') self.assertEqual(field.check(), []) @isolate_apps('invalid_models_tests') class FilePathFieldTests(SimpleTestCase): def test_forbidden_files_and_folders(self): class Model(models.Model): field = models.FilePathField(allow_files=False, allow_folders=False) field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( "FilePathFields must have either 'allow_files' or 'allow_folders' set to True.", obj=field, id='fields.E140', ), ]) @isolate_apps('invalid_models_tests') class GenericIPAddressFieldTests(SimpleTestCase): def test_non_nullable_blank(self): class Model(models.Model): field = models.GenericIPAddressField(null=False, blank=True) field = Model._meta.get_field('field') self.assertEqual(field.check(), [ Error( ('GenericIPAddressFields cannot have blank=True if null=False, ' 'as blank values are stored as nulls.'), obj=field, id='fields.E150', ), ]) @isolate_apps('invalid_models_tests') class ImageFieldTests(SimpleTestCase): def test_pillow_installed(self): try: from PIL import Image # NOQA except ImportError: pillow_installed = False else: pillow_installed = True class Model(models.Model): field = models.ImageField(upload_to='somewhere') field = Model._meta.get_field('field') errors = field.check() expected = [] if pillow_installed else [ Error( 'Cannot use ImageField because Pillow is not installed.', hint=('Get Pillow at https://pypi.org/project/Pillow/ ' 'or run command "python -m pip install Pillow".'), obj=field, id='fields.E210', ), ] self.assertEqual(errors, expected) @isolate_apps('invalid_models_tests') class IntegerFieldTests(SimpleTestCase): def test_max_length_warning(self): class Model(models.Model): integer = models.IntegerField(max_length=2) biginteger = models.BigIntegerField(max_length=2) smallinteger = models.SmallIntegerField(max_length=2) positiveinteger = models.PositiveIntegerField(max_length=2) positivesmallinteger = models.PositiveSmallIntegerField(max_length=2) for field in Model._meta.get_fields(): if field.auto_created: continue with self.subTest(name=field.name): self.assertEqual(field.check(), [ DjangoWarning( "'max_length' is ignored when used with %s." % field.__class__.__name__, hint="Remove 'max_length' from field", obj=field, id='fields.W122', ) ]) @isolate_apps('invalid_models_tests') class TimeFieldTests(SimpleTestCase): maxDiff = None def test_fix_default_value(self): class Model(models.Model): field_dt = models.TimeField(default=now()) field_t = models.TimeField(default=now().time()) field_now = models.DateField(default=now) field_dt = Model._meta.get_field('field_dt') field_t = Model._meta.get_field('field_t') field_now = Model._meta.get_field('field_now') errors = field_dt.check() errors.extend(field_t.check()) errors.extend(field_now.check()) # doesn't raise a warning self.assertEqual(errors, [ DjangoWarning( 'Fixed default value provided.', hint='It seems you set a fixed date / time / datetime ' 'value as default for this field. This may not be ' 'what you want. If you want to have the current date ' 'as default, use `django.utils.timezone.now`', obj=field_dt, id='fields.W161', ), DjangoWarning( 'Fixed default value provided.', hint='It seems you set a fixed date / time / datetime ' 'value as default for this field. This may not be ' 'what you want. If you want to have the current date ' 'as default, use `django.utils.timezone.now`', obj=field_t, id='fields.W161', ) ]) @override_settings(USE_TZ=True) def test_fix_default_value_tz(self): self.test_fix_default_value() @isolate_apps('invalid_models_tests') class TextFieldTests(TestCase): @skipIfDBFeature('supports_index_on_text_field') def test_max_length_warning(self): class Model(models.Model): value = models.TextField(db_index=True) field = Model._meta.get_field('value') field_type = field.db_type(connection) self.assertEqual(field.check(), [ DjangoWarning( '%s does not support a database index on %s columns.' % (connection.display_name, field_type), hint=( "An index won't be created. Silence this warning if you " "don't care about it." ), obj=field, id='fields.W162', ) ])
97367d92e2936c811335e56bebd310b0c896c8311e7e77fee1301041890772b0
import asyncore import base64 import mimetypes import os import shutil import smtpd import sys import tempfile import threading from email import charset, message_from_binary_file, message_from_bytes from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr from io import StringIO from smtplib import SMTP, SMTPAuthenticationError, SMTPException from ssl import SSLError from unittest import mock from django.core import mail from django.core.mail import ( DNS_NAME, EmailMessage, EmailMultiAlternatives, mail_admins, mail_managers, send_mail, send_mass_mail, ) from django.core.mail.backends import console, dummy, filebased, locmem, smtp from django.core.mail.message import BadHeaderError, sanitize_address from django.test import SimpleTestCase, override_settings from django.test.utils import requires_tz_support from django.utils.translation import gettext_lazy class HeadersCheckMixin: def assertMessageHasHeaders(self, message, headers): """ Asserts that the `message` has all `headers`. message: can be an instance of an email.Message subclass or a string with the contents of an email message. headers: should be a set of (header-name, header-value) tuples. """ if isinstance(message, bytes): message = message_from_bytes(message) msg_headers = set(message.items()) self.assertTrue(headers.issubset(msg_headers), msg='Message is missing ' 'the following headers: %s' % (headers - msg_headers),) class MailTests(HeadersCheckMixin, SimpleTestCase): """ Non-backend specific tests. """ def get_decoded_attachments(self, django_message): """ Encode the specified django.core.mail.message.EmailMessage, then decode it using Python's email.parser module and, for each attachment of the message, return a list of tuples with (filename, content, mimetype). """ msg_bytes = django_message.message().as_bytes() email_message = message_from_bytes(msg_bytes) def iter_attachments(): for i in email_message.walk(): if i.get_content_disposition() == 'attachment': filename = i.get_filename() content = i.get_payload(decode=True) mimetype = i.get_content_type() yield filename, content, mimetype return list(iter_attachments()) def test_ascii(self): email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]']) message = email.message() self.assertEqual(message['Subject'], 'Subject') self.assertEqual(message.get_payload(), 'Content') self.assertEqual(message['From'], '[email protected]') self.assertEqual(message['To'], '[email protected]') def test_multiple_recipients(self): email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]', '[email protected]']) message = email.message() self.assertEqual(message['Subject'], 'Subject') self.assertEqual(message.get_payload(), 'Content') self.assertEqual(message['From'], '[email protected]') self.assertEqual(message['To'], '[email protected], [email protected]') def test_header_omitted_for_no_to_recipients(self): message = EmailMessage('Subject', 'Content', '[email protected]', cc=['[email protected]']).message() self.assertNotIn('To', message) def test_recipients_with_empty_strings(self): """ Empty strings in various recipient arguments are always stripped off the final recipient list. """ email = EmailMessage( 'Subject', 'Content', '[email protected]', ['[email protected]', ''], cc=['[email protected]', ''], bcc=['', '[email protected]'], reply_to=['', None], ) self.assertEqual( email.recipients(), ['[email protected]', '[email protected]', '[email protected]'] ) def test_cc(self): """Regression test for #7722""" email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], cc=['[email protected]']) message = email.message() self.assertEqual(message['Cc'], '[email protected]') self.assertEqual(email.recipients(), ['[email protected]', '[email protected]']) # Test multiple CC with multiple To email = EmailMessage( 'Subject', 'Content', '[email protected]', ['[email protected]', '[email protected]'], cc=['[email protected]', '[email protected]'] ) message = email.message() self.assertEqual(message['Cc'], '[email protected], [email protected]') self.assertEqual( email.recipients(), ['[email protected]', '[email protected]', '[email protected]', '[email protected]'] ) # Testing with Bcc email = EmailMessage( 'Subject', 'Content', '[email protected]', ['[email protected]', '[email protected]'], cc=['[email protected]', '[email protected]'], bcc=['[email protected]'] ) message = email.message() self.assertEqual(message['Cc'], '[email protected], [email protected]') self.assertEqual( email.recipients(), ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]'] ) def test_cc_headers(self): message = EmailMessage( 'Subject', 'Content', '[email protected]', ['[email protected]'], cc=['[email protected]'], headers={'Cc': '[email protected]'}, ).message() self.assertEqual(message['Cc'], '[email protected]') def test_cc_in_headers_only(self): message = EmailMessage( 'Subject', 'Content', '[email protected]', ['[email protected]'], headers={'Cc': '[email protected]'}, ).message() self.assertEqual(message['Cc'], '[email protected]') def test_reply_to(self): email = EmailMessage( 'Subject', 'Content', '[email protected]', ['[email protected]'], reply_to=['[email protected]'], ) message = email.message() self.assertEqual(message['Reply-To'], '[email protected]') email = EmailMessage( 'Subject', 'Content', '[email protected]', ['[email protected]'], reply_to=['[email protected]', '[email protected]'] ) message = email.message() self.assertEqual(message['Reply-To'], '[email protected], [email protected]') def test_recipients_as_tuple(self): email = EmailMessage( 'Subject', 'Content', '[email protected]', ('[email protected]', '[email protected]'), cc=('[email protected]', '[email protected]'), bcc=('[email protected]',) ) message = email.message() self.assertEqual(message['Cc'], '[email protected], [email protected]') self.assertEqual( email.recipients(), ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]'] ) def test_recipients_as_string(self): with self.assertRaisesMessage(TypeError, '"to" argument must be a list or tuple'): EmailMessage(to='[email protected]') with self.assertRaisesMessage(TypeError, '"cc" argument must be a list or tuple'): EmailMessage(cc='[email protected]') with self.assertRaisesMessage(TypeError, '"bcc" argument must be a list or tuple'): EmailMessage(bcc='[email protected]') with self.assertRaisesMessage(TypeError, '"reply_to" argument must be a list or tuple'): EmailMessage(reply_to='[email protected]') def test_header_injection(self): email = EmailMessage('Subject\nInjection Test', 'Content', '[email protected]', ['[email protected]']) with self.assertRaises(BadHeaderError): email.message() email = EmailMessage( gettext_lazy('Subject\nInjection Test'), 'Content', '[email protected]', ['[email protected]'] ) with self.assertRaises(BadHeaderError): email.message() def test_space_continuation(self): """ Test for space continuation character in long (ASCII) subject headers (#7747) """ email = EmailMessage( 'Long subject lines that get wrapped should contain a space ' 'continuation character to get expected behavior in Outlook and Thunderbird', 'Content', '[email protected]', ['[email protected]'] ) message = email.message() self.assertEqual( message['Subject'].encode(), b'Long subject lines that get wrapped should contain a space continuation\n' b' character to get expected behavior in Outlook and Thunderbird' ) def test_message_header_overrides(self): """ Specifying dates or message-ids in the extra headers overrides the default values (#9233) """ headers = {"date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} email = EmailMessage('subject', 'content', '[email protected]', ['[email protected]'], headers=headers) self.assertMessageHasHeaders(email.message(), { ('Content-Transfer-Encoding', '7bit'), ('Content-Type', 'text/plain; charset="utf-8"'), ('From', '[email protected]'), ('MIME-Version', '1.0'), ('Message-ID', 'foo'), ('Subject', 'subject'), ('To', '[email protected]'), ('date', 'Fri, 09 Nov 2001 01:08:47 -0000'), }) def test_from_header(self): """ Make sure we can manually set the From header (#9214) """ email = EmailMessage( 'Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}, ) message = email.message() self.assertEqual(message['From'], '[email protected]') def test_to_header(self): """ Make sure we can manually set the To header (#17444) """ email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]', '[email protected]'], headers={'To': '[email protected]'}) message = email.message() self.assertEqual(message['To'], '[email protected]') self.assertEqual(email.to, ['[email protected]', '[email protected]']) # If we don't set the To header manually, it should default to the `to` argument to the constructor email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]', '[email protected]']) message = email.message() self.assertEqual(message['To'], '[email protected], [email protected]') self.assertEqual(email.to, ['[email protected]', '[email protected]']) def test_to_in_headers_only(self): message = EmailMessage( 'Subject', 'Content', '[email protected]', headers={'To': '[email protected]'}, ).message() self.assertEqual(message['To'], '[email protected]') def test_reply_to_header(self): """ Specifying 'Reply-To' in headers should override reply_to. """ email = EmailMessage( 'Subject', 'Content', '[email protected]', ['[email protected]'], reply_to=['[email protected]'], headers={'Reply-To': '[email protected]'}, ) message = email.message() self.assertEqual(message['Reply-To'], '[email protected]') def test_reply_to_in_headers_only(self): message = EmailMessage( 'Subject', 'Content', '[email protected]', ['[email protected]'], headers={'Reply-To': '[email protected]'}, ).message() self.assertEqual(message['Reply-To'], '[email protected]') def test_multiple_message_call(self): """ Regression for #13259 - Make sure that headers are not changed when calling EmailMessage.message() """ email = EmailMessage( 'Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}, ) message = email.message() self.assertEqual(message['From'], '[email protected]') message = email.message() self.assertEqual(message['From'], '[email protected]') def test_unicode_address_header(self): """ Regression for #11144 - When a to/from/cc header contains unicode, make sure the email addresses are parsed correctly (especially with regards to commas) """ email = EmailMessage( 'Subject', 'Content', '[email protected]', ['"Firstname Sürname" <[email protected]>', '[email protected]'], ) self.assertEqual( email.message()['To'], '=?utf-8?q?Firstname_S=C3=BCrname?= <[email protected]>, [email protected]' ) email = EmailMessage( 'Subject', 'Content', '[email protected]', ['"Sürname, Firstname" <[email protected]>', '[email protected]'], ) self.assertEqual( email.message()['To'], '=?utf-8?q?S=C3=BCrname=2C_Firstname?= <[email protected]>, [email protected]' ) def test_unicode_headers(self): email = EmailMessage( 'Gżegżółka', 'Content', '[email protected]', ['[email protected]'], headers={ 'Sender': '"Firstname Sürname" <[email protected]>', 'Comments': 'My Sürname is non-ASCII', }, ) message = email.message() self.assertEqual(message['Subject'], '=?utf-8?b?R8W8ZWfFvMOzxYJrYQ==?=') self.assertEqual(message['Sender'], '=?utf-8?q?Firstname_S=C3=BCrname?= <[email protected]>') self.assertEqual(message['Comments'], '=?utf-8?q?My_S=C3=BCrname_is_non-ASCII?=') def test_safe_mime_multipart(self): """ Make sure headers can be set with a different encoding than utf-8 in SafeMIMEMultipart as well """ headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} from_email, to = '[email protected]', '"Sürname, Firstname" <[email protected]>' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives('Message from Firstname Sürname', text_content, from_email, [to], headers=headers) msg.attach_alternative(html_content, "text/html") msg.encoding = 'iso-8859-1' self.assertEqual(msg.message()['To'], '=?iso-8859-1?q?S=FCrname=2C_Firstname?= <[email protected]>') self.assertEqual(msg.message()['Subject'], '=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=') def test_safe_mime_multipart_with_attachments(self): """ EmailMultiAlternatives includes alternatives if the body is empty and it has attachments. """ msg = EmailMultiAlternatives(body='') html_content = '<p>This is <strong>html</strong></p>' msg.attach_alternative(html_content, 'text/html') msg.attach('example.txt', 'Text file content', 'text/plain') self.assertIn(html_content, msg.message().as_string()) def test_none_body(self): msg = EmailMessage('subject', None, '[email protected]', ['[email protected]']) self.assertEqual(msg.body, '') self.assertEqual(msg.message().get_payload(), '') @mock.patch('socket.getfqdn', return_value='漢字') def test_non_ascii_dns_non_unicode_email(self, mocked_getfqdn): delattr(DNS_NAME, '_fqdn') email = EmailMessage('subject', 'content', '[email protected]', ['[email protected]']) email.encoding = 'iso-8859-1' self.assertIn('@xn--p8s937b>', email.message()['Message-ID']) def test_encoding(self): """ Regression for #12791 - Encode body correctly with other encodings than utf-8 """ email = EmailMessage('Subject', 'Firstname Sürname is a great guy.', '[email protected]', ['[email protected]']) email.encoding = 'iso-8859-1' message = email.message() self.assertMessageHasHeaders(message, { ('MIME-Version', '1.0'), ('Content-Type', 'text/plain; charset="iso-8859-1"'), ('Content-Transfer-Encoding', 'quoted-printable'), ('Subject', 'Subject'), ('From', '[email protected]'), ('To', '[email protected]')}) self.assertEqual(message.get_payload(), 'Firstname S=FCrname is a great guy.') # Make sure MIME attachments also works correctly with other encodings than utf-8 text_content = 'Firstname Sürname is a great guy.' html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>' msg = EmailMultiAlternatives('Subject', text_content, '[email protected]', ['[email protected]']) msg.encoding = 'iso-8859-1' msg.attach_alternative(html_content, "text/html") payload0 = msg.message().get_payload(0) self.assertMessageHasHeaders(payload0, { ('MIME-Version', '1.0'), ('Content-Type', 'text/plain; charset="iso-8859-1"'), ('Content-Transfer-Encoding', 'quoted-printable')}) self.assertTrue(payload0.as_bytes().endswith(b'\n\nFirstname S=FCrname is a great guy.')) payload1 = msg.message().get_payload(1) self.assertMessageHasHeaders(payload1, { ('MIME-Version', '1.0'), ('Content-Type', 'text/html; charset="iso-8859-1"'), ('Content-Transfer-Encoding', 'quoted-printable')}) self.assertTrue( payload1.as_bytes().endswith(b'\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>') ) def test_attachments(self): """Regression test for #9367""" headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} subject, from_email, to = 'hello', '[email protected]', '[email protected]' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to], headers=headers) msg.attach_alternative(html_content, "text/html") msg.attach("an attachment.pdf", b"%PDF-1.4.%...", mimetype="application/pdf") msg_bytes = msg.message().as_bytes() message = message_from_bytes(msg_bytes) self.assertTrue(message.is_multipart()) self.assertEqual(message.get_content_type(), 'multipart/mixed') self.assertEqual(message.get_default_type(), 'text/plain') payload = message.get_payload() self.assertEqual(payload[0].get_content_type(), 'multipart/alternative') self.assertEqual(payload[1].get_content_type(), 'application/pdf') def test_attachments_two_tuple(self): msg = EmailMessage(attachments=[('filename1', 'content1')]) filename, content, mimetype = self.get_decoded_attachments(msg)[0] self.assertEqual(filename, 'filename1') self.assertEqual(content, b'content1') self.assertEqual(mimetype, 'application/octet-stream') def test_attachments_MIMEText(self): txt = MIMEText('content1') msg = EmailMessage(attachments=[txt]) payload = msg.message().get_payload() self.assertEqual(payload[0], txt) def test_non_ascii_attachment_filename(self): """Regression test for #14964""" headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} subject, from_email, to = 'hello', '[email protected]', '[email protected]' content = 'This is the message.' msg = EmailMessage(subject, content, from_email, [to], headers=headers) # Unicode in file name msg.attach("une pièce jointe.pdf", b"%PDF-1.4.%...", mimetype="application/pdf") msg_bytes = msg.message().as_bytes() message = message_from_bytes(msg_bytes) payload = message.get_payload() self.assertEqual(payload[1].get_filename(), 'une pièce jointe.pdf') def test_attach_file(self): """ Test attaching a file against different mimetypes and make sure that a file will be attached and sent properly even if an invalid mimetype is specified. """ files = ( # filename, actual mimetype ('file.txt', 'text/plain'), ('file.png', 'image/png'), ('file_txt', None), ('file_png', None), ('file_txt.png', 'image/png'), ('file_png.txt', 'text/plain'), ('file.eml', 'message/rfc822'), ) test_mimetypes = ['text/plain', 'image/png', None] for basename, real_mimetype in files: for mimetype in test_mimetypes: email = EmailMessage('subject', 'body', '[email protected]', ['[email protected]']) self.assertEqual(mimetypes.guess_type(basename)[0], real_mimetype) self.assertEqual(email.attachments, []) file_path = os.path.join(os.path.dirname(__file__), 'attachments', basename) email.attach_file(file_path, mimetype=mimetype) self.assertEqual(len(email.attachments), 1) self.assertIn(basename, email.attachments[0]) msgs_sent_num = email.send() self.assertEqual(msgs_sent_num, 1) def test_attach_text_as_bytes(self): msg = EmailMessage('subject', 'body', '[email protected]', ['[email protected]']) msg.attach('file.txt', b'file content') sent_num = msg.send() self.assertEqual(sent_num, 1) filename, content, mimetype = self.get_decoded_attachments(msg)[0] self.assertEqual(filename, 'file.txt') self.assertEqual(content, b'file content') self.assertEqual(mimetype, 'text/plain') def test_attach_utf8_text_as_bytes(self): """ Non-ASCII characters encoded as valid UTF-8 are correctly transported and decoded. """ msg = EmailMessage('subject', 'body', '[email protected]', ['[email protected]']) msg.attach('file.txt', b'\xc3\xa4') # UTF-8 encoded a umlaut. filename, content, mimetype = self.get_decoded_attachments(msg)[0] self.assertEqual(filename, 'file.txt') self.assertEqual(content, b'\xc3\xa4') self.assertEqual(mimetype, 'text/plain') def test_attach_non_utf8_text_as_bytes(self): """ Binary data that can't be decoded as UTF-8 overrides the MIME type instead of decoding the data. """ msg = EmailMessage('subject', 'body', '[email protected]', ['[email protected]']) msg.attach('file.txt', b'\xff') # Invalid UTF-8. filename, content, mimetype = self.get_decoded_attachments(msg)[0] self.assertEqual(filename, 'file.txt') # Content should be passed through unmodified. self.assertEqual(content, b'\xff') self.assertEqual(mimetype, 'application/octet-stream') def test_dummy_backend(self): """ Make sure that dummy backends returns correct number of sent messages """ connection = dummy.EmailBackend() email = EmailMessage( 'Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}, ) self.assertEqual(connection.send_messages([email, email, email]), 3) def test_arbitrary_keyword(self): """ Make sure that get_connection() accepts arbitrary keyword that might be used with custom backends. """ c = mail.get_connection(fail_silently=True, foo='bar') self.assertTrue(c.fail_silently) def test_custom_backend(self): """Test custom backend defined in this suite.""" conn = mail.get_connection('mail.custombackend.EmailBackend') self.assertTrue(hasattr(conn, 'test_outbox')) email = EmailMessage( 'Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}, ) conn.send_messages([email]) self.assertEqual(len(conn.test_outbox), 1) def test_backend_arg(self): """Test backend argument of mail.get_connection()""" self.assertIsInstance(mail.get_connection('django.core.mail.backends.smtp.EmailBackend'), smtp.EmailBackend) self.assertIsInstance( mail.get_connection('django.core.mail.backends.locmem.EmailBackend'), locmem.EmailBackend ) self.assertIsInstance(mail.get_connection('django.core.mail.backends.dummy.EmailBackend'), dummy.EmailBackend) self.assertIsInstance( mail.get_connection('django.core.mail.backends.console.EmailBackend'), console.EmailBackend ) with tempfile.TemporaryDirectory() as tmp_dir: self.assertIsInstance( mail.get_connection('django.core.mail.backends.filebased.EmailBackend', file_path=tmp_dir), filebased.EmailBackend ) self.assertIsInstance(mail.get_connection(), locmem.EmailBackend) @override_settings( EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend', ADMINS=[('nobody', '[email protected]')], MANAGERS=[('nobody', '[email protected]')]) def test_connection_arg(self): """Test connection argument to send_mail(), et. al.""" mail.outbox = [] # Send using non-default connection connection = mail.get_connection('mail.custombackend.EmailBackend') send_mail('Subject', 'Content', '[email protected]', ['[email protected]'], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, 'Subject') connection = mail.get_connection('mail.custombackend.EmailBackend') send_mass_mail([ ('Subject1', 'Content1', '[email protected]', ['[email protected]']), ('Subject2', 'Content2', '[email protected]', ['[email protected]']), ], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 2) self.assertEqual(connection.test_outbox[0].subject, 'Subject1') self.assertEqual(connection.test_outbox[1].subject, 'Subject2') connection = mail.get_connection('mail.custombackend.EmailBackend') mail_admins('Admin message', 'Content', connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, '[Django] Admin message') connection = mail.get_connection('mail.custombackend.EmailBackend') mail_managers('Manager message', 'Content', connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, '[Django] Manager message') def test_dont_mangle_from_in_body(self): # Regression for #13433 - Make sure that EmailMessage doesn't mangle # 'From ' in message body. email = EmailMessage( 'Subject', 'From the future', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}, ) self.assertNotIn(b'>From the future', email.message().as_bytes()) def test_dont_base64_encode(self): # Ticket #3472 # Shouldn't use Base64 encoding at all msg = EmailMessage( 'Subject', 'UTF-8 encoded body', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}, ) self.assertIn(b'Content-Transfer-Encoding: 7bit', msg.message().as_bytes()) # Ticket #11212 # Shouldn't use quoted printable, should detect it can represent content with 7 bit data msg = EmailMessage( 'Subject', 'Body with only ASCII characters.', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}, ) s = msg.message().as_bytes() self.assertIn(b'Content-Transfer-Encoding: 7bit', s) # Shouldn't use quoted printable, should detect it can represent content with 8 bit data msg = EmailMessage( 'Subject', 'Body with latin characters: àáä.', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}, ) s = msg.message().as_bytes() self.assertIn(b'Content-Transfer-Encoding: 8bit', s) s = msg.message().as_string() self.assertIn('Content-Transfer-Encoding: 8bit', s) msg = EmailMessage( 'Subject', 'Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}, ) s = msg.message().as_bytes() self.assertIn(b'Content-Transfer-Encoding: 8bit', s) s = msg.message().as_string() self.assertIn('Content-Transfer-Encoding: 8bit', s) def test_dont_base64_encode_message_rfc822(self): # Ticket #18967 # Shouldn't use base64 encoding for a child EmailMessage attachment. # Create a child message first child_msg = EmailMessage( 'Child Subject', 'Some body of child message', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}, ) child_s = child_msg.message().as_string() # Now create a parent parent_msg = EmailMessage( 'Parent Subject', 'Some parent body', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}, ) # Attach to parent as a string parent_msg.attach(content=child_s, mimetype='message/rfc822') parent_s = parent_msg.message().as_string() # The child message header is not base64 encoded self.assertIn('Child Subject', parent_s) # Feature test: try attaching email.Message object directly to the mail. parent_msg = EmailMessage( 'Parent Subject', 'Some parent body', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}, ) parent_msg.attach(content=child_msg.message(), mimetype='message/rfc822') parent_s = parent_msg.message().as_string() # The child message header is not base64 encoded self.assertIn('Child Subject', parent_s) # Feature test: try attaching Django's EmailMessage object directly to the mail. parent_msg = EmailMessage( 'Parent Subject', 'Some parent body', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}, ) parent_msg.attach(content=child_msg, mimetype='message/rfc822') parent_s = parent_msg.message().as_string() # The child message header is not base64 encoded self.assertIn('Child Subject', parent_s) def test_custom_utf8_encoding(self): """A UTF-8 charset with a custom body encoding is respected.""" body = 'Body with latin characters: àáä.' msg = EmailMessage('Subject', body, '[email protected]', ['[email protected]']) encoding = charset.Charset('utf-8') encoding.body_encoding = charset.QP msg.encoding = encoding message = msg.message() self.assertMessageHasHeaders(message, { ('MIME-Version', '1.0'), ('Content-Type', 'text/plain; charset="utf-8"'), ('Content-Transfer-Encoding', 'quoted-printable'), }) self.assertEqual(message.get_payload(), encoding.body_encode(body)) def test_sanitize_address(self): """Email addresses are properly sanitized.""" for email_address, encoding, expected_result in ( # ASCII addresses. ('[email protected]', 'ascii', '[email protected]'), ('[email protected]', 'utf-8', '[email protected]'), (('A name', '[email protected]'), 'ascii', 'A name <[email protected]>'), ( ('A name', '[email protected]'), 'utf-8', '=?utf-8?q?A_name?= <[email protected]>', ), ('localpartonly', 'ascii', 'localpartonly'), # ASCII addresses with display names. ('A name <[email protected]>', 'ascii', 'A name <[email protected]>'), ('A name <[email protected]>', 'utf-8', '=?utf-8?q?A_name?= <[email protected]>'), ('"A name" <[email protected]>', 'ascii', 'A name <[email protected]>'), ('"A name" <[email protected]>', 'utf-8', '=?utf-8?q?A_name?= <[email protected]>'), # Unicode addresses (supported per RFC-6532). ('tó@example.com', 'utf-8', '[email protected]'), ('to@éxample.com', 'utf-8', '[email protected]'), ( ('Tó Example', 'tó@example.com'), 'utf-8', '=?utf-8?q?T=C3=B3_Example?= <[email protected]>', ), # Unicode addresses with display names. ( 'Tó Example <tó@example.com>', 'utf-8', '=?utf-8?q?T=C3=B3_Example?= <[email protected]>', ), ('To Example <to@éxample.com>', 'ascii', 'To Example <[email protected]>'), ( 'To Example <to@éxample.com>', 'utf-8', '=?utf-8?q?To_Example?= <[email protected]>', ), # Addresses with two @ signs. ('"[email protected]"@example.com', 'utf-8', r'"[email protected]"@example.com'), ( '"[email protected]" <[email protected]>', 'utf-8', '=?utf-8?q?to=40other=2Ecom?= <[email protected]>', ), ( ('To Example', '[email protected]@example.com'), 'utf-8', '=?utf-8?q?To_Example?= <"[email protected]"@example.com>', ), ): with self.subTest(email_address=email_address, encoding=encoding): self.assertEqual(sanitize_address(email_address, encoding), expected_result) def test_sanitize_address_invalid(self): for email_address in ( # Invalid address with two @ signs. '[email protected]@example.com', # Invalid address without the quotes. '[email protected] <[email protected]>', # Other invalid addresses. '@', 'to@', '@example.com', ): with self.subTest(email_address=email_address): with self.assertRaises(ValueError): sanitize_address(email_address, encoding='utf-8') @requires_tz_support class MailTimeZoneTests(SimpleTestCase): @override_settings(EMAIL_USE_LOCALTIME=False, USE_TZ=True, TIME_ZONE='Africa/Algiers') def test_date_header_utc(self): """ EMAIL_USE_LOCALTIME=False creates a datetime in UTC. """ email = EmailMessage('Subject', 'Body', '[email protected]', ['[email protected]']) self.assertTrue(email.message()['Date'].endswith('-0000')) @override_settings(EMAIL_USE_LOCALTIME=True, USE_TZ=True, TIME_ZONE='Africa/Algiers') def test_date_header_localtime(self): """ EMAIL_USE_LOCALTIME=True creates a datetime in the local time zone. """ email = EmailMessage('Subject', 'Body', '[email protected]', ['[email protected]']) self.assertTrue(email.message()['Date'].endswith('+0100')) # Africa/Algiers is UTC+1 class PythonGlobalState(SimpleTestCase): """ Tests for #12422 -- Django smarts (#2472/#11212) with charset of utf-8 text parts shouldn't pollute global email Python package charset registry when django.mail.message is imported. """ def test_utf8(self): txt = MIMEText('UTF-8 encoded body', 'plain', 'utf-8') self.assertIn('Content-Transfer-Encoding: base64', txt.as_string()) def test_7bit(self): txt = MIMEText('Body with only ASCII characters.', 'plain', 'utf-8') self.assertIn('Content-Transfer-Encoding: base64', txt.as_string()) def test_8bit_latin(self): txt = MIMEText('Body with latin characters: àáä.', 'plain', 'utf-8') self.assertIn('Content-Transfer-Encoding: base64', txt.as_string()) def test_8bit_non_latin(self): txt = MIMEText('Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'plain', 'utf-8') self.assertIn('Content-Transfer-Encoding: base64', txt.as_string()) class BaseEmailBackendTests(HeadersCheckMixin): email_backend = None def setUp(self): self.settings_override = override_settings(EMAIL_BACKEND=self.email_backend) self.settings_override.enable() def tearDown(self): self.settings_override.disable() def assertStartsWith(self, first, second): if not first.startswith(second): self.longMessage = True self.assertEqual(first[:len(second)], second, "First string doesn't start with the second.") def get_mailbox_content(self): raise NotImplementedError('subclasses of BaseEmailBackendTests must provide a get_mailbox_content() method') def flush_mailbox(self): raise NotImplementedError('subclasses of BaseEmailBackendTests may require a flush_mailbox() method') def get_the_message(self): mailbox = self.get_mailbox_content() self.assertEqual( len(mailbox), 1, "Expected exactly one message, got %d.\n%r" % (len(mailbox), [m.as_string() for m in mailbox]) ) return mailbox[0] def test_send(self): email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]']) num_sent = mail.get_connection().send_messages([email]) self.assertEqual(num_sent, 1) message = self.get_the_message() self.assertEqual(message["subject"], "Subject") self.assertEqual(message.get_payload(), "Content") self.assertEqual(message["from"], "[email protected]") self.assertEqual(message.get_all("to"), ["[email protected]"]) def test_send_unicode(self): email = EmailMessage('Chère maman', 'Je t\'aime très fort', '[email protected]', ['[email protected]']) num_sent = mail.get_connection().send_messages([email]) self.assertEqual(num_sent, 1) message = self.get_the_message() self.assertEqual(message["subject"], '=?utf-8?q?Ch=C3=A8re_maman?=') self.assertEqual(message.get_payload(decode=True).decode(), 'Je t\'aime très fort') def test_send_long_lines(self): """ Email line length is limited to 998 chars by the RFC: https://tools.ietf.org/html/rfc5322#section-2.1.1 Message body containing longer lines are converted to Quoted-Printable to avoid having to insert newlines, which could be hairy to do properly. """ # Unencoded body length is < 998 (840) but > 998 when utf-8 encoded. email = EmailMessage('Subject', 'В южных морях ' * 60, '[email protected]', ['[email protected]']) email.send() message = self.get_the_message() self.assertMessageHasHeaders(message, { ('MIME-Version', '1.0'), ('Content-Type', 'text/plain; charset="utf-8"'), ('Content-Transfer-Encoding', 'quoted-printable'), }) def test_send_many(self): email1 = EmailMessage('Subject', 'Content1', '[email protected]', ['[email protected]']) email2 = EmailMessage('Subject', 'Content2', '[email protected]', ['[email protected]']) # send_messages() may take a list or an iterator. emails_lists = ([email1, email2], iter((email1, email2))) for emails_list in emails_lists: num_sent = mail.get_connection().send_messages(emails_list) self.assertEqual(num_sent, 2) messages = self.get_mailbox_content() self.assertEqual(len(messages), 2) self.assertEqual(messages[0].get_payload(), 'Content1') self.assertEqual(messages[1].get_payload(), 'Content2') self.flush_mailbox() def test_send_verbose_name(self): email = EmailMessage("Subject", "Content", '"Firstname Sürname" <[email protected]>', ["[email protected]"]) email.send() message = self.get_the_message() self.assertEqual(message["subject"], "Subject") self.assertEqual(message.get_payload(), "Content") self.assertEqual(message["from"], "=?utf-8?q?Firstname_S=C3=BCrname?= <[email protected]>") def test_plaintext_send_mail(self): """ Test send_mail without the html_message regression test for adding html_message parameter to send_mail() """ send_mail('Subject', 'Content', '[email protected]', ['[email protected]']) message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get_all('to'), ['[email protected]']) self.assertFalse(message.is_multipart()) self.assertEqual(message.get_payload(), 'Content') self.assertEqual(message.get_content_type(), 'text/plain') def test_html_send_mail(self): """Test html_message argument to send_mail""" send_mail('Subject', 'Content', '[email protected]', ['[email protected]'], html_message='HTML Content') message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get_all('to'), ['[email protected]']) self.assertTrue(message.is_multipart()) self.assertEqual(len(message.get_payload()), 2) self.assertEqual(message.get_payload(0).get_payload(), 'Content') self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain') self.assertEqual(message.get_payload(1).get_payload(), 'HTML Content') self.assertEqual(message.get_payload(1).get_content_type(), 'text/html') @override_settings(MANAGERS=[('nobody', '[email protected]')]) def test_html_mail_managers(self): """Test html_message argument to mail_managers""" mail_managers('Subject', 'Content', html_message='HTML Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') self.assertEqual(message.get_all('to'), ['[email protected]']) self.assertTrue(message.is_multipart()) self.assertEqual(len(message.get_payload()), 2) self.assertEqual(message.get_payload(0).get_payload(), 'Content') self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain') self.assertEqual(message.get_payload(1).get_payload(), 'HTML Content') self.assertEqual(message.get_payload(1).get_content_type(), 'text/html') @override_settings(ADMINS=[('nobody', '[email protected]')]) def test_html_mail_admins(self): """Test html_message argument to mail_admins """ mail_admins('Subject', 'Content', html_message='HTML Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') self.assertEqual(message.get_all('to'), ['[email protected]']) self.assertTrue(message.is_multipart()) self.assertEqual(len(message.get_payload()), 2) self.assertEqual(message.get_payload(0).get_payload(), 'Content') self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain') self.assertEqual(message.get_payload(1).get_payload(), 'HTML Content') self.assertEqual(message.get_payload(1).get_content_type(), 'text/html') @override_settings( ADMINS=[('nobody', '[email protected]')], MANAGERS=[('nobody', '[email protected]')]) def test_manager_and_admin_mail_prefix(self): """ String prefix + lazy translated subject = bad output Regression for #13494 """ mail_managers(gettext_lazy('Subject'), 'Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') self.flush_mailbox() mail_admins(gettext_lazy('Subject'), 'Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') @override_settings(ADMINS=[], MANAGERS=[]) def test_empty_admins(self): """ mail_admins/mail_managers doesn't connect to the mail server if there are no recipients (#9383) """ mail_admins('hi', 'there') self.assertEqual(self.get_mailbox_content(), []) mail_managers('hi', 'there') self.assertEqual(self.get_mailbox_content(), []) def test_wrong_admins_managers(self): tests = ( '[email protected]', ('[email protected]',), ['[email protected]', '[email protected]'], ('[email protected]', '[email protected]'), ) for setting, mail_func in ( ('ADMINS', mail_admins), ('MANAGERS', mail_managers), ): msg = 'The %s setting must be a list of 2-tuples.' % setting for value in tests: with self.subTest(setting=setting, value=value), self.settings(**{setting: value}): with self.assertRaisesMessage(ValueError, msg): mail_func('subject', 'content') def test_message_cc_header(self): """ Regression test for #7722 """ email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], cc=['[email protected]']) mail.get_connection().send_messages([email]) message = self.get_the_message() self.assertMessageHasHeaders(message, { ('MIME-Version', '1.0'), ('Content-Type', 'text/plain; charset="utf-8"'), ('Content-Transfer-Encoding', '7bit'), ('Subject', 'Subject'), ('From', '[email protected]'), ('To', '[email protected]'), ('Cc', '[email protected]')}) self.assertIn('\nDate: ', message.as_string()) def test_idn_send(self): """ Regression test for #14301 """ self.assertTrue(send_mail('Subject', 'Content', 'from@öäü.com', ['to@öäü.com'])) message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), '[email protected]') self.assertEqual(message.get('to'), '[email protected]') self.flush_mailbox() m = EmailMessage('Subject', 'Content', 'from@öäü.com', ['to@öäü.com'], cc=['cc@öäü.com']) m.send() message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), '[email protected]') self.assertEqual(message.get('to'), '[email protected]') self.assertEqual(message.get('cc'), '[email protected]') def test_recipient_without_domain(self): """ Regression test for #15042 """ self.assertTrue(send_mail("Subject", "Content", "tester", ["django"])) message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), "tester") self.assertEqual(message.get('to'), "django") def test_lazy_addresses(self): """ Email sending should support lazy email addresses (#24416). """ _ = gettext_lazy self.assertTrue(send_mail('Subject', 'Content', _('tester'), [_('django')])) message = self.get_the_message() self.assertEqual(message.get('from'), 'tester') self.assertEqual(message.get('to'), 'django') self.flush_mailbox() m = EmailMessage( 'Subject', 'Content', _('tester'), [_('to1'), _('to2')], cc=[_('cc1'), _('cc2')], bcc=[_('bcc')], reply_to=[_('reply')], ) self.assertEqual(m.recipients(), ['to1', 'to2', 'cc1', 'cc2', 'bcc']) m.send() message = self.get_the_message() self.assertEqual(message.get('from'), 'tester') self.assertEqual(message.get('to'), 'to1, to2') self.assertEqual(message.get('cc'), 'cc1, cc2') self.assertEqual(message.get('Reply-To'), 'reply') def test_close_connection(self): """ Connection can be closed (even when not explicitly opened) """ conn = mail.get_connection(username='', password='') conn.close() def test_use_as_contextmanager(self): """ The connection can be used as a contextmanager. """ opened = [False] closed = [False] conn = mail.get_connection(username='', password='') def open(): opened[0] = True conn.open = open def close(): closed[0] = True conn.close = close with conn as same_conn: self.assertTrue(opened[0]) self.assertIs(same_conn, conn) self.assertFalse(closed[0]) self.assertTrue(closed[0]) class LocmemBackendTests(BaseEmailBackendTests, SimpleTestCase): email_backend = 'django.core.mail.backends.locmem.EmailBackend' def get_mailbox_content(self): return [m.message() for m in mail.outbox] def flush_mailbox(self): mail.outbox = [] def tearDown(self): super().tearDown() mail.outbox = [] def test_locmem_shared_messages(self): """ Make sure that the locmen backend populates the outbox. """ connection = locmem.EmailBackend() connection2 = locmem.EmailBackend() email = EmailMessage( 'Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}, ) connection.send_messages([email]) connection2.send_messages([email]) self.assertEqual(len(mail.outbox), 2) def test_validate_multiline_headers(self): # Ticket #18861 - Validate emails when using the locmem backend with self.assertRaises(BadHeaderError): send_mail('Subject\nMultiline', 'Content', '[email protected]', ['[email protected]']) class FileBackendTests(BaseEmailBackendTests, SimpleTestCase): email_backend = 'django.core.mail.backends.filebased.EmailBackend' def setUp(self): super().setUp() self.tmp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.tmp_dir) self._settings_override = override_settings(EMAIL_FILE_PATH=self.tmp_dir) self._settings_override.enable() def tearDown(self): self._settings_override.disable() super().tearDown() def flush_mailbox(self): for filename in os.listdir(self.tmp_dir): os.unlink(os.path.join(self.tmp_dir, filename)) def get_mailbox_content(self): messages = [] for filename in os.listdir(self.tmp_dir): with open(os.path.join(self.tmp_dir, filename), 'rb') as fp: session = fp.read().split(b'\n' + (b'-' * 79) + b'\n') messages.extend(message_from_bytes(m) for m in session if m) return messages def test_file_sessions(self): """Make sure opening a connection creates a new file""" msg = EmailMessage( 'Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}, ) connection = mail.get_connection() connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 1) with open(os.path.join(self.tmp_dir, os.listdir(self.tmp_dir)[0]), 'rb') as fp: message = message_from_binary_file(fp) self.assertEqual(message.get_content_type(), 'text/plain') self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), '[email protected]') self.assertEqual(message.get('to'), '[email protected]') connection2 = mail.get_connection() connection2.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 2) connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 2) msg.connection = mail.get_connection() self.assertTrue(connection.open()) msg.send() self.assertEqual(len(os.listdir(self.tmp_dir)), 3) msg.send() self.assertEqual(len(os.listdir(self.tmp_dir)), 3) connection.close() class ConsoleBackendTests(BaseEmailBackendTests, SimpleTestCase): email_backend = 'django.core.mail.backends.console.EmailBackend' def setUp(self): super().setUp() self.__stdout = sys.stdout self.stream = sys.stdout = StringIO() def tearDown(self): del self.stream sys.stdout = self.__stdout del self.__stdout super().tearDown() def flush_mailbox(self): self.stream = sys.stdout = StringIO() def get_mailbox_content(self): messages = self.stream.getvalue().split('\n' + ('-' * 79) + '\n') return [message_from_bytes(m.encode()) for m in messages if m] def test_console_stream_kwarg(self): """ The console backend can be pointed at an arbitrary stream. """ s = StringIO() connection = mail.get_connection('django.core.mail.backends.console.EmailBackend', stream=s) send_mail('Subject', 'Content', '[email protected]', ['[email protected]'], connection=connection) message = s.getvalue().split('\n' + ('-' * 79) + '\n')[0].encode() self.assertMessageHasHeaders(message, { ('MIME-Version', '1.0'), ('Content-Type', 'text/plain; charset="utf-8"'), ('Content-Transfer-Encoding', '7bit'), ('Subject', 'Subject'), ('From', '[email protected]'), ('To', '[email protected]')}) self.assertIn(b'\nDate: ', message) class FakeSMTPChannel(smtpd.SMTPChannel): def collect_incoming_data(self, data): try: smtpd.SMTPChannel.collect_incoming_data(self, data) except UnicodeDecodeError: # Ignore decode error in SSL/TLS connection tests as the test only # cares whether the connection attempt was made. pass def smtp_AUTH(self, arg): if arg == 'CRAM-MD5': # This is only the first part of the login process. But it's enough # for our tests. challenge = base64.b64encode(b'somerandomstring13579') self.push('334 %s' % challenge.decode()) else: self.push('502 Error: login "%s" not implemented' % arg) class FakeSMTPServer(smtpd.SMTPServer, threading.Thread): """ Asyncore SMTP server wrapped into a thread. Based on DummyFTPServer from: http://svn.python.org/view/python/branches/py3k/Lib/test/test_ftplib.py?revision=86061&view=markup """ channel_class = FakeSMTPChannel def __init__(self, *args, **kwargs): threading.Thread.__init__(self) smtpd.SMTPServer.__init__(self, *args, decode_data=True, **kwargs) self._sink = [] self.active = False self.active_lock = threading.Lock() self.sink_lock = threading.Lock() def process_message(self, peer, mailfrom, rcpttos, data): data = data.encode() m = message_from_bytes(data) maddr = parseaddr(m.get('from'))[1] if mailfrom != maddr: # According to the spec, mailfrom does not necessarily match the # From header - this is the case where the local part isn't # encoded, so try to correct that. lp, domain = mailfrom.split('@', 1) lp = Header(lp, 'utf-8').encode() mailfrom = '@'.join([lp, domain]) if mailfrom != maddr: return "553 '%s' != '%s'" % (mailfrom, maddr) with self.sink_lock: self._sink.append(m) def get_sink(self): with self.sink_lock: return self._sink[:] def flush_sink(self): with self.sink_lock: self._sink[:] = [] def start(self): assert not self.active self.__flag = threading.Event() threading.Thread.start(self) self.__flag.wait() def run(self): self.active = True self.__flag.set() while self.active and asyncore.socket_map: with self.active_lock: asyncore.loop(timeout=0.1, count=1) asyncore.close_all() def stop(self): if self.active: self.active = False self.join() class FakeAUTHSMTPConnection(SMTP): """ A SMTP connection pretending support for the AUTH command. It does not, but at least this can allow testing the first part of the AUTH process. """ def ehlo(self, name=''): response = SMTP.ehlo(self, name=name) self.esmtp_features.update({ 'auth': 'CRAM-MD5 PLAIN LOGIN', }) return response class SMTPBackendTestsBase(SimpleTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.server = FakeSMTPServer(('127.0.0.1', 0), None) cls._settings_override = override_settings( EMAIL_HOST="127.0.0.1", EMAIL_PORT=cls.server.socket.getsockname()[1]) cls._settings_override.enable() cls.server.start() @classmethod def tearDownClass(cls): cls._settings_override.disable() cls.server.stop() super().tearDownClass() class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase): email_backend = 'django.core.mail.backends.smtp.EmailBackend' def setUp(self): super().setUp() self.server.flush_sink() def tearDown(self): self.server.flush_sink() super().tearDown() def flush_mailbox(self): self.server.flush_sink() def get_mailbox_content(self): return self.server.get_sink() @override_settings( EMAIL_HOST_USER="not empty username", EMAIL_HOST_PASSWORD='not empty password', ) def test_email_authentication_use_settings(self): backend = smtp.EmailBackend() self.assertEqual(backend.username, 'not empty username') self.assertEqual(backend.password, 'not empty password') @override_settings( EMAIL_HOST_USER="not empty username", EMAIL_HOST_PASSWORD='not empty password', ) def test_email_authentication_override_settings(self): backend = smtp.EmailBackend(username='username', password='password') self.assertEqual(backend.username, 'username') self.assertEqual(backend.password, 'password') @override_settings( EMAIL_HOST_USER="not empty username", EMAIL_HOST_PASSWORD='not empty password', ) def test_email_disabled_authentication(self): backend = smtp.EmailBackend(username='', password='') self.assertEqual(backend.username, '') self.assertEqual(backend.password, '') def test_auth_attempted(self): """ Opening the backend with non empty username/password tries to authenticate against the SMTP server. """ backend = smtp.EmailBackend( username='not empty username', password='not empty password') with self.assertRaisesMessage(SMTPException, 'SMTP AUTH extension not supported by server.'): with backend: pass def test_server_open(self): """ open() returns whether it opened a connection. """ backend = smtp.EmailBackend(username='', password='') self.assertIsNone(backend.connection) opened = backend.open() backend.close() self.assertIs(opened, True) def test_reopen_connection(self): backend = smtp.EmailBackend() # Simulate an already open connection. backend.connection = True self.assertIs(backend.open(), False) def test_server_login(self): """ Even if the Python SMTP server doesn't support authentication, the login process starts and the appropriate exception is raised. """ class CustomEmailBackend(smtp.EmailBackend): connection_class = FakeAUTHSMTPConnection backend = CustomEmailBackend(username='username', password='password') with self.assertRaises(SMTPAuthenticationError): with backend: pass @override_settings(EMAIL_USE_TLS=True) def test_email_tls_use_settings(self): backend = smtp.EmailBackend() self.assertTrue(backend.use_tls) @override_settings(EMAIL_USE_TLS=True) def test_email_tls_override_settings(self): backend = smtp.EmailBackend(use_tls=False) self.assertFalse(backend.use_tls) def test_email_tls_default_disabled(self): backend = smtp.EmailBackend() self.assertFalse(backend.use_tls) def test_ssl_tls_mutually_exclusive(self): msg = ( 'EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set ' 'one of those settings to True.' ) with self.assertRaisesMessage(ValueError, msg): smtp.EmailBackend(use_ssl=True, use_tls=True) @override_settings(EMAIL_USE_SSL=True) def test_email_ssl_use_settings(self): backend = smtp.EmailBackend() self.assertTrue(backend.use_ssl) @override_settings(EMAIL_USE_SSL=True) def test_email_ssl_override_settings(self): backend = smtp.EmailBackend(use_ssl=False) self.assertFalse(backend.use_ssl) def test_email_ssl_default_disabled(self): backend = smtp.EmailBackend() self.assertFalse(backend.use_ssl) @override_settings(EMAIL_SSL_CERTFILE='foo') def test_email_ssl_certfile_use_settings(self): backend = smtp.EmailBackend() self.assertEqual(backend.ssl_certfile, 'foo') @override_settings(EMAIL_SSL_CERTFILE='foo') def test_email_ssl_certfile_override_settings(self): backend = smtp.EmailBackend(ssl_certfile='bar') self.assertEqual(backend.ssl_certfile, 'bar') def test_email_ssl_certfile_default_disabled(self): backend = smtp.EmailBackend() self.assertIsNone(backend.ssl_certfile) @override_settings(EMAIL_SSL_KEYFILE='foo') def test_email_ssl_keyfile_use_settings(self): backend = smtp.EmailBackend() self.assertEqual(backend.ssl_keyfile, 'foo') @override_settings(EMAIL_SSL_KEYFILE='foo') def test_email_ssl_keyfile_override_settings(self): backend = smtp.EmailBackend(ssl_keyfile='bar') self.assertEqual(backend.ssl_keyfile, 'bar') def test_email_ssl_keyfile_default_disabled(self): backend = smtp.EmailBackend() self.assertIsNone(backend.ssl_keyfile) @override_settings(EMAIL_USE_TLS=True) def test_email_tls_attempts_starttls(self): backend = smtp.EmailBackend() self.assertTrue(backend.use_tls) with self.assertRaisesMessage(SMTPException, 'STARTTLS extension not supported by server.'): with backend: pass @override_settings(EMAIL_USE_SSL=True) def test_email_ssl_attempts_ssl_connection(self): backend = smtp.EmailBackend() self.assertTrue(backend.use_ssl) with self.assertRaises(SSLError): with backend: pass def test_connection_timeout_default(self): """The connection's timeout value is None by default.""" connection = mail.get_connection('django.core.mail.backends.smtp.EmailBackend') self.assertIsNone(connection.timeout) def test_connection_timeout_custom(self): """The timeout parameter can be customized.""" class MyEmailBackend(smtp.EmailBackend): def __init__(self, *args, **kwargs): kwargs.setdefault('timeout', 42) super().__init__(*args, **kwargs) myemailbackend = MyEmailBackend() myemailbackend.open() self.assertEqual(myemailbackend.timeout, 42) self.assertEqual(myemailbackend.connection.timeout, 42) myemailbackend.close() @override_settings(EMAIL_TIMEOUT=10) def test_email_timeout_override_settings(self): backend = smtp.EmailBackend() self.assertEqual(backend.timeout, 10) def test_email_msg_uses_crlf(self): """#23063 -- RFC-compliant messages are sent over SMTP.""" send = SMTP.send try: smtp_messages = [] def mock_send(self, s): smtp_messages.append(s) return send(self, s) SMTP.send = mock_send email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]']) mail.get_connection().send_messages([email]) # Find the actual message msg = None for i, m in enumerate(smtp_messages): if m[:4] == 'data': msg = smtp_messages[i + 1] break self.assertTrue(msg) msg = msg.decode() # The message only contains CRLF and not combinations of CRLF, LF, and CR. msg = msg.replace('\r\n', '') self.assertNotIn('\r', msg) self.assertNotIn('\n', msg) finally: SMTP.send = send def test_send_messages_after_open_failed(self): """ send_messages() shouldn't try to send messages if open() raises an exception after initializing the connection. """ backend = smtp.EmailBackend() # Simulate connection initialization success and a subsequent # connection exception. backend.connection = True backend.open = lambda: None email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]']) self.assertEqual(backend.send_messages([email]), 0) def test_send_messages_empty_list(self): backend = smtp.EmailBackend() backend.connection = True self.assertEqual(backend.send_messages([]), 0) def test_send_messages_zero_sent(self): """A message isn't sent if it doesn't have any recipients.""" backend = smtp.EmailBackend() backend.connection = True email = EmailMessage('Subject', 'Content', '[email protected]', to=[]) sent = backend.send_messages([email]) self.assertEqual(sent, 0) class SMTPBackendStoppedServerTests(SMTPBackendTestsBase): """ These tests require a separate class, because the FakeSMTPServer is shut down in setUpClass(), and it cannot be restarted ("RuntimeError: threads can only be started once"). """ @classmethod def setUpClass(cls): super().setUpClass() cls.backend = smtp.EmailBackend(username='', password='') cls.server.stop() def test_server_stopped(self): """ Closing the backend while the SMTP server is stopped doesn't raise an exception. """ self.backend.close() def test_fail_silently_on_connection_error(self): """ A socket connection error is silenced with fail_silently=True. """ with self.assertRaises(ConnectionError): self.backend.open() self.backend.fail_silently = True self.backend.open()
e4fc0b657330baef087761b8c28a53fbc2afbc49c806c26a07d6424e81713b3b
import unittest from django.core import validators from django.core.exceptions import ValidationError from django.db import IntegrityError, connection, models from django.test import SimpleTestCase, TestCase from .models import ( BigIntegerModel, IntegerModel, PositiveIntegerModel, PositiveSmallIntegerModel, SmallIntegerModel, ) class IntegerFieldTests(TestCase): model = IntegerModel documented_range = (-2147483648, 2147483647) @property def backend_range(self): field = self.model._meta.get_field('value') internal_type = field.get_internal_type() return connection.ops.integer_field_range(internal_type) def test_documented_range(self): """ Values within the documented safe range pass validation, and can be saved and retrieved without corruption. """ min_value, max_value = self.documented_range instance = self.model(value=min_value) instance.full_clean() instance.save() qs = self.model.objects.filter(value__lte=min_value) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, min_value) instance = self.model(value=max_value) instance.full_clean() instance.save() qs = self.model.objects.filter(value__gte=max_value) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, max_value) def test_backend_range_save(self): """ Backend specific ranges can be saved without corruption. """ min_value, max_value = self.backend_range if min_value is not None: instance = self.model(value=min_value) instance.full_clean() instance.save() qs = self.model.objects.filter(value__lte=min_value) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, min_value) if max_value is not None: instance = self.model(value=max_value) instance.full_clean() instance.save() qs = self.model.objects.filter(value__gte=max_value) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, max_value) def test_backend_range_validation(self): """ Backend specific ranges are enforced at the model validation level (#12030). """ min_value, max_value = self.backend_range if min_value is not None: instance = self.model(value=min_value - 1) expected_message = validators.MinValueValidator.message % { 'limit_value': min_value, } with self.assertRaisesMessage(ValidationError, expected_message): instance.full_clean() instance.value = min_value instance.full_clean() if max_value is not None: instance = self.model(value=max_value + 1) expected_message = validators.MaxValueValidator.message % { 'limit_value': max_value, } with self.assertRaisesMessage(ValidationError, expected_message): instance.full_clean() instance.value = max_value instance.full_clean() def test_redundant_backend_range_validators(self): """ If there are stricter validators than the ones from the database backend then the backend validators aren't added. """ min_backend_value, max_backend_value = self.backend_range for callable_limit in (True, False): with self.subTest(callable_limit=callable_limit): if min_backend_value is not None: min_custom_value = min_backend_value + 1 limit_value = (lambda: min_custom_value) if callable_limit else min_custom_value ranged_value_field = self.model._meta.get_field('value').__class__( validators=[validators.MinValueValidator(limit_value)] ) field_range_message = validators.MinValueValidator.message % { 'limit_value': min_custom_value, } with self.assertRaisesMessage(ValidationError, '[%r]' % field_range_message): ranged_value_field.run_validators(min_backend_value - 1) if max_backend_value is not None: max_custom_value = max_backend_value - 1 limit_value = (lambda: max_custom_value) if callable_limit else max_custom_value ranged_value_field = self.model._meta.get_field('value').__class__( validators=[validators.MaxValueValidator(limit_value)] ) field_range_message = validators.MaxValueValidator.message % { 'limit_value': max_custom_value, } with self.assertRaisesMessage(ValidationError, '[%r]' % field_range_message): ranged_value_field.run_validators(max_backend_value + 1) def test_types(self): instance = self.model(value=1) self.assertIsInstance(instance.value, int) instance.save() self.assertIsInstance(instance.value, int) instance = self.model.objects.get() self.assertIsInstance(instance.value, int) def test_coercing(self): self.model.objects.create(value='10') instance = self.model.objects.get(value='10') self.assertEqual(instance.value, 10) def test_invalid_value(self): tests = [ (TypeError, ()), (TypeError, []), (TypeError, {}), (TypeError, set()), (TypeError, object()), (TypeError, complex()), (ValueError, 'non-numeric string'), (ValueError, b'non-numeric byte-string'), ] for exception, value in tests: with self.subTest(value): msg = "Field 'value' expected a number but got %r." % (value,) with self.assertRaisesMessage(exception, msg): self.model.objects.create(value=value) class SmallIntegerFieldTests(IntegerFieldTests): model = SmallIntegerModel documented_range = (-32768, 32767) class BigIntegerFieldTests(IntegerFieldTests): model = BigIntegerModel documented_range = (-9223372036854775808, 9223372036854775807) class PositiveSmallIntegerFieldTests(IntegerFieldTests): model = PositiveSmallIntegerModel documented_range = (0, 32767) class PositiveIntegerFieldTests(IntegerFieldTests): model = PositiveIntegerModel documented_range = (0, 2147483647) @unittest.skipIf(connection.vendor == 'sqlite', "SQLite doesn't have a constraint.") def test_negative_values(self): p = PositiveIntegerModel.objects.create(value=0) p.value = models.F('value') - 1 with self.assertRaises(IntegrityError): p.save() class ValidationTests(SimpleTestCase): class Choices(models.IntegerChoices): A = 1 def test_integerfield_cleans_valid_string(self): f = models.IntegerField() self.assertEqual(f.clean('2', None), 2) def test_integerfield_raises_error_on_invalid_intput(self): f = models.IntegerField() with self.assertRaises(ValidationError): f.clean('a', None) def test_choices_validation_supports_named_groups(self): f = models.IntegerField(choices=(('group', ((10, 'A'), (20, 'B'))), (30, 'C'))) self.assertEqual(10, f.clean(10, None)) def test_nullable_integerfield_raises_error_with_blank_false(self): f = models.IntegerField(null=True, blank=False) with self.assertRaises(ValidationError): f.clean(None, None) def test_nullable_integerfield_cleans_none_on_null_and_blank_true(self): f = models.IntegerField(null=True, blank=True) self.assertIsNone(f.clean(None, None)) def test_integerfield_raises_error_on_empty_input(self): f = models.IntegerField(null=False) with self.assertRaises(ValidationError): f.clean(None, None) with self.assertRaises(ValidationError): f.clean('', None) def test_integerfield_validates_zero_against_choices(self): f = models.IntegerField(choices=((1, 1),)) with self.assertRaises(ValidationError): f.clean('0', None) def test_enum_choices_cleans_valid_string(self): f = models.IntegerField(choices=self.Choices.choices) self.assertEqual(f.clean('1', None), 1) def test_enum_choices_invalid_input(self): f = models.IntegerField(choices=self.Choices.choices) with self.assertRaises(ValidationError): f.clean('A', None) with self.assertRaises(ValidationError): f.clean('3', None)
312c2b8a66be8049b35a79d6535f08667e8185b62f5b9f3c28f3b7480e3144a9
import datetime import json from django import forms from django.core import exceptions, serializers from django.db import models from django.test import SimpleTestCase, TestCase from .models import DurationModel, NullDurationModel class TestSaveLoad(TestCase): def test_simple_roundtrip(self): duration = datetime.timedelta(microseconds=8999999999999999) DurationModel.objects.create(field=duration) loaded = DurationModel.objects.get() self.assertEqual(loaded.field, duration) def test_create_empty(self): NullDurationModel.objects.create() loaded = NullDurationModel.objects.get() self.assertIsNone(loaded.field) def test_fractional_seconds(self): value = datetime.timedelta(seconds=2.05) d = DurationModel.objects.create(field=value) d.refresh_from_db() self.assertEqual(d.field, value) class TestQuerying(TestCase): @classmethod def setUpTestData(cls): cls.objs = [ DurationModel.objects.create(field=datetime.timedelta(days=1)), DurationModel.objects.create(field=datetime.timedelta(seconds=1)), DurationModel.objects.create(field=datetime.timedelta(seconds=-1)), ] def test_exact(self): self.assertSequenceEqual( DurationModel.objects.filter(field=datetime.timedelta(days=1)), [self.objs[0]] ) def test_gt(self): self.assertSequenceEqual( DurationModel.objects.filter(field__gt=datetime.timedelta(days=0)), [self.objs[0], self.objs[1]] ) class TestSerialization(SimpleTestCase): test_data = '[{"fields": {"field": "1 01:00:00"}, "model": "model_fields.durationmodel", "pk": null}]' def test_dumping(self): instance = DurationModel(field=datetime.timedelta(days=1, hours=1)) data = serializers.serialize('json', [instance]) self.assertEqual(json.loads(data), json.loads(self.test_data)) def test_loading(self): instance = list(serializers.deserialize('json', self.test_data))[0].object self.assertEqual(instance.field, datetime.timedelta(days=1, hours=1)) class TestValidation(SimpleTestCase): def test_invalid_string(self): field = models.DurationField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean('not a datetime', None) self.assertEqual(cm.exception.code, 'invalid') self.assertEqual( cm.exception.message % cm.exception.params, '“not a datetime” value has an invalid format. ' 'It must be in [DD] [[HH:]MM:]ss[.uuuuuu] format.' ) class TestFormField(SimpleTestCase): # Tests for forms.DurationField are in the forms_tests app. def test_formfield(self): field = models.DurationField() self.assertIsInstance(field.formfield(), forms.DurationField)
ab6aacf835064ca6020072ae69d43940ba7cf51e6fd33ceedcf00c6f6f6566dd
from django.db import models from django.test import SimpleTestCase from .models import AutoModel, BigAutoModel, SmallAutoModel from .test_integerfield import ( BigIntegerFieldTests, IntegerFieldTests, SmallIntegerFieldTests, ) class AutoFieldTests(IntegerFieldTests): model = AutoModel class BigAutoFieldTests(BigIntegerFieldTests): model = BigAutoModel class SmallAutoFieldTests(SmallIntegerFieldTests): model = SmallAutoModel class AutoFieldInheritanceTests(SimpleTestCase): def test_isinstance_of_autofield(self): for field in (models.BigAutoField, models.SmallAutoField): with self.subTest(field.__name__): self.assertIsInstance(field(), models.AutoField) def test_issubclass_of_autofield(self): for field in (models.BigAutoField, models.SmallAutoField): with self.subTest(field.__name__): self.assertTrue(issubclass(field, models.AutoField))
d8c73a6da1db734cf1d7424edd3d63cfccf07a332e55e3ed3bed13c0c7d51498
import pickle from django import forms from django.core.exceptions import ValidationError from django.db import models from django.test import SimpleTestCase, TestCase from django.utils.functional import lazy from .models import ( Bar, Choiceful, Foo, RenamedField, VerboseNameField, Whiz, WhizDelayed, WhizIter, WhizIterEmpty, ) class Nested: class Field(models.Field): pass class BasicFieldTests(SimpleTestCase): def test_show_hidden_initial(self): """ Fields with choices respect show_hidden_initial as a kwarg to formfield(). """ choices = [(0, 0), (1, 1)] model_field = models.Field(choices=choices) form_field = model_field.formfield(show_hidden_initial=True) self.assertTrue(form_field.show_hidden_initial) form_field = model_field.formfield(show_hidden_initial=False) self.assertFalse(form_field.show_hidden_initial) def test_field_repr(self): """ __repr__() of a field displays its name. """ f = Foo._meta.get_field('a') self.assertEqual(repr(f), '<django.db.models.fields.CharField: a>') f = models.fields.CharField() self.assertEqual(repr(f), '<django.db.models.fields.CharField>') def test_field_repr_nested(self): """__repr__() uses __qualname__ for nested class support.""" self.assertEqual(repr(Nested.Field()), '<model_fields.tests.Nested.Field>') def test_field_name(self): """ A defined field name (name="fieldname") is used instead of the model model's attribute name (modelname). """ instance = RenamedField() self.assertTrue(hasattr(instance, 'get_fieldname_display')) self.assertFalse(hasattr(instance, 'get_modelname_display')) def test_field_verbose_name(self): m = VerboseNameField for i in range(1, 23): self.assertEqual(m._meta.get_field('field%d' % i).verbose_name, 'verbose field%d' % i) self.assertEqual(m._meta.get_field('id').verbose_name, 'verbose pk') def test_choices_form_class(self): """Can supply a custom choices form class to Field.formfield()""" choices = [('a', 'a')] field = models.CharField(choices=choices) klass = forms.TypedMultipleChoiceField self.assertIsInstance(field.formfield(choices_form_class=klass), klass) def test_formfield_disabled(self): """Field.formfield() sets disabled for fields with choices.""" field = models.CharField(choices=[('a', 'b')]) form_field = field.formfield(disabled=True) self.assertIs(form_field.disabled, True) def test_field_str(self): f = models.Field() self.assertEqual(str(f), '<django.db.models.fields.Field>') f = Foo._meta.get_field('a') self.assertEqual(str(f), 'model_fields.Foo.a') def test_field_ordering(self): """Fields are ordered based on their creation.""" f1 = models.Field() f2 = models.Field(auto_created=True) f3 = models.Field() self.assertLess(f2, f1) self.assertGreater(f3, f1) self.assertIsNotNone(f1) self.assertNotIn(f2, (None, 1, '')) def test_field_instance_is_picklable(self): """Field instances can be pickled.""" field = models.Field(max_length=100, default='a string') # Must be picklable with this cached property populated (#28188). field._get_default pickle.dumps(field) def test_deconstruct_nested_field(self): """deconstruct() uses __qualname__ for nested class support.""" name, path, args, kwargs = Nested.Field().deconstruct() self.assertEqual(path, 'model_fields.tests.Nested.Field') class ChoicesTests(SimpleTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.no_choices = Choiceful._meta.get_field('no_choices') cls.empty_choices = Choiceful._meta.get_field('empty_choices') cls.empty_choices_bool = Choiceful._meta.get_field('empty_choices_bool') cls.empty_choices_text = Choiceful._meta.get_field('empty_choices_text') cls.with_choices = Choiceful._meta.get_field('with_choices') def test_choices(self): self.assertIsNone(self.no_choices.choices) self.assertEqual(self.empty_choices.choices, ()) self.assertEqual(self.with_choices.choices, [(1, 'A')]) def test_flatchoices(self): self.assertEqual(self.no_choices.flatchoices, []) self.assertEqual(self.empty_choices.flatchoices, []) self.assertEqual(self.with_choices.flatchoices, [(1, 'A')]) def test_check(self): self.assertEqual(Choiceful.check(), []) def test_invalid_choice(self): model_instance = None # Actual model instance not needed. self.no_choices.validate(0, model_instance) msg = "['Value 99 is not a valid choice.']" with self.assertRaisesMessage(ValidationError, msg): self.empty_choices.validate(99, model_instance) with self.assertRaisesMessage(ValidationError, msg): self.with_choices.validate(99, model_instance) def test_formfield(self): no_choices_formfield = self.no_choices.formfield() self.assertIsInstance(no_choices_formfield, forms.IntegerField) fields = ( self.empty_choices, self.with_choices, self.empty_choices_bool, self.empty_choices_text, ) for field in fields: with self.subTest(field=field): self.assertIsInstance(field.formfield(), forms.ChoiceField) class GetFieldDisplayTests(SimpleTestCase): def test_choices_and_field_display(self): """ get_choices() interacts with get_FIELD_display() to return the expected values. """ self.assertEqual(Whiz(c=1).get_c_display(), 'First') # A nested value self.assertEqual(Whiz(c=0).get_c_display(), 'Other') # A top level value self.assertEqual(Whiz(c=9).get_c_display(), 9) # Invalid value self.assertIsNone(Whiz(c=None).get_c_display()) # Blank value self.assertEqual(Whiz(c='').get_c_display(), '') # Empty value self.assertEqual(WhizDelayed(c=0).get_c_display(), 'Other') # Delayed choices def test_get_FIELD_display_translated(self): """A translated display value is coerced to str.""" val = Whiz(c=5).get_c_display() self.assertIsInstance(val, str) self.assertEqual(val, 'translated') def test_iterator_choices(self): """ get_choices() works with Iterators. """ self.assertEqual(WhizIter(c=1).c, 1) # A nested value self.assertEqual(WhizIter(c=9).c, 9) # Invalid value self.assertIsNone(WhizIter(c=None).c) # Blank value self.assertEqual(WhizIter(c='').c, '') # Empty value def test_empty_iterator_choices(self): """ get_choices() works with empty iterators. """ self.assertEqual(WhizIterEmpty(c="a").c, "a") # A nested value self.assertEqual(WhizIterEmpty(c="b").c, "b") # Invalid value self.assertIsNone(WhizIterEmpty(c=None).c) # Blank value self.assertEqual(WhizIterEmpty(c='').c, '') # Empty value class GetChoicesTests(SimpleTestCase): def test_empty_choices(self): choices = [] f = models.CharField(choices=choices) self.assertEqual(f.get_choices(include_blank=False), choices) def test_blank_in_choices(self): choices = [('', '<><>'), ('a', 'A')] f = models.CharField(choices=choices) self.assertEqual(f.get_choices(include_blank=True), choices) def test_blank_in_grouped_choices(self): choices = [ ('f', 'Foo'), ('b', 'Bar'), ('Group', ( ('', 'No Preference'), ('fg', 'Foo'), ('bg', 'Bar'), )), ] f = models.CharField(choices=choices) self.assertEqual(f.get_choices(include_blank=True), choices) def test_lazy_strings_not_evaluated(self): lazy_func = lazy(lambda x: 0 / 0, int) # raises ZeroDivisionError if evaluated. f = models.CharField(choices=[(lazy_func('group'), (('a', 'A'), ('b', 'B')))]) self.assertEqual(f.get_choices(include_blank=True)[0], ('', '---------')) class GetChoicesOrderingTests(TestCase): @classmethod def setUpTestData(cls): cls.foo1 = Foo.objects.create(a='a', d='12.35') cls.foo2 = Foo.objects.create(a='b', d='12.34') cls.bar1 = Bar.objects.create(a=cls.foo1, b='b') cls.bar2 = Bar.objects.create(a=cls.foo2, b='a') cls.field = Bar._meta.get_field('a') def assertChoicesEqual(self, choices, objs): self.assertEqual(choices, [(obj.pk, str(obj)) for obj in objs]) def test_get_choices(self): self.assertChoicesEqual( self.field.get_choices(include_blank=False, ordering=('a',)), [self.foo1, self.foo2] ) self.assertChoicesEqual( self.field.get_choices(include_blank=False, ordering=('-a',)), [self.foo2, self.foo1] ) def test_get_choices_default_ordering(self): self.addCleanup(setattr, Foo._meta, 'ordering', Foo._meta.ordering) Foo._meta.ordering = ('d',) self.assertChoicesEqual( self.field.get_choices(include_blank=False), [self.foo2, self.foo1] ) def test_get_choices_reverse_related_field(self): self.assertChoicesEqual( self.field.remote_field.get_choices(include_blank=False, ordering=('a',)), [self.bar1, self.bar2] ) self.assertChoicesEqual( self.field.remote_field.get_choices(include_blank=False, ordering=('-a',)), [self.bar2, self.bar1] ) def test_get_choices_reverse_related_field_default_ordering(self): self.addCleanup(setattr, Bar._meta, 'ordering', Bar._meta.ordering) Bar._meta.ordering = ('b',) self.assertChoicesEqual( self.field.remote_field.get_choices(include_blank=False), [self.bar2, self.bar1] )
e126d28e37f521899424c5c60367556fa3b744344b5483fec29e24a426f677fa
import os import tempfile import uuid from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation, ) from django.contrib.contenttypes.models import ContentType from django.core.files.storage import FileSystemStorage from django.db import models from django.db.models.fields.files import ImageField, ImageFieldFile from django.db.models.fields.related import ( ForeignKey, ForeignObject, ManyToManyField, OneToOneField, ) from django.utils.translation import gettext_lazy as _ try: from PIL import Image except ImportError: Image = None class Foo(models.Model): a = models.CharField(max_length=10) d = models.DecimalField(max_digits=5, decimal_places=3) def get_foo(): return Foo.objects.get(id=1).pk class Bar(models.Model): b = models.CharField(max_length=10) a = models.ForeignKey(Foo, models.CASCADE, default=get_foo, related_name='bars') class Whiz(models.Model): CHOICES = ( ('Group 1', ( (1, 'First'), (2, 'Second'), ) ), ('Group 2', ( (3, 'Third'), (4, 'Fourth'), ) ), (0, 'Other'), (5, _('translated')), ) c = models.IntegerField(choices=CHOICES, null=True) class WhizDelayed(models.Model): c = models.IntegerField(choices=(), null=True) # Contrived way of adding choices later. WhizDelayed._meta.get_field('c').choices = Whiz.CHOICES class WhizIter(models.Model): c = models.IntegerField(choices=iter(Whiz.CHOICES), null=True) class WhizIterEmpty(models.Model): c = models.CharField(choices=iter(()), blank=True, max_length=1) class Choiceful(models.Model): no_choices = models.IntegerField(null=True) empty_choices = models.IntegerField(choices=(), null=True) with_choices = models.IntegerField(choices=[(1, 'A')], null=True) empty_choices_bool = models.BooleanField(choices=()) empty_choices_text = models.TextField(choices=()) class BigD(models.Model): d = models.DecimalField(max_digits=32, decimal_places=30) class FloatModel(models.Model): size = models.FloatField() class BigS(models.Model): s = models.SlugField(max_length=255) class UnicodeSlugField(models.Model): s = models.SlugField(max_length=255, allow_unicode=True) class AutoModel(models.Model): value = models.AutoField(primary_key=True) class BigAutoModel(models.Model): value = models.BigAutoField(primary_key=True) class SmallAutoModel(models.Model): value = models.SmallAutoField(primary_key=True) class SmallIntegerModel(models.Model): value = models.SmallIntegerField() class IntegerModel(models.Model): value = models.IntegerField() class BigIntegerModel(models.Model): value = models.BigIntegerField() null_value = models.BigIntegerField(null=True, blank=True) class PositiveSmallIntegerModel(models.Model): value = models.PositiveSmallIntegerField() class PositiveIntegerModel(models.Model): value = models.PositiveIntegerField() class Post(models.Model): title = models.CharField(max_length=100) body = models.TextField() class NullBooleanModel(models.Model): nbfield = models.BooleanField(null=True, blank=True) nbfield_old = models.NullBooleanField() class BooleanModel(models.Model): bfield = models.BooleanField() string = models.CharField(max_length=10, default='abc') class DateTimeModel(models.Model): d = models.DateField() dt = models.DateTimeField() t = models.TimeField() class DurationModel(models.Model): field = models.DurationField() class NullDurationModel(models.Model): field = models.DurationField(null=True) class PrimaryKeyCharModel(models.Model): string = models.CharField(max_length=10, primary_key=True) class FksToBooleans(models.Model): """Model with FKs to models with {Null,}BooleanField's, #15040""" bf = models.ForeignKey(BooleanModel, models.CASCADE) nbf = models.ForeignKey(NullBooleanModel, models.CASCADE) class FkToChar(models.Model): """Model with FK to a model with a CharField primary key, #19299""" out = models.ForeignKey(PrimaryKeyCharModel, models.CASCADE) class RenamedField(models.Model): modelname = models.IntegerField(name="fieldname", choices=((1, 'One'),)) class VerboseNameField(models.Model): id = models.AutoField("verbose pk", primary_key=True) field1 = models.BigIntegerField("verbose field1") field2 = models.BooleanField("verbose field2", default=False) field3 = models.CharField("verbose field3", max_length=10) field4 = models.DateField("verbose field4") field5 = models.DateTimeField("verbose field5") field6 = models.DecimalField("verbose field6", max_digits=6, decimal_places=1) field7 = models.EmailField("verbose field7") field8 = models.FileField("verbose field8", upload_to="unused") field9 = models.FilePathField("verbose field9") field10 = models.FloatField("verbose field10") # Don't want to depend on Pillow in this test # field_image = models.ImageField("verbose field") field11 = models.IntegerField("verbose field11") field12 = models.GenericIPAddressField("verbose field12", protocol="ipv4") field13 = models.NullBooleanField("verbose field13") field14 = models.PositiveIntegerField("verbose field14") field15 = models.PositiveSmallIntegerField("verbose field15") field16 = models.SlugField("verbose field16") field17 = models.SmallIntegerField("verbose field17") field18 = models.TextField("verbose field18") field19 = models.TimeField("verbose field19") field20 = models.URLField("verbose field20") field21 = models.UUIDField("verbose field21") field22 = models.DurationField("verbose field22") class GenericIPAddress(models.Model): ip = models.GenericIPAddressField(null=True, protocol='ipv4') ############################################################################### # These models aren't used in any test, just here to ensure they validate # successfully. # See ticket #16570. class DecimalLessThanOne(models.Model): d = models.DecimalField(max_digits=3, decimal_places=3) # See ticket #18389. class FieldClassAttributeModel(models.Model): field_class = models.CharField ############################################################################### class DataModel(models.Model): short_data = models.BinaryField(max_length=10, default=b'\x08') data = models.BinaryField() ############################################################################### # FileField class Document(models.Model): myfile = models.FileField(upload_to='unused', unique=True) ############################################################################### # ImageField # If Pillow available, do these tests. if Image: class TestImageFieldFile(ImageFieldFile): """ Custom Field File class that records whether or not the underlying file was opened. """ def __init__(self, *args, **kwargs): self.was_opened = False super().__init__(*args, **kwargs) def open(self): self.was_opened = True super().open() class TestImageField(ImageField): attr_class = TestImageFieldFile # Set up a temp directory for file storage. temp_storage_dir = tempfile.mkdtemp() temp_storage = FileSystemStorage(temp_storage_dir) temp_upload_to_dir = os.path.join(temp_storage.location, 'tests') class Person(models.Model): """ Model that defines an ImageField with no dimension fields. """ name = models.CharField(max_length=50) mugshot = TestImageField(storage=temp_storage, upload_to='tests') class AbstractPersonWithHeight(models.Model): """ Abstract model that defines an ImageField with only one dimension field to make sure the dimension update is correctly run on concrete subclass instance post-initialization. """ mugshot = TestImageField(storage=temp_storage, upload_to='tests', height_field='mugshot_height') mugshot_height = models.PositiveSmallIntegerField() class Meta: abstract = True class PersonWithHeight(AbstractPersonWithHeight): """ Concrete model that subclass an abstract one with only on dimension field. """ name = models.CharField(max_length=50) class PersonWithHeightAndWidth(models.Model): """ Model that defines height and width fields after the ImageField. """ name = models.CharField(max_length=50) mugshot = TestImageField(storage=temp_storage, upload_to='tests', height_field='mugshot_height', width_field='mugshot_width') mugshot_height = models.PositiveSmallIntegerField() mugshot_width = models.PositiveSmallIntegerField() class PersonDimensionsFirst(models.Model): """ Model that defines height and width fields before the ImageField. """ name = models.CharField(max_length=50) mugshot_height = models.PositiveSmallIntegerField() mugshot_width = models.PositiveSmallIntegerField() mugshot = TestImageField(storage=temp_storage, upload_to='tests', height_field='mugshot_height', width_field='mugshot_width') class PersonTwoImages(models.Model): """ Model that: * Defines two ImageFields * Defines the height/width fields before the ImageFields * Has a nullable ImageField """ name = models.CharField(max_length=50) mugshot_height = models.PositiveSmallIntegerField() mugshot_width = models.PositiveSmallIntegerField() mugshot = TestImageField(storage=temp_storage, upload_to='tests', height_field='mugshot_height', width_field='mugshot_width') headshot_height = models.PositiveSmallIntegerField( blank=True, null=True) headshot_width = models.PositiveSmallIntegerField( blank=True, null=True) headshot = TestImageField(blank=True, null=True, storage=temp_storage, upload_to='tests', height_field='headshot_height', width_field='headshot_width') class AllFieldsModel(models.Model): big_integer = models.BigIntegerField() binary = models.BinaryField() boolean = models.BooleanField(default=False) char = models.CharField(max_length=10) date = models.DateField() datetime = models.DateTimeField() decimal = models.DecimalField(decimal_places=2, max_digits=2) duration = models.DurationField() email = models.EmailField() file_path = models.FilePathField() floatf = models.FloatField() integer = models.IntegerField() generic_ip = models.GenericIPAddressField() null_boolean = models.NullBooleanField() positive_integer = models.PositiveIntegerField() positive_small_integer = models.PositiveSmallIntegerField() slug = models.SlugField() small_integer = models.SmallIntegerField() text = models.TextField() time = models.TimeField() url = models.URLField() uuid = models.UUIDField() fo = ForeignObject( 'self', on_delete=models.CASCADE, from_fields=['positive_integer'], to_fields=['id'], related_name='reverse' ) fk = ForeignKey( 'self', models.CASCADE, related_name='reverse2' ) m2m = ManyToManyField('self') oto = OneToOneField('self', models.CASCADE) object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType, models.CASCADE) gfk = GenericForeignKey() gr = GenericRelation(DataModel) class ManyToMany(models.Model): m2m = models.ManyToManyField('self') ############################################################################### class UUIDModel(models.Model): field = models.UUIDField() class NullableUUIDModel(models.Model): field = models.UUIDField(blank=True, null=True) class PrimaryKeyUUIDModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) class RelatedToUUIDModel(models.Model): uuid_fk = models.ForeignKey('PrimaryKeyUUIDModel', models.CASCADE) class UUIDChild(PrimaryKeyUUIDModel): pass class UUIDGrandchild(UUIDChild): pass
75f9166281c839bca2c8678ec95489c1d49365e004caa256d1d0f564f2610701
import json import uuid from django.core import exceptions, serializers from django.db import IntegrityError, connection, models from django.db.models import CharField, F, Value from django.db.models.functions import Concat, Repeat from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, skipUnlessDBFeature, ) from .models import ( NullableUUIDModel, PrimaryKeyUUIDModel, RelatedToUUIDModel, UUIDGrandchild, UUIDModel, ) class TestSaveLoad(TestCase): def test_uuid_instance(self): instance = UUIDModel.objects.create(field=uuid.uuid4()) loaded = UUIDModel.objects.get() self.assertEqual(loaded.field, instance.field) def test_str_instance_no_hyphens(self): UUIDModel.objects.create(field='550e8400e29b41d4a716446655440000') loaded = UUIDModel.objects.get() self.assertEqual(loaded.field, uuid.UUID('550e8400e29b41d4a716446655440000')) def test_str_instance_hyphens(self): UUIDModel.objects.create(field='550e8400-e29b-41d4-a716-446655440000') loaded = UUIDModel.objects.get() self.assertEqual(loaded.field, uuid.UUID('550e8400e29b41d4a716446655440000')) def test_str_instance_bad_hyphens(self): UUIDModel.objects.create(field='550e84-00-e29b-41d4-a716-4-466-55440000') loaded = UUIDModel.objects.get() self.assertEqual(loaded.field, uuid.UUID('550e8400e29b41d4a716446655440000')) def test_null_handling(self): NullableUUIDModel.objects.create(field=None) loaded = NullableUUIDModel.objects.get() self.assertIsNone(loaded.field) def test_pk_validated(self): with self.assertRaisesMessage(exceptions.ValidationError, 'is not a valid UUID'): PrimaryKeyUUIDModel.objects.get(pk={}) with self.assertRaisesMessage(exceptions.ValidationError, 'is not a valid UUID'): PrimaryKeyUUIDModel.objects.get(pk=[]) def test_wrong_value(self): with self.assertRaisesMessage(exceptions.ValidationError, 'is not a valid UUID'): UUIDModel.objects.get(field='not-a-uuid') with self.assertRaisesMessage(exceptions.ValidationError, 'is not a valid UUID'): UUIDModel.objects.create(field='not-a-uuid') class TestMethods(SimpleTestCase): def test_deconstruct(self): field = models.UUIDField() name, path, args, kwargs = field.deconstruct() self.assertEqual(kwargs, {}) def test_to_python(self): self.assertIsNone(models.UUIDField().to_python(None)) def test_to_python_int_values(self): self.assertEqual( models.UUIDField().to_python(0), uuid.UUID('00000000-0000-0000-0000-000000000000') ) # Works for integers less than 128 bits. self.assertEqual( models.UUIDField().to_python((2 ** 128) - 1), uuid.UUID('ffffffff-ffff-ffff-ffff-ffffffffffff') ) def test_to_python_int_too_large(self): # Fails for integers larger than 128 bits. with self.assertRaises(exceptions.ValidationError): models.UUIDField().to_python(2 ** 128) class TestQuerying(TestCase): @classmethod def setUpTestData(cls): cls.objs = [ NullableUUIDModel.objects.create(field=uuid.uuid4()), NullableUUIDModel.objects.create(field='550e8400e29b41d4a716446655440000'), NullableUUIDModel.objects.create(field=None), ] def assertSequenceEqualWithoutHyphens(self, qs, result): """ Backends with a native datatype for UUID don't support fragment lookups without hyphens because they store values with them. """ self.assertSequenceEqual( qs, [] if connection.features.has_native_uuid_field else result, ) def test_exact(self): self.assertSequenceEqual( NullableUUIDModel.objects.filter(field__exact='550e8400e29b41d4a716446655440000'), [self.objs[1]] ) self.assertSequenceEqual( NullableUUIDModel.objects.filter( field__exact='550e8400-e29b-41d4-a716-446655440000' ), [self.objs[1]], ) def test_iexact(self): self.assertSequenceEqualWithoutHyphens( NullableUUIDModel.objects.filter( field__iexact='550E8400E29B41D4A716446655440000' ), [self.objs[1]], ) self.assertSequenceEqual( NullableUUIDModel.objects.filter( field__iexact='550E8400-E29B-41D4-A716-446655440000' ), [self.objs[1]], ) def test_isnull(self): self.assertSequenceEqual( NullableUUIDModel.objects.filter(field__isnull=True), [self.objs[2]] ) def test_contains(self): self.assertSequenceEqualWithoutHyphens( NullableUUIDModel.objects.filter(field__contains='8400e29b'), [self.objs[1]], ) self.assertSequenceEqual( NullableUUIDModel.objects.filter(field__contains='8400-e29b'), [self.objs[1]], ) def test_icontains(self): self.assertSequenceEqualWithoutHyphens( NullableUUIDModel.objects.filter(field__icontains='8400E29B'), [self.objs[1]], ) self.assertSequenceEqual( NullableUUIDModel.objects.filter(field__icontains='8400-E29B'), [self.objs[1]], ) def test_startswith(self): self.assertSequenceEqualWithoutHyphens( NullableUUIDModel.objects.filter(field__startswith='550e8400e29b4'), [self.objs[1]], ) self.assertSequenceEqual( NullableUUIDModel.objects.filter(field__startswith='550e8400-e29b-4'), [self.objs[1]], ) def test_istartswith(self): self.assertSequenceEqualWithoutHyphens( NullableUUIDModel.objects.filter(field__istartswith='550E8400E29B4'), [self.objs[1]], ) self.assertSequenceEqual( NullableUUIDModel.objects.filter(field__istartswith='550E8400-E29B-4'), [self.objs[1]], ) def test_endswith(self): self.assertSequenceEqualWithoutHyphens( NullableUUIDModel.objects.filter(field__endswith='a716446655440000'), [self.objs[1]], ) self.assertSequenceEqual( NullableUUIDModel.objects.filter(field__endswith='a716-446655440000'), [self.objs[1]], ) def test_iendswith(self): self.assertSequenceEqualWithoutHyphens( NullableUUIDModel.objects.filter(field__iendswith='A716446655440000'), [self.objs[1]], ) self.assertSequenceEqual( NullableUUIDModel.objects.filter(field__iendswith='A716-446655440000'), [self.objs[1]], ) def test_filter_with_expr(self): self.assertSequenceEqualWithoutHyphens( NullableUUIDModel.objects.annotate( value=Concat(Value('8400'), Value('e29b'), output_field=CharField()), ).filter(field__contains=F('value')), [self.objs[1]], ) self.assertSequenceEqual( NullableUUIDModel.objects.annotate( value=Concat(Value('8400'), Value('-'), Value('e29b'), output_field=CharField()), ).filter(field__contains=F('value')), [self.objs[1]], ) self.assertSequenceEqual( NullableUUIDModel.objects.annotate( value=Repeat(Value('0'), 4, output_field=CharField()), ).filter(field__contains=F('value')), [self.objs[1]], ) class TestSerialization(SimpleTestCase): test_data = ( '[{"fields": {"field": "550e8400-e29b-41d4-a716-446655440000"}, ' '"model": "model_fields.uuidmodel", "pk": null}]' ) nullable_test_data = ( '[{"fields": {"field": null}, ' '"model": "model_fields.nullableuuidmodel", "pk": null}]' ) def test_dumping(self): instance = UUIDModel(field=uuid.UUID('550e8400e29b41d4a716446655440000')) data = serializers.serialize('json', [instance]) self.assertEqual(json.loads(data), json.loads(self.test_data)) def test_loading(self): instance = list(serializers.deserialize('json', self.test_data))[0].object self.assertEqual(instance.field, uuid.UUID('550e8400-e29b-41d4-a716-446655440000')) def test_nullable_loading(self): instance = list(serializers.deserialize('json', self.nullable_test_data))[0].object self.assertIsNone(instance.field) class TestValidation(SimpleTestCase): def test_invalid_uuid(self): field = models.UUIDField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean('550e8400', None) self.assertEqual(cm.exception.code, 'invalid') self.assertEqual(cm.exception.message % cm.exception.params, '“550e8400” is not a valid UUID.') def test_uuid_instance_ok(self): field = models.UUIDField() field.clean(uuid.uuid4(), None) # no error class TestAsPrimaryKey(TestCase): def test_creation(self): PrimaryKeyUUIDModel.objects.create() loaded = PrimaryKeyUUIDModel.objects.get() self.assertIsInstance(loaded.pk, uuid.UUID) def test_uuid_pk_on_save(self): saved = PrimaryKeyUUIDModel.objects.create(id=None) loaded = PrimaryKeyUUIDModel.objects.get() self.assertIsNotNone(loaded.id, None) self.assertEqual(loaded.id, saved.id) def test_uuid_pk_on_bulk_create(self): u1 = PrimaryKeyUUIDModel() u2 = PrimaryKeyUUIDModel(id=None) PrimaryKeyUUIDModel.objects.bulk_create([u1, u2]) # The two objects were correctly created. u1_found = PrimaryKeyUUIDModel.objects.filter(id=u1.id).exists() u2_found = PrimaryKeyUUIDModel.objects.exclude(id=u1.id).exists() self.assertTrue(u1_found) self.assertTrue(u2_found) self.assertEqual(PrimaryKeyUUIDModel.objects.count(), 2) def test_underlying_field(self): pk_model = PrimaryKeyUUIDModel.objects.create() RelatedToUUIDModel.objects.create(uuid_fk=pk_model) related = RelatedToUUIDModel.objects.get() self.assertEqual(related.uuid_fk.pk, related.uuid_fk_id) def test_update_with_related_model_instance(self): # regression for #24611 u1 = PrimaryKeyUUIDModel.objects.create() u2 = PrimaryKeyUUIDModel.objects.create() r = RelatedToUUIDModel.objects.create(uuid_fk=u1) RelatedToUUIDModel.objects.update(uuid_fk=u2) r.refresh_from_db() self.assertEqual(r.uuid_fk, u2) def test_update_with_related_model_id(self): u1 = PrimaryKeyUUIDModel.objects.create() u2 = PrimaryKeyUUIDModel.objects.create() r = RelatedToUUIDModel.objects.create(uuid_fk=u1) RelatedToUUIDModel.objects.update(uuid_fk=u2.pk) r.refresh_from_db() self.assertEqual(r.uuid_fk, u2) def test_two_level_foreign_keys(self): gc = UUIDGrandchild() # exercises ForeignKey.get_db_prep_value() gc.save() self.assertIsInstance(gc.uuidchild_ptr_id, uuid.UUID) gc.refresh_from_db() self.assertIsInstance(gc.uuidchild_ptr_id, uuid.UUID) class TestAsPrimaryKeyTransactionTests(TransactionTestCase): # Need a TransactionTestCase to avoid deferring FK constraint checking. available_apps = ['model_fields'] @skipUnlessDBFeature('supports_foreign_keys') def test_unsaved_fk(self): u1 = PrimaryKeyUUIDModel() with self.assertRaises(IntegrityError): RelatedToUUIDModel.objects.create(uuid_fk=u1)
8fee6c86633d1e4bc3805900dbb59839c866d1f5c8f8076e0f5d8b86fadea113
import unittest from decimal import Decimal from django.core import validators from django.core.exceptions import ValidationError from django.db import connection, models from django.test import TestCase from .models import BigD, Foo class DecimalFieldTests(TestCase): def test_to_python(self): f = models.DecimalField(max_digits=4, decimal_places=2) self.assertEqual(f.to_python(3), Decimal('3')) self.assertEqual(f.to_python('3.14'), Decimal('3.14')) # to_python() converts floats and honors max_digits. self.assertEqual(f.to_python(3.1415926535897), Decimal('3.142')) self.assertEqual(f.to_python(2.4), Decimal('2.400')) # Uses default rounding of ROUND_HALF_EVEN. self.assertEqual(f.to_python(2.0625), Decimal('2.062')) self.assertEqual(f.to_python(2.1875), Decimal('2.188')) msg = '“abc” value must be a decimal number.' with self.assertRaisesMessage(ValidationError, msg): f.to_python('abc') def test_default(self): f = models.DecimalField(default=Decimal('0.00')) self.assertEqual(f.get_default(), Decimal('0.00')) def test_get_prep_value(self): f = models.DecimalField(max_digits=5, decimal_places=1) self.assertIsNone(f.get_prep_value(None)) self.assertEqual(f.get_prep_value('2.4'), Decimal('2.4')) def test_filter_with_strings(self): """ Should be able to filter decimal fields using strings (#8023). """ foo = Foo.objects.create(a='abc', d=Decimal('12.34')) self.assertEqual(list(Foo.objects.filter(d='12.34')), [foo]) def test_save_without_float_conversion(self): """ Ensure decimals don't go through a corrupting float conversion during save (#5079). """ bd = BigD(d='12.9') bd.save() bd = BigD.objects.get(pk=bd.pk) self.assertEqual(bd.d, Decimal('12.9')) @unittest.skipIf(connection.vendor == 'sqlite', 'SQLite stores values rounded to 15 significant digits.') def test_fetch_from_db_without_float_rounding(self): big_decimal = BigD.objects.create(d=Decimal('.100000000000000000000000000005')) big_decimal.refresh_from_db() self.assertEqual(big_decimal.d, Decimal('.100000000000000000000000000005')) def test_lookup_really_big_value(self): """ Really big values can be used in a filter statement. """ # This should not crash. Foo.objects.filter(d__gte=100000000000) def test_max_digits_validation(self): field = models.DecimalField(max_digits=2) expected_message = validators.DecimalValidator.messages['max_digits'] % {'max': 2} with self.assertRaisesMessage(ValidationError, expected_message): field.clean(100, None) def test_max_decimal_places_validation(self): field = models.DecimalField(decimal_places=1) expected_message = validators.DecimalValidator.messages['max_decimal_places'] % {'max': 1} with self.assertRaisesMessage(ValidationError, expected_message): field.clean(Decimal('0.99'), None) def test_max_whole_digits_validation(self): field = models.DecimalField(max_digits=3, decimal_places=1) expected_message = validators.DecimalValidator.messages['max_whole_digits'] % {'max': 2} with self.assertRaisesMessage(ValidationError, expected_message): field.clean(Decimal('999'), None) def test_roundtrip_with_trailing_zeros(self): """Trailing zeros in the fractional part aren't truncated.""" obj = Foo.objects.create(a='bar', d=Decimal('8.320')) obj.refresh_from_db() self.assertEqual(obj.d.compare_total(Decimal('8.320')), Decimal('0'))
c9309596f0080d68d2a653fe5b75b404030957dbc959457ff34bbf4c8dd10e41
from unittest import skipIf from django.core.exceptions import ValidationError from django.db import connection, models from django.test import SimpleTestCase, TestCase from .models import Post class TestCharField(TestCase): def test_max_length_passed_to_formfield(self): """ CharField passes its max_length attribute to form fields created using the formfield() method. """ cf1 = models.CharField() cf2 = models.CharField(max_length=1234) self.assertIsNone(cf1.formfield().max_length) self.assertEqual(1234, cf2.formfield().max_length) def test_lookup_integer_in_charfield(self): self.assertEqual(Post.objects.filter(title=9).count(), 0) @skipIf(connection.vendor == 'mysql', 'Running on MySQL requires utf8mb4 encoding (#18392)') def test_emoji(self): p = Post.objects.create(title='Smile 😀', body='Whatever.') p.refresh_from_db() self.assertEqual(p.title, 'Smile 😀') def test_assignment_from_choice_enum(self): class Event(models.TextChoices): C = 'Carnival!' F = 'Festival!' p1 = Post.objects.create(title=Event.C, body=Event.F) p1.refresh_from_db() self.assertEqual(p1.title, 'Carnival!') self.assertEqual(p1.body, 'Festival!') self.assertEqual(p1.title, Event.C) self.assertEqual(p1.body, Event.F) p2 = Post.objects.get(title='Carnival!') self.assertEquals(p1, p2) self.assertEquals(p2.title, Event.C) class ValidationTests(SimpleTestCase): class Choices(models.TextChoices): C = 'c', 'C' def test_charfield_raises_error_on_empty_string(self): f = models.CharField() with self.assertRaises(ValidationError): f.clean('', None) def test_charfield_cleans_empty_string_when_blank_true(self): f = models.CharField(blank=True) self.assertEqual('', f.clean('', None)) def test_charfield_with_choices_cleans_valid_choice(self): f = models.CharField(max_length=1, choices=[('a', 'A'), ('b', 'B')]) self.assertEqual('a', f.clean('a', None)) def test_charfield_with_choices_raises_error_on_invalid_choice(self): f = models.CharField(choices=[('a', 'A'), ('b', 'B')]) with self.assertRaises(ValidationError): f.clean('not a', None) def test_enum_choices_cleans_valid_string(self): f = models.CharField(choices=self.Choices.choices, max_length=1) self.assertEqual(f.clean('c', None), 'c') def test_enum_choices_invalid_input(self): f = models.CharField(choices=self.Choices.choices, max_length=1) with self.assertRaises(ValidationError): f.clean('a', None) def test_charfield_raises_error_on_empty_input(self): f = models.CharField(null=False) with self.assertRaises(ValidationError): f.clean(None, None)
ad421538b0c2eafd4403344a764c719def7ddfdbbf66fa6649870db2f69d5e1e
from django.db import transaction from django.test import TestCase from .models import FloatModel class TestFloatField(TestCase): def test_float_validates_object(self): instance = FloatModel(size=2.5) # Try setting float field to unsaved object instance.size = instance with transaction.atomic(): with self.assertRaises(TypeError): instance.save() # Set value to valid and save instance.size = 2.5 instance.save() self.assertTrue(instance.id) # Set field to object on saved instance instance.size = instance msg = ( 'Tried to update field model_fields.FloatModel.size with a model ' 'instance, %r. Use a value compatible with FloatField.' ) % instance with transaction.atomic(): with self.assertRaisesMessage(TypeError, msg): instance.save() # Try setting field to object on retrieved object obj = FloatModel.objects.get(pk=instance.id) obj.size = obj with self.assertRaisesMessage(TypeError, msg): obj.save() def test_invalid_value(self): tests = [ (TypeError, ()), (TypeError, []), (TypeError, {}), (TypeError, set()), (TypeError, object()), (TypeError, complex()), (ValueError, 'non-numeric string'), (ValueError, b'non-numeric byte-string'), ] for exception, value in tests: with self.subTest(value): msg = "Field 'size' expected a number but got %r." % (value,) with self.assertRaisesMessage(exception, msg): FloatModel.objects.create(size=value)
0cabe9a78015c56515689ba6828b58b3194e08e05f9f929c6084cb9ee9432b5c
from unittest import mock from django.core.exceptions import ValidationError from django.db import IntegrityError, connection, models from django.db.models.constraints import BaseConstraint from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from .models import ChildModel, Product, UniqueConstraintProduct def get_constraints(table): with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) class BaseConstraintTests(SimpleTestCase): def test_constraint_sql(self): c = BaseConstraint('name') msg = 'This method must be implemented by a subclass.' with self.assertRaisesMessage(NotImplementedError, msg): c.constraint_sql(None, None) def test_create_sql(self): c = BaseConstraint('name') msg = 'This method must be implemented by a subclass.' with self.assertRaisesMessage(NotImplementedError, msg): c.create_sql(None, None) def test_remove_sql(self): c = BaseConstraint('name') msg = 'This method must be implemented by a subclass.' with self.assertRaisesMessage(NotImplementedError, msg): c.remove_sql(None, None) class CheckConstraintTests(TestCase): def test_eq(self): check1 = models.Q(price__gt=models.F('discounted_price')) check2 = models.Q(price__lt=models.F('discounted_price')) self.assertEqual( models.CheckConstraint(check=check1, name='price'), models.CheckConstraint(check=check1, name='price'), ) self.assertEqual(models.CheckConstraint(check=check1, name='price'), mock.ANY) self.assertNotEqual( models.CheckConstraint(check=check1, name='price'), models.CheckConstraint(check=check1, name='price2'), ) self.assertNotEqual( models.CheckConstraint(check=check1, name='price'), models.CheckConstraint(check=check2, name='price'), ) self.assertNotEqual(models.CheckConstraint(check=check1, name='price'), 1) def test_repr(self): check = models.Q(price__gt=models.F('discounted_price')) name = 'price_gt_discounted_price' constraint = models.CheckConstraint(check=check, name=name) self.assertEqual( repr(constraint), "<CheckConstraint: check='{}' name='{}'>".format(check, name), ) def test_deconstruction(self): check = models.Q(price__gt=models.F('discounted_price')) name = 'price_gt_discounted_price' constraint = models.CheckConstraint(check=check, name=name) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, 'django.db.models.CheckConstraint') self.assertEqual(args, ()) self.assertEqual(kwargs, {'check': check, 'name': name}) @skipUnlessDBFeature('supports_table_check_constraints') def test_database_constraint(self): Product.objects.create(price=10, discounted_price=5) with self.assertRaises(IntegrityError): Product.objects.create(price=10, discounted_price=20) @skipUnlessDBFeature('supports_table_check_constraints', 'can_introspect_check_constraints') def test_name(self): constraints = get_constraints(Product._meta.db_table) for expected_name in ( 'price_gt_discounted_price', 'constraints_product_price_gt_0', ): with self.subTest(expected_name): self.assertIn(expected_name, constraints) @skipUnlessDBFeature('supports_table_check_constraints', 'can_introspect_check_constraints') def test_abstract_name(self): constraints = get_constraints(ChildModel._meta.db_table) self.assertIn('constraints_childmodel_adult', constraints) class UniqueConstraintTests(TestCase): @classmethod def setUpTestData(cls): cls.p1, cls.p2 = UniqueConstraintProduct.objects.bulk_create([ UniqueConstraintProduct(name='p1', color='red'), UniqueConstraintProduct(name='p2'), ]) def test_eq(self): self.assertEqual( models.UniqueConstraint(fields=['foo', 'bar'], name='unique'), models.UniqueConstraint(fields=['foo', 'bar'], name='unique'), ) self.assertEqual( models.UniqueConstraint(fields=['foo', 'bar'], name='unique'), mock.ANY, ) self.assertNotEqual( models.UniqueConstraint(fields=['foo', 'bar'], name='unique'), models.UniqueConstraint(fields=['foo', 'bar'], name='unique2'), ) self.assertNotEqual( models.UniqueConstraint(fields=['foo', 'bar'], name='unique'), models.UniqueConstraint(fields=['foo', 'baz'], name='unique'), ) self.assertNotEqual(models.UniqueConstraint(fields=['foo', 'bar'], name='unique'), 1) def test_eq_with_condition(self): self.assertEqual( models.UniqueConstraint( fields=['foo', 'bar'], name='unique', condition=models.Q(foo=models.F('bar')) ), models.UniqueConstraint( fields=['foo', 'bar'], name='unique', condition=models.Q(foo=models.F('bar'))), ) self.assertNotEqual( models.UniqueConstraint( fields=['foo', 'bar'], name='unique', condition=models.Q(foo=models.F('bar')) ), models.UniqueConstraint( fields=['foo', 'bar'], name='unique', condition=models.Q(foo=models.F('baz')) ), ) def test_repr(self): fields = ['foo', 'bar'] name = 'unique_fields' constraint = models.UniqueConstraint(fields=fields, name=name) self.assertEqual( repr(constraint), "<UniqueConstraint: fields=('foo', 'bar') name='unique_fields'>", ) def test_repr_with_condition(self): constraint = models.UniqueConstraint( fields=['foo', 'bar'], name='unique_fields', condition=models.Q(foo=models.F('bar')), ) self.assertEqual( repr(constraint), "<UniqueConstraint: fields=('foo', 'bar') name='unique_fields' " "condition=(AND: ('foo', F(bar)))>", ) def test_deconstruction(self): fields = ['foo', 'bar'] name = 'unique_fields' constraint = models.UniqueConstraint(fields=fields, name=name) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, 'django.db.models.UniqueConstraint') self.assertEqual(args, ()) self.assertEqual(kwargs, {'fields': tuple(fields), 'name': name}) def test_deconstruction_with_condition(self): fields = ['foo', 'bar'] name = 'unique_fields' condition = models.Q(foo=models.F('bar')) constraint = models.UniqueConstraint(fields=fields, name=name, condition=condition) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, 'django.db.models.UniqueConstraint') self.assertEqual(args, ()) self.assertEqual(kwargs, {'fields': tuple(fields), 'name': name, 'condition': condition}) def test_database_constraint(self): with self.assertRaises(IntegrityError): UniqueConstraintProduct.objects.create(name=self.p1.name, color=self.p1.color) def test_model_validation(self): msg = 'Unique constraint product with this Name and Color already exists.' with self.assertRaisesMessage(ValidationError, msg): UniqueConstraintProduct(name=self.p1.name, color=self.p1.color).validate_unique() def test_model_validation_with_condition(self): """Partial unique constraints are ignored by Model.validate_unique().""" UniqueConstraintProduct(name=self.p1.name, color='blue').validate_unique() UniqueConstraintProduct(name=self.p2.name).validate_unique() def test_name(self): constraints = get_constraints(UniqueConstraintProduct._meta.db_table) expected_name = 'name_color_uniq' self.assertIn(expected_name, constraints) def test_condition_must_be_q(self): with self.assertRaisesMessage(ValueError, 'UniqueConstraint.condition must be a Q instance.'): models.UniqueConstraint(name='uniq', fields=['name'], condition='invalid')
8dc38b12e2be07054e39c630407533b5eb7808d20d4596c431a337e0d6a4ae87
from django.db import models class Product(models.Model): price = models.IntegerField(null=True) discounted_price = models.IntegerField(null=True) class Meta: required_db_features = { 'supports_table_check_constraints', } constraints = [ models.CheckConstraint( check=models.Q(price__gt=models.F('discounted_price')), name='price_gt_discounted_price', ), models.CheckConstraint( check=models.Q(price__gt=0), name='%(app_label)s_%(class)s_price_gt_0', ), ] class UniqueConstraintProduct(models.Model): name = models.CharField(max_length=255) color = models.CharField(max_length=32, null=True) class Meta: constraints = [ models.UniqueConstraint(fields=['name', 'color'], name='name_color_uniq'), models.UniqueConstraint( fields=['name'], name='name_without_color_uniq', condition=models.Q(color__isnull=True), ), ] class AbstractModel(models.Model): age = models.IntegerField() class Meta: abstract = True required_db_features = { 'supports_table_check_constraints', } constraints = [ models.CheckConstraint( check=models.Q(age__gte=18), name='%(app_label)s_%(class)s_adult', ), ] class ChildModel(AbstractModel): pass
c5802ed573cf87f0877f07834cfd6f5c3270258f36bae98b73df405a0aa88ccf
import warnings from datetime import datetime from django.core.paginator import ( EmptyPage, InvalidPage, PageNotAnInteger, Paginator, UnorderedObjectListWarning, ) from django.test import SimpleTestCase, TestCase from .custom import ValidAdjacentNumsPaginator from .models import Article class PaginationTests(SimpleTestCase): """ Tests for the Paginator and Page classes. """ def check_paginator(self, params, output): """ Helper method that instantiates a Paginator object from the passed params and then checks that its attributes match the passed output. """ count, num_pages, page_range = output paginator = Paginator(*params) self.check_attribute('count', paginator, count, params) self.check_attribute('num_pages', paginator, num_pages, params) self.check_attribute('page_range', paginator, page_range, params, coerce=list) def check_attribute(self, name, paginator, expected, params, coerce=None): """ Helper method that checks a single attribute and gives a nice error message upon test failure. """ got = getattr(paginator, name) if coerce is not None: got = coerce(got) self.assertEqual( expected, got, "For '%s', expected %s but got %s. Paginator parameters were: %s" % (name, expected, got, params) ) def test_paginator(self): """ Tests the paginator attributes using varying inputs. """ nine = [1, 2, 3, 4, 5, 6, 7, 8, 9] ten = nine + [10] eleven = ten + [11] tests = ( # Each item is two tuples: # First tuple is Paginator parameters - object_list, per_page, # orphans, and allow_empty_first_page. # Second tuple is resulting Paginator attributes - count, # num_pages, and page_range. # Ten items, varying orphans, no empty first page. ((ten, 4, 0, False), (10, 3, [1, 2, 3])), ((ten, 4, 1, False), (10, 3, [1, 2, 3])), ((ten, 4, 2, False), (10, 2, [1, 2])), ((ten, 4, 5, False), (10, 2, [1, 2])), ((ten, 4, 6, False), (10, 1, [1])), # Ten items, varying orphans, allow empty first page. ((ten, 4, 0, True), (10, 3, [1, 2, 3])), ((ten, 4, 1, True), (10, 3, [1, 2, 3])), ((ten, 4, 2, True), (10, 2, [1, 2])), ((ten, 4, 5, True), (10, 2, [1, 2])), ((ten, 4, 6, True), (10, 1, [1])), # One item, varying orphans, no empty first page. (([1], 4, 0, False), (1, 1, [1])), (([1], 4, 1, False), (1, 1, [1])), (([1], 4, 2, False), (1, 1, [1])), # One item, varying orphans, allow empty first page. (([1], 4, 0, True), (1, 1, [1])), (([1], 4, 1, True), (1, 1, [1])), (([1], 4, 2, True), (1, 1, [1])), # Zero items, varying orphans, no empty first page. (([], 4, 0, False), (0, 0, [])), (([], 4, 1, False), (0, 0, [])), (([], 4, 2, False), (0, 0, [])), # Zero items, varying orphans, allow empty first page. (([], 4, 0, True), (0, 1, [1])), (([], 4, 1, True), (0, 1, [1])), (([], 4, 2, True), (0, 1, [1])), # Number if items one less than per_page. (([], 1, 0, True), (0, 1, [1])), (([], 1, 0, False), (0, 0, [])), (([1], 2, 0, True), (1, 1, [1])), ((nine, 10, 0, True), (9, 1, [1])), # Number if items equal to per_page. (([1], 1, 0, True), (1, 1, [1])), (([1, 2], 2, 0, True), (2, 1, [1])), ((ten, 10, 0, True), (10, 1, [1])), # Number if items one more than per_page. (([1, 2], 1, 0, True), (2, 2, [1, 2])), (([1, 2, 3], 2, 0, True), (3, 2, [1, 2])), ((eleven, 10, 0, True), (11, 2, [1, 2])), # Number if items one more than per_page with one orphan. (([1, 2], 1, 1, True), (2, 1, [1])), (([1, 2, 3], 2, 1, True), (3, 1, [1])), ((eleven, 10, 1, True), (11, 1, [1])), # Non-integer inputs ((ten, '4', 1, False), (10, 3, [1, 2, 3])), ((ten, '4', 1, False), (10, 3, [1, 2, 3])), ((ten, 4, '1', False), (10, 3, [1, 2, 3])), ((ten, 4, '1', False), (10, 3, [1, 2, 3])), ) for params, output in tests: self.check_paginator(params, output) def test_invalid_page_number(self): """ Invalid page numbers result in the correct exception being raised. """ paginator = Paginator([1, 2, 3], 2) with self.assertRaises(InvalidPage): paginator.page(3) with self.assertRaises(PageNotAnInteger): paginator.validate_number(None) with self.assertRaises(PageNotAnInteger): paginator.validate_number('x') with self.assertRaises(PageNotAnInteger): paginator.validate_number(1.2) def test_float_integer_page(self): paginator = Paginator([1, 2, 3], 2) self.assertEqual(paginator.validate_number(1.0), 1) def test_no_content_allow_empty_first_page(self): # With no content and allow_empty_first_page=True, 1 is a valid page number paginator = Paginator([], 2) self.assertEqual(paginator.validate_number(1), 1) def test_paginate_misc_classes(self): class CountContainer: def count(self): return 42 # Paginator can be passed other objects with a count() method. paginator = Paginator(CountContainer(), 10) self.assertEqual(42, paginator.count) self.assertEqual(5, paginator.num_pages) self.assertEqual([1, 2, 3, 4, 5], list(paginator.page_range)) # Paginator can be passed other objects that implement __len__. class LenContainer: def __len__(self): return 42 paginator = Paginator(LenContainer(), 10) self.assertEqual(42, paginator.count) self.assertEqual(5, paginator.num_pages) self.assertEqual([1, 2, 3, 4, 5], list(paginator.page_range)) def test_count_does_not_silence_attribute_error(self): class AttributeErrorContainer: def count(self): raise AttributeError('abc') with self.assertRaisesMessage(AttributeError, 'abc'): Paginator(AttributeErrorContainer(), 10).count def test_count_does_not_silence_type_error(self): class TypeErrorContainer: def count(self): raise TypeError('abc') with self.assertRaisesMessage(TypeError, 'abc'): Paginator(TypeErrorContainer(), 10).count def check_indexes(self, params, page_num, indexes): """ Helper method that instantiates a Paginator object from the passed params and then checks that the start and end indexes of the passed page_num match those given as a 2-tuple in indexes. """ paginator = Paginator(*params) if page_num == 'first': page_num = 1 elif page_num == 'last': page_num = paginator.num_pages page = paginator.page(page_num) start, end = indexes msg = ("For %s of page %s, expected %s but got %s. Paginator parameters were: %s") self.assertEqual(start, page.start_index(), msg % ('start index', page_num, start, page.start_index(), params)) self.assertEqual(end, page.end_index(), msg % ('end index', page_num, end, page.end_index(), params)) def test_page_indexes(self): """ Paginator pages have the correct start and end indexes. """ ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] tests = ( # Each item is three tuples: # First tuple is Paginator parameters - object_list, per_page, # orphans, and allow_empty_first_page. # Second tuple is the start and end indexes of the first page. # Third tuple is the start and end indexes of the last page. # Ten items, varying per_page, no orphans. ((ten, 1, 0, True), (1, 1), (10, 10)), ((ten, 2, 0, True), (1, 2), (9, 10)), ((ten, 3, 0, True), (1, 3), (10, 10)), ((ten, 5, 0, True), (1, 5), (6, 10)), # Ten items, varying per_page, with orphans. ((ten, 1, 1, True), (1, 1), (9, 10)), ((ten, 1, 2, True), (1, 1), (8, 10)), ((ten, 3, 1, True), (1, 3), (7, 10)), ((ten, 3, 2, True), (1, 3), (7, 10)), ((ten, 3, 4, True), (1, 3), (4, 10)), ((ten, 5, 1, True), (1, 5), (6, 10)), ((ten, 5, 2, True), (1, 5), (6, 10)), ((ten, 5, 5, True), (1, 10), (1, 10)), # One item, varying orphans, no empty first page. (([1], 4, 0, False), (1, 1), (1, 1)), (([1], 4, 1, False), (1, 1), (1, 1)), (([1], 4, 2, False), (1, 1), (1, 1)), # One item, varying orphans, allow empty first page. (([1], 4, 0, True), (1, 1), (1, 1)), (([1], 4, 1, True), (1, 1), (1, 1)), (([1], 4, 2, True), (1, 1), (1, 1)), # Zero items, varying orphans, allow empty first page. (([], 4, 0, True), (0, 0), (0, 0)), (([], 4, 1, True), (0, 0), (0, 0)), (([], 4, 2, True), (0, 0), (0, 0)), ) for params, first, last in tests: self.check_indexes(params, 'first', first) self.check_indexes(params, 'last', last) # When no items and no empty first page, we should get EmptyPage error. with self.assertRaises(EmptyPage): self.check_indexes(([], 4, 0, False), 1, None) with self.assertRaises(EmptyPage): self.check_indexes(([], 4, 1, False), 1, None) with self.assertRaises(EmptyPage): self.check_indexes(([], 4, 2, False), 1, None) def test_page_sequence(self): """ A paginator page acts like a standard sequence. """ eleven = 'abcdefghijk' page2 = Paginator(eleven, per_page=5, orphans=1).page(2) self.assertEqual(len(page2), 6) self.assertIn('k', page2) self.assertNotIn('a', page2) self.assertEqual(''.join(page2), 'fghijk') self.assertEqual(''.join(reversed(page2)), 'kjihgf') def test_get_page_hook(self): """ A Paginator subclass can use the ``_get_page`` hook to return an alternative to the standard Page class. """ eleven = 'abcdefghijk' paginator = ValidAdjacentNumsPaginator(eleven, per_page=6) page1 = paginator.page(1) page2 = paginator.page(2) self.assertIsNone(page1.previous_page_number()) self.assertEqual(page1.next_page_number(), 2) self.assertEqual(page2.previous_page_number(), 1) self.assertIsNone(page2.next_page_number()) def test_page_range_iterator(self): """ Paginator.page_range should be an iterator. """ self.assertIsInstance(Paginator([1, 2, 3], 2).page_range, type(range(0))) def test_get_page(self): """ Paginator.get_page() returns a valid page even with invalid page arguments. """ paginator = Paginator([1, 2, 3], 2) page = paginator.get_page(1) self.assertEqual(page.number, 1) self.assertEqual(page.object_list, [1, 2]) # An empty page returns the last page. self.assertEqual(paginator.get_page(3).number, 2) # Non-integer page returns the first page. self.assertEqual(paginator.get_page(None).number, 1) def test_get_page_empty_object_list(self): """Paginator.get_page() with an empty object_list.""" paginator = Paginator([], 2) # An empty page returns the last page. self.assertEqual(paginator.get_page(1).number, 1) self.assertEqual(paginator.get_page(2).number, 1) # Non-integer page returns the first page. self.assertEqual(paginator.get_page(None).number, 1) def test_get_page_empty_object_list_and_allow_empty_first_page_false(self): """ Paginator.get_page() raises EmptyPage if allow_empty_first_page=False and object_list is empty. """ paginator = Paginator([], 2, allow_empty_first_page=False) with self.assertRaises(EmptyPage): paginator.get_page(1) def test_paginator_iteration(self): paginator = Paginator([1, 2, 3], 2) page_iterator = iter(paginator) for page, expected in enumerate(([1, 2], [3]), start=1): with self.subTest(page=page): self.assertEqual(expected, list(next(page_iterator))) class ModelPaginationTests(TestCase): """ Test pagination with Django model instances """ @classmethod def setUpTestData(cls): # Prepare a list of objects for pagination. for x in range(1, 10): a = Article(headline='Article %s' % x, pub_date=datetime(2005, 7, 29)) a.save() def test_first_page(self): paginator = Paginator(Article.objects.order_by('id'), 5) p = paginator.page(1) self.assertEqual("<Page 1 of 2>", str(p)) self.assertQuerysetEqual(p.object_list, [ "<Article: Article 1>", "<Article: Article 2>", "<Article: Article 3>", "<Article: Article 4>", "<Article: Article 5>" ]) self.assertTrue(p.has_next()) self.assertFalse(p.has_previous()) self.assertTrue(p.has_other_pages()) self.assertEqual(2, p.next_page_number()) with self.assertRaises(InvalidPage): p.previous_page_number() self.assertEqual(1, p.start_index()) self.assertEqual(5, p.end_index()) def test_last_page(self): paginator = Paginator(Article.objects.order_by('id'), 5) p = paginator.page(2) self.assertEqual("<Page 2 of 2>", str(p)) self.assertQuerysetEqual(p.object_list, [ "<Article: Article 6>", "<Article: Article 7>", "<Article: Article 8>", "<Article: Article 9>" ]) self.assertFalse(p.has_next()) self.assertTrue(p.has_previous()) self.assertTrue(p.has_other_pages()) with self.assertRaises(InvalidPage): p.next_page_number() self.assertEqual(1, p.previous_page_number()) self.assertEqual(6, p.start_index()) self.assertEqual(9, p.end_index()) def test_page_getitem(self): """ Tests proper behavior of a paginator page __getitem__ (queryset evaluation, slicing, exception raised). """ paginator = Paginator(Article.objects.order_by('id'), 5) p = paginator.page(1) # Make sure object_list queryset is not evaluated by an invalid __getitem__ call. # (this happens from the template engine when using eg: {% page_obj.has_previous %}) self.assertIsNone(p.object_list._result_cache) msg = 'Page indices must be integers or slices, not str.' with self.assertRaisesMessage(TypeError, msg): p['has_previous'] self.assertIsNone(p.object_list._result_cache) self.assertNotIsInstance(p.object_list, list) # Make sure slicing the Page object with numbers and slice objects work. self.assertEqual(p[0], Article.objects.get(headline='Article 1')) self.assertQuerysetEqual(p[slice(2)], [ "<Article: Article 1>", "<Article: Article 2>", ] ) # After __getitem__ is called, object_list is a list self.assertIsInstance(p.object_list, list) def test_paginating_unordered_queryset_raises_warning(self): msg = ( "Pagination may yield inconsistent results with an unordered " "object_list: <class 'pagination.models.Article'> QuerySet." ) with self.assertWarnsMessage(UnorderedObjectListWarning, msg) as cm: Paginator(Article.objects.all(), 5) # The warning points at the Paginator caller (i.e. the stacklevel # is appropriate). self.assertEqual(cm.filename, __file__) def test_paginating_empty_queryset_does_not_warn(self): with warnings.catch_warnings(record=True) as recorded: Paginator(Article.objects.none(), 5) self.assertEqual(len(recorded), 0) def test_paginating_unordered_object_list_raises_warning(self): """ Unordered object list warning with an object that has an ordered attribute but not a model attribute. """ class ObjectList: ordered = False object_list = ObjectList() msg = ( "Pagination may yield inconsistent results with an unordered " "object_list: {!r}.".format(object_list) ) with self.assertWarnsMessage(UnorderedObjectListWarning, msg): Paginator(object_list, 5)
03f35abe645ff67b3a904d045c3bb7fa48499a640a3422f148423bcb0dd7319d
import datetime import pickle import unittest import uuid from copy import deepcopy from unittest import mock from django.core.exceptions import FieldError from django.db import DatabaseError, connection, models from django.db.models import CharField, Q, TimeField, UUIDField from django.db.models.aggregates import ( Avg, Count, Max, Min, StdDev, Sum, Variance, ) from django.db.models.expressions import ( Case, Col, Combinable, Exists, Expression, ExpressionList, ExpressionWrapper, F, Func, OrderBy, OuterRef, Random, RawSQL, Ref, Subquery, Value, When, ) from django.db.models.functions import ( Coalesce, Concat, Length, Lower, Substr, Upper, ) from django.db.models.sql import constants from django.db.models.sql.datastructures import Join from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import Approximate, isolate_apps from .models import ( UUID, UUIDPK, Company, Employee, Experiment, Number, RemoteEmployee, Result, SimulationRun, Time, ) class BasicExpressionsTests(TestCase): @classmethod def setUpTestData(cls): cls.example_inc = Company.objects.create( name="Example Inc.", num_employees=2300, num_chairs=5, ceo=Employee.objects.create(firstname="Joe", lastname="Smith", salary=10) ) cls.foobar_ltd = Company.objects.create( name="Foobar Ltd.", num_employees=3, num_chairs=4, based_in_eu=True, ceo=Employee.objects.create(firstname="Frank", lastname="Meyer", salary=20) ) cls.max = Employee.objects.create(firstname='Max', lastname='Mustermann', salary=30) cls.gmbh = Company.objects.create(name='Test GmbH', num_employees=32, num_chairs=1, ceo=cls.max) def setUp(self): self.company_query = Company.objects.values( "name", "num_employees", "num_chairs" ).order_by( "name", "num_employees", "num_chairs" ) def test_annotate_values_aggregate(self): companies = Company.objects.annotate( salaries=F('ceo__salary'), ).values('num_employees', 'salaries').aggregate( result=Sum( F('salaries') + F('num_employees'), output_field=models.IntegerField() ), ) self.assertEqual(companies['result'], 2395) def test_annotate_values_filter(self): companies = Company.objects.annotate( foo=RawSQL('%s', ['value']), ).filter(foo='value').order_by('name') self.assertQuerysetEqual( companies, ['<Company: Example Inc.>', '<Company: Foobar Ltd.>', '<Company: Test GmbH>'], ) def test_annotate_values_count(self): companies = Company.objects.annotate(foo=RawSQL('%s', ['value'])) self.assertEqual(companies.count(), 3) @skipUnlessDBFeature('supports_boolean_expr_in_select_clause') def test_filtering_on_annotate_that_uses_q(self): self.assertEqual( Company.objects.annotate( num_employees_check=ExpressionWrapper(Q(num_employees__gt=3), output_field=models.BooleanField()) ).filter(num_employees_check=True).count(), 2, ) def test_filtering_on_q_that_is_boolean(self): self.assertEqual( Company.objects.filter( ExpressionWrapper(Q(num_employees__gt=3), output_field=models.BooleanField()) ).count(), 2, ) def test_filter_inter_attribute(self): # We can filter on attribute relationships on same model obj, e.g. # find companies where the number of employees is greater # than the number of chairs. self.assertSequenceEqual( self.company_query.filter(num_employees__gt=F("num_chairs")), [ { "num_chairs": 5, "name": "Example Inc.", "num_employees": 2300, }, { "num_chairs": 1, "name": "Test GmbH", "num_employees": 32 }, ], ) def test_update(self): # We can set one field to have the value of another field # Make sure we have enough chairs self.company_query.update(num_chairs=F("num_employees")) self.assertSequenceEqual( self.company_query, [ { "num_chairs": 2300, "name": "Example Inc.", "num_employees": 2300 }, { "num_chairs": 3, "name": "Foobar Ltd.", "num_employees": 3 }, { "num_chairs": 32, "name": "Test GmbH", "num_employees": 32 } ], ) def test_arithmetic(self): # We can perform arithmetic operations in expressions # Make sure we have 2 spare chairs self.company_query.update(num_chairs=F("num_employees") + 2) self.assertSequenceEqual( self.company_query, [ { 'num_chairs': 2302, 'name': 'Example Inc.', 'num_employees': 2300 }, { 'num_chairs': 5, 'name': 'Foobar Ltd.', 'num_employees': 3 }, { 'num_chairs': 34, 'name': 'Test GmbH', 'num_employees': 32 } ], ) def test_order_of_operations(self): # Law of order of operations is followed self.company_query.update(num_chairs=F('num_employees') + 2 * F('num_employees')) self.assertSequenceEqual( self.company_query, [ { 'num_chairs': 6900, 'name': 'Example Inc.', 'num_employees': 2300 }, { 'num_chairs': 9, 'name': 'Foobar Ltd.', 'num_employees': 3 }, { 'num_chairs': 96, 'name': 'Test GmbH', 'num_employees': 32 } ], ) def test_parenthesis_priority(self): # Law of order of operations can be overridden by parentheses self.company_query.update(num_chairs=(F('num_employees') + 2) * F('num_employees')) self.assertSequenceEqual( self.company_query, [ { 'num_chairs': 5294600, 'name': 'Example Inc.', 'num_employees': 2300 }, { 'num_chairs': 15, 'name': 'Foobar Ltd.', 'num_employees': 3 }, { 'num_chairs': 1088, 'name': 'Test GmbH', 'num_employees': 32 } ], ) def test_update_with_fk(self): # ForeignKey can become updated with the value of another ForeignKey. self.assertEqual(Company.objects.update(point_of_contact=F('ceo')), 3) self.assertQuerysetEqual( Company.objects.all(), ['Joe Smith', 'Frank Meyer', 'Max Mustermann'], lambda c: str(c.point_of_contact), ordered=False ) def test_update_with_none(self): Number.objects.create(integer=1, float=1.0) Number.objects.create(integer=2) Number.objects.filter(float__isnull=False).update(float=Value(None)) self.assertQuerysetEqual( Number.objects.all(), [None, None], lambda n: n.float, ordered=False ) def test_filter_with_join(self): # F Expressions can also span joins Company.objects.update(point_of_contact=F('ceo')) c = Company.objects.first() c.point_of_contact = Employee.objects.create(firstname="Guido", lastname="van Rossum") c.save() self.assertQuerysetEqual( Company.objects.filter(ceo__firstname=F('point_of_contact__firstname')), ['Foobar Ltd.', 'Test GmbH'], lambda c: c.name, ordered=False ) Company.objects.exclude( ceo__firstname=F("point_of_contact__firstname") ).update(name="foo") self.assertEqual( Company.objects.exclude( ceo__firstname=F('point_of_contact__firstname') ).get().name, "foo", ) msg = "Joined field references are not permitted in this query" with self.assertRaisesMessage(FieldError, msg): Company.objects.exclude( ceo__firstname=F('point_of_contact__firstname') ).update(name=F('point_of_contact__lastname')) def test_object_update(self): # F expressions can be used to update attributes on single objects self.gmbh.num_employees = F('num_employees') + 4 self.gmbh.save() self.gmbh.refresh_from_db() self.assertEqual(self.gmbh.num_employees, 36) def test_new_object_save(self): # We should be able to use Funcs when inserting new data test_co = Company(name=Lower(Value('UPPER')), num_employees=32, num_chairs=1, ceo=self.max) test_co.save() test_co.refresh_from_db() self.assertEqual(test_co.name, "upper") def test_new_object_create(self): test_co = Company.objects.create(name=Lower(Value('UPPER')), num_employees=32, num_chairs=1, ceo=self.max) test_co.refresh_from_db() self.assertEqual(test_co.name, "upper") def test_object_create_with_aggregate(self): # Aggregates are not allowed when inserting new data msg = 'Aggregate functions are not allowed in this query (num_employees=Max(Value(1))).' with self.assertRaisesMessage(FieldError, msg): Company.objects.create( name='Company', num_employees=Max(Value(1)), num_chairs=1, ceo=Employee.objects.create(firstname="Just", lastname="Doit", salary=30), ) def test_object_update_fk(self): # F expressions cannot be used to update attributes which are foreign # keys, or attributes which involve joins. test_gmbh = Company.objects.get(pk=self.gmbh.pk) msg = 'F(ceo)": "Company.point_of_contact" must be a "Employee" instance.' with self.assertRaisesMessage(ValueError, msg): test_gmbh.point_of_contact = F('ceo') test_gmbh.point_of_contact = self.gmbh.ceo test_gmbh.save() test_gmbh.name = F('ceo__lastname') msg = 'Joined field references are not permitted in this query' with self.assertRaisesMessage(FieldError, msg): test_gmbh.save() def test_update_inherited_field_value(self): msg = 'Joined field references are not permitted in this query' with self.assertRaisesMessage(FieldError, msg): RemoteEmployee.objects.update(adjusted_salary=F('salary') * 5) def test_object_update_unsaved_objects(self): # F expressions cannot be used to update attributes on objects which do # not yet exist in the database acme = Company(name='The Acme Widget Co.', num_employees=12, num_chairs=5, ceo=self.max) acme.num_employees = F("num_employees") + 16 msg = ( 'Failed to insert expression "Col(expressions_company, ' 'expressions.Company.num_employees) + Value(16)" on ' 'expressions.Company.num_employees. F() expressions can only be ' 'used to update, not to insert.' ) with self.assertRaisesMessage(ValueError, msg): acme.save() acme.num_employees = 12 acme.name = Lower(F('name')) msg = ( 'Failed to insert expression "Lower(Col(expressions_company, ' 'expressions.Company.name))" on expressions.Company.name. F() ' 'expressions can only be used to update, not to insert.' ) with self.assertRaisesMessage(ValueError, msg): acme.save() def test_ticket_11722_iexact_lookup(self): Employee.objects.create(firstname="John", lastname="Doe") Employee.objects.create(firstname="Test", lastname="test") queryset = Employee.objects.filter(firstname__iexact=F('lastname')) self.assertQuerysetEqual(queryset, ["<Employee: Test test>"]) def test_ticket_16731_startswith_lookup(self): Employee.objects.create(firstname="John", lastname="Doe") e2 = Employee.objects.create(firstname="Jack", lastname="Jackson") e3 = Employee.objects.create(firstname="Jack", lastname="jackson") self.assertSequenceEqual( Employee.objects.filter(lastname__startswith=F('firstname')), [e2, e3] if connection.features.has_case_insensitive_like else [e2] ) qs = Employee.objects.filter(lastname__istartswith=F('firstname')).order_by('pk') self.assertSequenceEqual(qs, [e2, e3]) def test_ticket_18375_join_reuse(self): # Reverse multijoin F() references and the lookup target the same join. # Pre #18375 the F() join was generated first and the lookup couldn't # reuse that join. qs = Employee.objects.filter(company_ceo_set__num_chairs=F('company_ceo_set__num_employees')) self.assertEqual(str(qs.query).count('JOIN'), 1) def test_ticket_18375_kwarg_ordering(self): # The next query was dict-randomization dependent - if the "gte=1" # was seen first, then the F() will reuse the join generated by the # gte lookup, if F() was seen first, then it generated a join the # other lookups could not reuse. qs = Employee.objects.filter( company_ceo_set__num_chairs=F('company_ceo_set__num_employees'), company_ceo_set__num_chairs__gte=1, ) self.assertEqual(str(qs.query).count('JOIN'), 1) def test_ticket_18375_kwarg_ordering_2(self): # Another similar case for F() than above. Now we have the same join # in two filter kwargs, one in the lhs lookup, one in F. Here pre # #18375 the amount of joins generated was random if dict # randomization was enabled, that is the generated query dependent # on which clause was seen first. qs = Employee.objects.filter( company_ceo_set__num_employees=F('pk'), pk=F('company_ceo_set__num_employees') ) self.assertEqual(str(qs.query).count('JOIN'), 1) def test_ticket_18375_chained_filters(self): # F() expressions do not reuse joins from previous filter. qs = Employee.objects.filter( company_ceo_set__num_employees=F('pk') ).filter( company_ceo_set__num_employees=F('company_ceo_set__num_employees') ) self.assertEqual(str(qs.query).count('JOIN'), 2) def test_order_by_exists(self): mary = Employee.objects.create(firstname='Mary', lastname='Mustermann', salary=20) mustermanns_by_seniority = Employee.objects.filter(lastname='Mustermann').order_by( # Order by whether the employee is the CEO of a company Exists(Company.objects.filter(ceo=OuterRef('pk'))).desc() ) self.assertSequenceEqual(mustermanns_by_seniority, [self.max, mary]) def test_order_by_multiline_sql(self): raw_order_by = ( RawSQL(''' CASE WHEN num_employees > 1000 THEN num_chairs ELSE 0 END ''', []).desc(), RawSQL(''' CASE WHEN num_chairs > 1 THEN 1 ELSE 0 END ''', []).asc() ) for qs in ( Company.objects.all(), Company.objects.distinct(), ): with self.subTest(qs=qs): self.assertSequenceEqual( qs.order_by(*raw_order_by), [self.example_inc, self.gmbh, self.foobar_ltd], ) def test_outerref(self): inner = Company.objects.filter(point_of_contact=OuterRef('pk')) msg = ( 'This queryset contains a reference to an outer query and may only ' 'be used in a subquery.' ) with self.assertRaisesMessage(ValueError, msg): inner.exists() outer = Employee.objects.annotate(is_point_of_contact=Exists(inner)) self.assertIs(outer.exists(), True) def test_exist_single_field_output_field(self): queryset = Company.objects.values('pk') self.assertIsInstance(Exists(queryset).output_field, models.BooleanField) def test_subquery(self): Company.objects.filter(name='Example Inc.').update( point_of_contact=Employee.objects.get(firstname='Joe', lastname='Smith'), ceo=self.max, ) Employee.objects.create(firstname='Bob', lastname='Brown', salary=40) qs = Employee.objects.annotate( is_point_of_contact=Exists(Company.objects.filter(point_of_contact=OuterRef('pk'))), is_not_point_of_contact=~Exists(Company.objects.filter(point_of_contact=OuterRef('pk'))), is_ceo_of_small_company=Exists(Company.objects.filter(num_employees__lt=200, ceo=OuterRef('pk'))), is_ceo_small_2=~~Exists(Company.objects.filter(num_employees__lt=200, ceo=OuterRef('pk'))), largest_company=Subquery(Company.objects.order_by('-num_employees').filter( models.Q(ceo=OuterRef('pk')) | models.Q(point_of_contact=OuterRef('pk')) ).values('name')[:1], output_field=models.CharField()) ).values( 'firstname', 'is_point_of_contact', 'is_not_point_of_contact', 'is_ceo_of_small_company', 'is_ceo_small_2', 'largest_company', ).order_by('firstname') results = list(qs) # Could use Coalesce(subq, Value('')) instead except for the bug in # cx_Oracle mentioned in #23843. bob = results[0] if bob['largest_company'] == '' and connection.features.interprets_empty_strings_as_nulls: bob['largest_company'] = None self.assertEqual(results, [ { 'firstname': 'Bob', 'is_point_of_contact': False, 'is_not_point_of_contact': True, 'is_ceo_of_small_company': False, 'is_ceo_small_2': False, 'largest_company': None, }, { 'firstname': 'Frank', 'is_point_of_contact': False, 'is_not_point_of_contact': True, 'is_ceo_of_small_company': True, 'is_ceo_small_2': True, 'largest_company': 'Foobar Ltd.', }, { 'firstname': 'Joe', 'is_point_of_contact': True, 'is_not_point_of_contact': False, 'is_ceo_of_small_company': False, 'is_ceo_small_2': False, 'largest_company': 'Example Inc.', }, { 'firstname': 'Max', 'is_point_of_contact': False, 'is_not_point_of_contact': True, 'is_ceo_of_small_company': True, 'is_ceo_small_2': True, 'largest_company': 'Example Inc.' } ]) # A less elegant way to write the same query: this uses a LEFT OUTER # JOIN and an IS NULL, inside a WHERE NOT IN which is probably less # efficient than EXISTS. self.assertCountEqual( qs.filter(is_point_of_contact=True).values('pk'), Employee.objects.exclude(company_point_of_contact_set=None).values('pk') ) def test_in_subquery(self): # This is a contrived test (and you really wouldn't write this query), # but it is a succinct way to test the __in=Subquery() construct. small_companies = Company.objects.filter(num_employees__lt=200).values('pk') subquery_test = Company.objects.filter(pk__in=Subquery(small_companies)) self.assertCountEqual(subquery_test, [self.foobar_ltd, self.gmbh]) subquery_test2 = Company.objects.filter(pk=Subquery(small_companies.filter(num_employees=3))) self.assertCountEqual(subquery_test2, [self.foobar_ltd]) def test_uuid_pk_subquery(self): u = UUIDPK.objects.create() UUID.objects.create(uuid_fk=u) qs = UUIDPK.objects.filter(id__in=Subquery(UUID.objects.values('uuid_fk__id'))) self.assertCountEqual(qs, [u]) def test_nested_subquery(self): inner = Company.objects.filter(point_of_contact=OuterRef('pk')) outer = Employee.objects.annotate(is_point_of_contact=Exists(inner)) contrived = Employee.objects.annotate( is_point_of_contact=Subquery( outer.filter(pk=OuterRef('pk')).values('is_point_of_contact'), output_field=models.BooleanField(), ), ) self.assertCountEqual(contrived.values_list(), outer.values_list()) def test_nested_subquery_outer_ref_2(self): first = Time.objects.create(time='09:00') second = Time.objects.create(time='17:00') third = Time.objects.create(time='21:00') SimulationRun.objects.bulk_create([ SimulationRun(start=first, end=second, midpoint='12:00'), SimulationRun(start=first, end=third, midpoint='15:00'), SimulationRun(start=second, end=first, midpoint='00:00'), ]) inner = Time.objects.filter(time=OuterRef(OuterRef('time')), pk=OuterRef('start')).values('time') middle = SimulationRun.objects.annotate(other=Subquery(inner)).values('other')[:1] outer = Time.objects.annotate(other=Subquery(middle, output_field=models.TimeField())) # This is a contrived example. It exercises the double OuterRef form. self.assertCountEqual(outer, [first, second, third]) def test_nested_subquery_outer_ref_with_autofield(self): first = Time.objects.create(time='09:00') second = Time.objects.create(time='17:00') SimulationRun.objects.create(start=first, end=second, midpoint='12:00') inner = SimulationRun.objects.filter(start=OuterRef(OuterRef('pk'))).values('start') middle = Time.objects.annotate(other=Subquery(inner)).values('other')[:1] outer = Time.objects.annotate(other=Subquery(middle, output_field=models.IntegerField())) # This exercises the double OuterRef form with AutoField as pk. self.assertCountEqual(outer, [first, second]) def test_annotations_within_subquery(self): Company.objects.filter(num_employees__lt=50).update(ceo=Employee.objects.get(firstname='Frank')) inner = Company.objects.filter( ceo=OuterRef('pk') ).values('ceo').annotate(total_employees=models.Sum('num_employees')).values('total_employees') outer = Employee.objects.annotate(total_employees=Subquery(inner)).filter(salary__lte=Subquery(inner)) self.assertSequenceEqual( outer.order_by('-total_employees').values('salary', 'total_employees'), [{'salary': 10, 'total_employees': 2300}, {'salary': 20, 'total_employees': 35}], ) def test_subquery_references_joined_table_twice(self): inner = Company.objects.filter( num_chairs__gte=OuterRef('ceo__salary'), num_employees__gte=OuterRef('point_of_contact__salary'), ) # Another contrived example (there is no need to have a subquery here) outer = Company.objects.filter(pk__in=Subquery(inner.values('pk'))) self.assertFalse(outer.exists()) def test_subquery_filter_by_aggregate(self): Number.objects.create(integer=1000, float=1.2) Employee.objects.create(salary=1000) qs = Number.objects.annotate( min_valuable_count=Subquery( Employee.objects.filter( salary=OuterRef('integer'), ).annotate(cnt=Count('salary')).filter(cnt__gt=0).values('cnt')[:1] ), ) self.assertEqual(qs.get().float, 1.2) def test_aggregate_subquery_annotation(self): with self.assertNumQueries(1) as ctx: aggregate = Company.objects.annotate( ceo_salary=Subquery( Employee.objects.filter( id=OuterRef('ceo_id'), ).values('salary') ), ).aggregate( ceo_salary_gt_20=Count('pk', filter=Q(ceo_salary__gt=20)), ) self.assertEqual(aggregate, {'ceo_salary_gt_20': 1}) # Aggregation over a subquery annotation doesn't annotate the subquery # twice in the inner query. sql = ctx.captured_queries[0]['sql'] self.assertLessEqual(sql.count('SELECT'), 3) # GROUP BY isn't required to aggregate over a query that doesn't # contain nested aggregates. self.assertNotIn('GROUP BY', sql) def test_explicit_output_field(self): class FuncA(Func): output_field = models.CharField() class FuncB(Func): pass expr = FuncB(FuncA()) self.assertEqual(expr.output_field, FuncA.output_field) def test_outerref_mixed_case_table_name(self): inner = Result.objects.filter(result_time__gte=OuterRef('experiment__assigned')) outer = Result.objects.filter(pk__in=Subquery(inner.values('pk'))) self.assertFalse(outer.exists()) def test_outerref_with_operator(self): inner = Company.objects.filter(num_employees=OuterRef('ceo__salary') + 2) outer = Company.objects.filter(pk__in=Subquery(inner.values('pk'))) self.assertEqual(outer.get().name, 'Test GmbH') def test_annotation_with_outerref(self): gmbh_salary = Company.objects.annotate( max_ceo_salary_raise=Subquery( Company.objects.annotate( salary_raise=OuterRef('num_employees') + F('num_employees'), ).order_by('-salary_raise').values('salary_raise')[:1], output_field=models.IntegerField(), ), ).get(pk=self.gmbh.pk) self.assertEqual(gmbh_salary.max_ceo_salary_raise, 2332) def test_pickle_expression(self): expr = Value(1, output_field=models.IntegerField()) expr.convert_value # populate cached property self.assertEqual(pickle.loads(pickle.dumps(expr)), expr) def test_incorrect_field_in_F_expression(self): with self.assertRaisesMessage(FieldError, "Cannot resolve keyword 'nope' into field."): list(Employee.objects.filter(firstname=F('nope'))) def test_incorrect_joined_field_in_F_expression(self): with self.assertRaisesMessage(FieldError, "Cannot resolve keyword 'nope' into field."): list(Company.objects.filter(ceo__pk=F('point_of_contact__nope'))) def test_exists_in_filter(self): inner = Company.objects.filter(ceo=OuterRef('pk')).values('pk') qs1 = Employee.objects.filter(Exists(inner)) qs2 = Employee.objects.annotate(found=Exists(inner)).filter(found=True) self.assertCountEqual(qs1, qs2) self.assertFalse(Employee.objects.exclude(Exists(inner)).exists()) self.assertCountEqual(qs2, Employee.objects.exclude(~Exists(inner))) def test_subquery_in_filter(self): inner = Company.objects.filter(ceo=OuterRef('pk')).values('based_in_eu') self.assertSequenceEqual( Employee.objects.filter(Subquery(inner)), [self.foobar_ltd.ceo], ) def test_case_in_filter_if_boolean_output_field(self): is_ceo = Company.objects.filter(ceo=OuterRef('pk')) is_poc = Company.objects.filter(point_of_contact=OuterRef('pk')) qs = Employee.objects.filter( Case( When(Exists(is_ceo), then=True), When(Exists(is_poc), then=True), default=False, output_field=models.BooleanField(), ), ) self.assertSequenceEqual(qs, [self.example_inc.ceo, self.foobar_ltd.ceo, self.max]) def test_boolean_expression_combined(self): is_ceo = Company.objects.filter(ceo=OuterRef('pk')) is_poc = Company.objects.filter(point_of_contact=OuterRef('pk')) self.gmbh.point_of_contact = self.max self.gmbh.save() self.assertSequenceEqual( Employee.objects.filter(Exists(is_ceo) | Exists(is_poc)), [self.example_inc.ceo, self.foobar_ltd.ceo, self.max], ) self.assertSequenceEqual( Employee.objects.filter(Exists(is_ceo) & Exists(is_poc)), [self.max], ) self.assertSequenceEqual( Employee.objects.filter(Exists(is_ceo) & Q(salary__gte=30)), [self.max], ) self.assertSequenceEqual( Employee.objects.filter(Exists(is_poc) | Q(salary__lt=15)), [self.example_inc.ceo, self.max], ) class IterableLookupInnerExpressionsTests(TestCase): @classmethod def setUpTestData(cls): ceo = Employee.objects.create(firstname='Just', lastname='Doit', salary=30) # MySQL requires that the values calculated for expressions don't pass # outside of the field's range, so it's inconvenient to use the values # in the more general tests. Company.objects.create(name='5020 Ltd', num_employees=50, num_chairs=20, ceo=ceo) Company.objects.create(name='5040 Ltd', num_employees=50, num_chairs=40, ceo=ceo) Company.objects.create(name='5050 Ltd', num_employees=50, num_chairs=50, ceo=ceo) Company.objects.create(name='5060 Ltd', num_employees=50, num_chairs=60, ceo=ceo) Company.objects.create(name='99300 Ltd', num_employees=99, num_chairs=300, ceo=ceo) def test_in_lookup_allows_F_expressions_and_expressions_for_integers(self): # __in lookups can use F() expressions for integers. queryset = Company.objects.filter(num_employees__in=([F('num_chairs') - 10])) self.assertQuerysetEqual(queryset, ['<Company: 5060 Ltd>'], ordered=False) self.assertQuerysetEqual( Company.objects.filter(num_employees__in=([F('num_chairs') - 10, F('num_chairs') + 10])), ['<Company: 5040 Ltd>', '<Company: 5060 Ltd>'], ordered=False ) self.assertQuerysetEqual( Company.objects.filter( num_employees__in=([F('num_chairs') - 10, F('num_chairs'), F('num_chairs') + 10]) ), ['<Company: 5040 Ltd>', '<Company: 5050 Ltd>', '<Company: 5060 Ltd>'], ordered=False ) def test_expressions_in_lookups_join_choice(self): midpoint = datetime.time(13, 0) t1 = Time.objects.create(time=datetime.time(12, 0)) t2 = Time.objects.create(time=datetime.time(14, 0)) SimulationRun.objects.create(start=t1, end=t2, midpoint=midpoint) SimulationRun.objects.create(start=t1, end=None, midpoint=midpoint) SimulationRun.objects.create(start=None, end=t2, midpoint=midpoint) SimulationRun.objects.create(start=None, end=None, midpoint=midpoint) queryset = SimulationRun.objects.filter(midpoint__range=[F('start__time'), F('end__time')]) self.assertQuerysetEqual( queryset, ['<SimulationRun: 13:00:00 (12:00:00 to 14:00:00)>'], ordered=False ) for alias in queryset.query.alias_map.values(): if isinstance(alias, Join): self.assertEqual(alias.join_type, constants.INNER) queryset = SimulationRun.objects.exclude(midpoint__range=[F('start__time'), F('end__time')]) self.assertQuerysetEqual(queryset, [], ordered=False) for alias in queryset.query.alias_map.values(): if isinstance(alias, Join): self.assertEqual(alias.join_type, constants.LOUTER) def test_range_lookup_allows_F_expressions_and_expressions_for_integers(self): # Range lookups can use F() expressions for integers. Company.objects.filter(num_employees__exact=F("num_chairs")) self.assertQuerysetEqual( Company.objects.filter(num_employees__range=(F('num_chairs'), 100)), ['<Company: 5020 Ltd>', '<Company: 5040 Ltd>', '<Company: 5050 Ltd>'], ordered=False ) self.assertQuerysetEqual( Company.objects.filter(num_employees__range=(F('num_chairs') - 10, F('num_chairs') + 10)), ['<Company: 5040 Ltd>', '<Company: 5050 Ltd>', '<Company: 5060 Ltd>'], ordered=False ) self.assertQuerysetEqual( Company.objects.filter(num_employees__range=(F('num_chairs') - 10, 100)), ['<Company: 5020 Ltd>', '<Company: 5040 Ltd>', '<Company: 5050 Ltd>', '<Company: 5060 Ltd>'], ordered=False ) self.assertQuerysetEqual( Company.objects.filter(num_employees__range=(1, 100)), [ '<Company: 5020 Ltd>', '<Company: 5040 Ltd>', '<Company: 5050 Ltd>', '<Company: 5060 Ltd>', '<Company: 99300 Ltd>', ], ordered=False ) @unittest.skipUnless(connection.vendor == 'sqlite', "This defensive test only works on databases that don't validate parameter types") def test_complex_expressions_do_not_introduce_sql_injection_via_untrusted_string_inclusion(self): """ This tests that SQL injection isn't possible using compilation of expressions in iterable filters, as their compilation happens before the main query compilation. It's limited to SQLite, as PostgreSQL, Oracle and other vendors have defense in depth against this by type checking. Testing against SQLite (the most permissive of the built-in databases) demonstrates that the problem doesn't exist while keeping the test simple. """ queryset = Company.objects.filter(name__in=[F('num_chairs') + '1)) OR ((1==1']) self.assertQuerysetEqual(queryset, [], ordered=False) def test_in_lookup_allows_F_expressions_and_expressions_for_datetimes(self): start = datetime.datetime(2016, 2, 3, 15, 0, 0) end = datetime.datetime(2016, 2, 5, 15, 0, 0) experiment_1 = Experiment.objects.create( name='Integrity testing', assigned=start.date(), start=start, end=end, completed=end.date(), estimated_time=end - start, ) experiment_2 = Experiment.objects.create( name='Taste testing', assigned=start.date(), start=start, end=end, completed=end.date(), estimated_time=end - start, ) Result.objects.create( experiment=experiment_1, result_time=datetime.datetime(2016, 2, 4, 15, 0, 0), ) Result.objects.create( experiment=experiment_1, result_time=datetime.datetime(2016, 3, 10, 2, 0, 0), ) Result.objects.create( experiment=experiment_2, result_time=datetime.datetime(2016, 1, 8, 5, 0, 0), ) within_experiment_time = [F('experiment__start'), F('experiment__end')] queryset = Result.objects.filter(result_time__range=within_experiment_time) self.assertQuerysetEqual(queryset, ["<Result: Result at 2016-02-04 15:00:00>"]) within_experiment_time = [F('experiment__start'), F('experiment__end')] queryset = Result.objects.filter(result_time__range=within_experiment_time) self.assertQuerysetEqual(queryset, ["<Result: Result at 2016-02-04 15:00:00>"]) class FTests(SimpleTestCase): def test_deepcopy(self): f = F("foo") g = deepcopy(f) self.assertEqual(f.name, g.name) def test_deconstruct(self): f = F('name') path, args, kwargs = f.deconstruct() self.assertEqual(path, 'django.db.models.expressions.F') self.assertEqual(args, (f.name,)) self.assertEqual(kwargs, {}) def test_equal(self): f = F('name') same_f = F('name') other_f = F('username') self.assertEqual(f, same_f) self.assertNotEqual(f, other_f) def test_hash(self): d = {F('name'): 'Bob'} self.assertIn(F('name'), d) self.assertEqual(d[F('name')], 'Bob') def test_not_equal_Value(self): f = F('name') value = Value('name') self.assertNotEqual(f, value) self.assertNotEqual(value, f) class ExpressionsTests(TestCase): def test_F_reuse(self): f = F('id') n = Number.objects.create(integer=-1) c = Company.objects.create( name="Example Inc.", num_employees=2300, num_chairs=5, ceo=Employee.objects.create(firstname="Joe", lastname="Smith") ) c_qs = Company.objects.filter(id=f) self.assertEqual(c_qs.get(), c) # Reuse the same F-object for another queryset n_qs = Number.objects.filter(id=f) self.assertEqual(n_qs.get(), n) # The original query still works correctly self.assertEqual(c_qs.get(), c) def test_patterns_escape(self): r""" Special characters (e.g. %, _ and \) stored in database are properly escaped when using a pattern lookup with an expression refs #16731 """ Employee.objects.bulk_create([ Employee(firstname="%Joh\\nny", lastname="%Joh\\n"), Employee(firstname="Johnny", lastname="%John"), Employee(firstname="Jean-Claude", lastname="Claud_"), Employee(firstname="Jean-Claude", lastname="Claude"), Employee(firstname="Jean-Claude", lastname="Claude%"), Employee(firstname="Johnny", lastname="Joh\\n"), Employee(firstname="Johnny", lastname="John"), Employee(firstname="Johnny", lastname="_ohn"), ]) self.assertQuerysetEqual( Employee.objects.filter(firstname__contains=F('lastname')), ["<Employee: %Joh\\nny %Joh\\n>", "<Employee: Jean-Claude Claude>", "<Employee: Johnny John>"], ordered=False, ) self.assertQuerysetEqual( Employee.objects.filter(firstname__startswith=F('lastname')), ["<Employee: %Joh\\nny %Joh\\n>", "<Employee: Johnny John>"], ordered=False, ) self.assertQuerysetEqual( Employee.objects.filter(firstname__endswith=F('lastname')), ["<Employee: Jean-Claude Claude>"], ordered=False, ) def test_insensitive_patterns_escape(self): r""" Special characters (e.g. %, _ and \) stored in database are properly escaped when using a case insensitive pattern lookup with an expression -- refs #16731 """ Employee.objects.bulk_create([ Employee(firstname="%Joh\\nny", lastname="%joh\\n"), Employee(firstname="Johnny", lastname="%john"), Employee(firstname="Jean-Claude", lastname="claud_"), Employee(firstname="Jean-Claude", lastname="claude"), Employee(firstname="Jean-Claude", lastname="claude%"), Employee(firstname="Johnny", lastname="joh\\n"), Employee(firstname="Johnny", lastname="john"), Employee(firstname="Johnny", lastname="_ohn"), ]) self.assertQuerysetEqual( Employee.objects.filter(firstname__icontains=F('lastname')), ["<Employee: %Joh\\nny %joh\\n>", "<Employee: Jean-Claude claude>", "<Employee: Johnny john>"], ordered=False, ) self.assertQuerysetEqual( Employee.objects.filter(firstname__istartswith=F('lastname')), ["<Employee: %Joh\\nny %joh\\n>", "<Employee: Johnny john>"], ordered=False, ) self.assertQuerysetEqual( Employee.objects.filter(firstname__iendswith=F('lastname')), ["<Employee: Jean-Claude claude>"], ordered=False, ) @isolate_apps('expressions') class SimpleExpressionTests(SimpleTestCase): def test_equal(self): self.assertEqual(Expression(), Expression()) self.assertEqual( Expression(models.IntegerField()), Expression(output_field=models.IntegerField()) ) self.assertEqual(Expression(models.IntegerField()), mock.ANY) self.assertNotEqual( Expression(models.IntegerField()), Expression(models.CharField()) ) class TestModel(models.Model): field = models.IntegerField() other_field = models.IntegerField() self.assertNotEqual( Expression(TestModel._meta.get_field('field')), Expression(TestModel._meta.get_field('other_field')), ) def test_hash(self): self.assertEqual(hash(Expression()), hash(Expression())) self.assertEqual( hash(Expression(models.IntegerField())), hash(Expression(output_field=models.IntegerField())) ) self.assertNotEqual( hash(Expression(models.IntegerField())), hash(Expression(models.CharField())), ) class TestModel(models.Model): field = models.IntegerField() other_field = models.IntegerField() self.assertNotEqual( hash(Expression(TestModel._meta.get_field('field'))), hash(Expression(TestModel._meta.get_field('other_field'))), ) class ExpressionsNumericTests(TestCase): @classmethod def setUpTestData(cls): Number(integer=-1).save() Number(integer=42).save() Number(integer=1337).save() Number.objects.update(float=F('integer')) def test_fill_with_value_from_same_object(self): """ We can fill a value in all objects with an other value of the same object. """ self.assertQuerysetEqual( Number.objects.all(), ['<Number: -1, -1.000>', '<Number: 42, 42.000>', '<Number: 1337, 1337.000>'], ordered=False ) def test_increment_value(self): """ We can increment a value of all objects in a query set. """ self.assertEqual(Number.objects.filter(integer__gt=0).update(integer=F('integer') + 1), 2) self.assertQuerysetEqual( Number.objects.all(), ['<Number: -1, -1.000>', '<Number: 43, 42.000>', '<Number: 1338, 1337.000>'], ordered=False ) def test_filter_not_equals_other_field(self): """ We can filter for objects, where a value is not equals the value of an other field. """ self.assertEqual(Number.objects.filter(integer__gt=0).update(integer=F('integer') + 1), 2) self.assertQuerysetEqual( Number.objects.exclude(float=F('integer')), ['<Number: 43, 42.000>', '<Number: 1338, 1337.000>'], ordered=False ) def test_complex_expressions(self): """ Complex expressions of different connection types are possible. """ n = Number.objects.create(integer=10, float=123.45) self.assertEqual(Number.objects.filter(pk=n.pk).update( float=F('integer') + F('float') * 2), 1) self.assertEqual(Number.objects.get(pk=n.pk).integer, 10) self.assertEqual(Number.objects.get(pk=n.pk).float, Approximate(256.900, places=3)) class ExpressionOperatorTests(TestCase): @classmethod def setUpTestData(cls): cls.n = Number.objects.create(integer=42, float=15.5) cls.n1 = Number.objects.create(integer=-42, float=-15.5) def test_lefthand_addition(self): # LH Addition of floats and integers Number.objects.filter(pk=self.n.pk).update( integer=F('integer') + 15, float=F('float') + 42.7 ) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 57) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(58.200, places=3)) def test_lefthand_subtraction(self): # LH Subtraction of floats and integers Number.objects.filter(pk=self.n.pk).update(integer=F('integer') - 15, float=F('float') - 42.7) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 27) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(-27.200, places=3)) def test_lefthand_multiplication(self): # Multiplication of floats and integers Number.objects.filter(pk=self.n.pk).update(integer=F('integer') * 15, float=F('float') * 42.7) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 630) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(661.850, places=3)) def test_lefthand_division(self): # LH Division of floats and integers Number.objects.filter(pk=self.n.pk).update(integer=F('integer') / 2, float=F('float') / 42.7) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 21) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(0.363, places=3)) def test_lefthand_modulo(self): # LH Modulo arithmetic on integers Number.objects.filter(pk=self.n.pk).update(integer=F('integer') % 20) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 2) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) def test_lefthand_bitwise_and(self): # LH Bitwise ands on integers Number.objects.filter(pk=self.n.pk).update(integer=F('integer').bitand(56)) Number.objects.filter(pk=self.n1.pk).update(integer=F('integer').bitand(-56)) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 40) self.assertEqual(Number.objects.get(pk=self.n1.pk).integer, -64) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) def test_lefthand_bitwise_left_shift_operator(self): Number.objects.update(integer=F('integer').bitleftshift(2)) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 168) self.assertEqual(Number.objects.get(pk=self.n1.pk).integer, -168) def test_lefthand_bitwise_right_shift_operator(self): Number.objects.update(integer=F('integer').bitrightshift(2)) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 10) self.assertEqual(Number.objects.get(pk=self.n1.pk).integer, -11) def test_lefthand_bitwise_or(self): # LH Bitwise or on integers Number.objects.update(integer=F('integer').bitor(48)) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 58) self.assertEqual(Number.objects.get(pk=self.n1.pk).integer, -10) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) def test_lefthand_power(self): # LH Power arithmetic operation on floats and integers Number.objects.filter(pk=self.n.pk).update(integer=F('integer') ** 2, float=F('float') ** 1.5) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 1764) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(61.02, places=2)) def test_right_hand_addition(self): # Right hand operators Number.objects.filter(pk=self.n.pk).update(integer=15 + F('integer'), float=42.7 + F('float')) # RH Addition of floats and integers self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 57) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(58.200, places=3)) def test_right_hand_subtraction(self): Number.objects.filter(pk=self.n.pk).update(integer=15 - F('integer'), float=42.7 - F('float')) # RH Subtraction of floats and integers self.assertEqual(Number.objects.get(pk=self.n.pk).integer, -27) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(27.200, places=3)) def test_right_hand_multiplication(self): # RH Multiplication of floats and integers Number.objects.filter(pk=self.n.pk).update(integer=15 * F('integer'), float=42.7 * F('float')) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 630) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(661.850, places=3)) def test_right_hand_division(self): # RH Division of floats and integers Number.objects.filter(pk=self.n.pk).update(integer=640 / F('integer'), float=42.7 / F('float')) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 15) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(2.755, places=3)) def test_right_hand_modulo(self): # RH Modulo arithmetic on integers Number.objects.filter(pk=self.n.pk).update(integer=69 % F('integer')) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 27) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) def test_righthand_power(self): # RH Power arithmetic operation on floats and integers Number.objects.filter(pk=self.n.pk).update(integer=2 ** F('integer'), float=1.5 ** F('float')) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 4398046511104) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(536.308, places=3)) class FTimeDeltaTests(TestCase): @classmethod def setUpTestData(cls): cls.sday = sday = datetime.date(2010, 6, 25) cls.stime = stime = datetime.datetime(2010, 6, 25, 12, 15, 30, 747000) midnight = datetime.time(0) delta0 = datetime.timedelta(0) delta1 = datetime.timedelta(microseconds=253000) delta2 = datetime.timedelta(seconds=44) delta3 = datetime.timedelta(hours=21, minutes=8) delta4 = datetime.timedelta(days=10) delta5 = datetime.timedelta(days=90) # Test data is set so that deltas and delays will be # strictly increasing. cls.deltas = [] cls.delays = [] cls.days_long = [] # e0: started same day as assigned, zero duration end = stime + delta0 e0 = Experiment.objects.create( name='e0', assigned=sday, start=stime, end=end, completed=end.date(), estimated_time=delta0, ) cls.deltas.append(delta0) cls.delays.append(e0.start - datetime.datetime.combine(e0.assigned, midnight)) cls.days_long.append(e0.completed - e0.assigned) # e1: started one day after assigned, tiny duration, data # set so that end time has no fractional seconds, which # tests an edge case on sqlite. delay = datetime.timedelta(1) end = stime + delay + delta1 e1 = Experiment.objects.create( name='e1', assigned=sday, start=stime + delay, end=end, completed=end.date(), estimated_time=delta1, ) cls.deltas.append(delta1) cls.delays.append(e1.start - datetime.datetime.combine(e1.assigned, midnight)) cls.days_long.append(e1.completed - e1.assigned) # e2: started three days after assigned, small duration end = stime + delta2 e2 = Experiment.objects.create( name='e2', assigned=sday - datetime.timedelta(3), start=stime, end=end, completed=end.date(), estimated_time=datetime.timedelta(hours=1), ) cls.deltas.append(delta2) cls.delays.append(e2.start - datetime.datetime.combine(e2.assigned, midnight)) cls.days_long.append(e2.completed - e2.assigned) # e3: started four days after assigned, medium duration delay = datetime.timedelta(4) end = stime + delay + delta3 e3 = Experiment.objects.create( name='e3', assigned=sday, start=stime + delay, end=end, completed=end.date(), estimated_time=delta3, ) cls.deltas.append(delta3) cls.delays.append(e3.start - datetime.datetime.combine(e3.assigned, midnight)) cls.days_long.append(e3.completed - e3.assigned) # e4: started 10 days after assignment, long duration end = stime + delta4 e4 = Experiment.objects.create( name='e4', assigned=sday - datetime.timedelta(10), start=stime, end=end, completed=end.date(), estimated_time=delta4 - datetime.timedelta(1), ) cls.deltas.append(delta4) cls.delays.append(e4.start - datetime.datetime.combine(e4.assigned, midnight)) cls.days_long.append(e4.completed - e4.assigned) # e5: started a month after assignment, very long duration delay = datetime.timedelta(30) end = stime + delay + delta5 e5 = Experiment.objects.create( name='e5', assigned=sday, start=stime + delay, end=end, completed=end.date(), estimated_time=delta5, ) cls.deltas.append(delta5) cls.delays.append(e5.start - datetime.datetime.combine(e5.assigned, midnight)) cls.days_long.append(e5.completed - e5.assigned) cls.expnames = [e.name for e in Experiment.objects.all()] def test_multiple_query_compilation(self): # Ticket #21643 queryset = Experiment.objects.filter(end__lt=F('start') + datetime.timedelta(hours=1)) q1 = str(queryset.query) q2 = str(queryset.query) self.assertEqual(q1, q2) def test_query_clone(self): # Ticket #21643 - Crash when compiling query more than once qs = Experiment.objects.filter(end__lt=F('start') + datetime.timedelta(hours=1)) qs2 = qs.all() list(qs) list(qs2) # Intentionally no assert def test_delta_add(self): for i, delta in enumerate(self.deltas): test_set = [e.name for e in Experiment.objects.filter(end__lt=F('start') + delta)] self.assertEqual(test_set, self.expnames[:i]) test_set = [e.name for e in Experiment.objects.filter(end__lt=delta + F('start'))] self.assertEqual(test_set, self.expnames[:i]) test_set = [e.name for e in Experiment.objects.filter(end__lte=F('start') + delta)] self.assertEqual(test_set, self.expnames[:i + 1]) def test_delta_subtract(self): for i, delta in enumerate(self.deltas): test_set = [e.name for e in Experiment.objects.filter(start__gt=F('end') - delta)] self.assertEqual(test_set, self.expnames[:i]) test_set = [e.name for e in Experiment.objects.filter(start__gte=F('end') - delta)] self.assertEqual(test_set, self.expnames[:i + 1]) def test_exclude(self): for i, delta in enumerate(self.deltas): test_set = [e.name for e in Experiment.objects.exclude(end__lt=F('start') + delta)] self.assertEqual(test_set, self.expnames[i:]) test_set = [e.name for e in Experiment.objects.exclude(end__lte=F('start') + delta)] self.assertEqual(test_set, self.expnames[i + 1:]) def test_date_comparison(self): for i, days in enumerate(self.days_long): test_set = [e.name for e in Experiment.objects.filter(completed__lt=F('assigned') + days)] self.assertEqual(test_set, self.expnames[:i]) test_set = [e.name for e in Experiment.objects.filter(completed__lte=F('assigned') + days)] self.assertEqual(test_set, self.expnames[:i + 1]) @skipUnlessDBFeature("supports_mixed_date_datetime_comparisons") def test_mixed_comparisons1(self): for i, delay in enumerate(self.delays): test_set = [e.name for e in Experiment.objects.filter(assigned__gt=F('start') - delay)] self.assertEqual(test_set, self.expnames[:i]) test_set = [e.name for e in Experiment.objects.filter(assigned__gte=F('start') - delay)] self.assertEqual(test_set, self.expnames[:i + 1]) def test_mixed_comparisons2(self): for i, delay in enumerate(self.delays): delay = datetime.timedelta(delay.days) test_set = [e.name for e in Experiment.objects.filter(start__lt=F('assigned') + delay)] self.assertEqual(test_set, self.expnames[:i]) test_set = [ e.name for e in Experiment.objects.filter(start__lte=F('assigned') + delay + datetime.timedelta(1)) ] self.assertEqual(test_set, self.expnames[:i + 1]) def test_delta_update(self): for delta in self.deltas: exps = Experiment.objects.all() expected_durations = [e.duration() for e in exps] expected_starts = [e.start + delta for e in exps] expected_ends = [e.end + delta for e in exps] Experiment.objects.update(start=F('start') + delta, end=F('end') + delta) exps = Experiment.objects.all() new_starts = [e.start for e in exps] new_ends = [e.end for e in exps] new_durations = [e.duration() for e in exps] self.assertEqual(expected_starts, new_starts) self.assertEqual(expected_ends, new_ends) self.assertEqual(expected_durations, new_durations) def test_invalid_operator(self): with self.assertRaises(DatabaseError): list(Experiment.objects.filter(start=F('start') * datetime.timedelta(0))) def test_durationfield_add(self): zeros = [e.name for e in Experiment.objects.filter(start=F('start') + F('estimated_time'))] self.assertEqual(zeros, ['e0']) end_less = [e.name for e in Experiment.objects.filter(end__lt=F('start') + F('estimated_time'))] self.assertEqual(end_less, ['e2']) delta_math = [ e.name for e in Experiment.objects.filter(end__gte=F('start') + F('estimated_time') + datetime.timedelta(hours=1)) ] self.assertEqual(delta_math, ['e4']) queryset = Experiment.objects.annotate(shifted=ExpressionWrapper( F('start') + Value(None, output_field=models.DurationField()), output_field=models.DateTimeField(), )) self.assertIsNone(queryset.first().shifted) @skipUnlessDBFeature('supports_temporal_subtraction') def test_date_subtraction(self): queryset = Experiment.objects.annotate( completion_duration=ExpressionWrapper( F('completed') - F('assigned'), output_field=models.DurationField() ) ) at_least_5_days = {e.name for e in queryset.filter(completion_duration__gte=datetime.timedelta(days=5))} self.assertEqual(at_least_5_days, {'e3', 'e4', 'e5'}) at_least_120_days = {e.name for e in queryset.filter(completion_duration__gte=datetime.timedelta(days=120))} self.assertEqual(at_least_120_days, {'e5'}) less_than_5_days = {e.name for e in queryset.filter(completion_duration__lt=datetime.timedelta(days=5))} self.assertEqual(less_than_5_days, {'e0', 'e1', 'e2'}) queryset = Experiment.objects.annotate(difference=ExpressionWrapper( F('completed') - Value(None, output_field=models.DateField()), output_field=models.DurationField(), )) self.assertIsNone(queryset.first().difference) queryset = Experiment.objects.annotate(shifted=ExpressionWrapper( F('completed') - Value(None, output_field=models.DurationField()), output_field=models.DateField(), )) self.assertIsNone(queryset.first().shifted) @skipUnlessDBFeature('supports_temporal_subtraction') def test_time_subtraction(self): Time.objects.create(time=datetime.time(12, 30, 15, 2345)) queryset = Time.objects.annotate( difference=ExpressionWrapper( F('time') - Value(datetime.time(11, 15, 0), output_field=models.TimeField()), output_field=models.DurationField(), ) ) self.assertEqual( queryset.get().difference, datetime.timedelta(hours=1, minutes=15, seconds=15, microseconds=2345) ) queryset = Time.objects.annotate(difference=ExpressionWrapper( F('time') - Value(None, output_field=models.TimeField()), output_field=models.DurationField(), )) self.assertIsNone(queryset.first().difference) queryset = Time.objects.annotate(shifted=ExpressionWrapper( F('time') - Value(None, output_field=models.DurationField()), output_field=models.TimeField(), )) self.assertIsNone(queryset.first().shifted) @skipUnlessDBFeature('supports_temporal_subtraction') def test_datetime_subtraction(self): under_estimate = [ e.name for e in Experiment.objects.filter(estimated_time__gt=F('end') - F('start')) ] self.assertEqual(under_estimate, ['e2']) over_estimate = [ e.name for e in Experiment.objects.filter(estimated_time__lt=F('end') - F('start')) ] self.assertEqual(over_estimate, ['e4']) queryset = Experiment.objects.annotate(difference=ExpressionWrapper( F('start') - Value(None, output_field=models.DateTimeField()), output_field=models.DurationField(), )) self.assertIsNone(queryset.first().difference) queryset = Experiment.objects.annotate(shifted=ExpressionWrapper( F('start') - Value(None, output_field=models.DurationField()), output_field=models.DateTimeField(), )) self.assertIsNone(queryset.first().shifted) @skipUnlessDBFeature('supports_temporal_subtraction') def test_datetime_subtraction_microseconds(self): delta = datetime.timedelta(microseconds=8999999999999999) Experiment.objects.update(end=F('start') + delta) qs = Experiment.objects.annotate( delta=ExpressionWrapper(F('end') - F('start'), output_field=models.DurationField()) ) for e in qs: self.assertEqual(e.delta, delta) def test_duration_with_datetime(self): # Exclude e1 which has very high precision so we can test this on all # backends regardless of whether or not it supports # microsecond_precision. over_estimate = Experiment.objects.exclude(name='e1').filter( completed__gt=self.stime + F('estimated_time'), ).order_by('name') self.assertQuerysetEqual(over_estimate, ['e3', 'e4', 'e5'], lambda e: e.name) def test_duration_with_datetime_microseconds(self): delta = datetime.timedelta(microseconds=8999999999999999) qs = Experiment.objects.annotate(dt=ExpressionWrapper( F('start') + delta, output_field=models.DateTimeField(), )) for e in qs: self.assertEqual(e.dt, e.start + delta) def test_date_minus_duration(self): more_than_4_days = Experiment.objects.filter( assigned__lt=F('completed') - Value(datetime.timedelta(days=4), output_field=models.DurationField()) ) self.assertQuerysetEqual(more_than_4_days, ['e3', 'e4', 'e5'], lambda e: e.name) def test_negative_timedelta_update(self): # subtract 30 seconds, 30 minutes, 2 hours and 2 days experiments = Experiment.objects.filter(name='e0').annotate( start_sub_seconds=F('start') + datetime.timedelta(seconds=-30), ).annotate( start_sub_minutes=F('start_sub_seconds') + datetime.timedelta(minutes=-30), ).annotate( start_sub_hours=F('start_sub_minutes') + datetime.timedelta(hours=-2), ).annotate( new_start=F('start_sub_hours') + datetime.timedelta(days=-2), ) expected_start = datetime.datetime(2010, 6, 23, 9, 45, 0) # subtract 30 microseconds experiments = experiments.annotate(new_start=F('new_start') + datetime.timedelta(microseconds=-30)) expected_start += datetime.timedelta(microseconds=+746970) experiments.update(start=F('new_start')) e0 = Experiment.objects.get(name='e0') self.assertEqual(e0.start, expected_start) class ValueTests(TestCase): def test_update_TimeField_using_Value(self): Time.objects.create() Time.objects.update(time=Value(datetime.time(1), output_field=TimeField())) self.assertEqual(Time.objects.get().time, datetime.time(1)) def test_update_UUIDField_using_Value(self): UUID.objects.create() UUID.objects.update(uuid=Value(uuid.UUID('12345678901234567890123456789012'), output_field=UUIDField())) self.assertEqual(UUID.objects.get().uuid, uuid.UUID('12345678901234567890123456789012')) def test_deconstruct(self): value = Value('name') path, args, kwargs = value.deconstruct() self.assertEqual(path, 'django.db.models.expressions.Value') self.assertEqual(args, (value.value,)) self.assertEqual(kwargs, {}) def test_deconstruct_output_field(self): value = Value('name', output_field=CharField()) path, args, kwargs = value.deconstruct() self.assertEqual(path, 'django.db.models.expressions.Value') self.assertEqual(args, (value.value,)) self.assertEqual(len(kwargs), 1) self.assertEqual(kwargs['output_field'].deconstruct(), CharField().deconstruct()) def test_equal(self): value = Value('name') self.assertEqual(value, Value('name')) self.assertNotEqual(value, Value('username')) def test_hash(self): d = {Value('name'): 'Bob'} self.assertIn(Value('name'), d) self.assertEqual(d[Value('name')], 'Bob') def test_equal_output_field(self): value = Value('name', output_field=CharField()) same_value = Value('name', output_field=CharField()) other_value = Value('name', output_field=TimeField()) no_output_field = Value('name') self.assertEqual(value, same_value) self.assertNotEqual(value, other_value) self.assertNotEqual(value, no_output_field) def test_raise_empty_expressionlist(self): msg = 'ExpressionList requires at least one expression' with self.assertRaisesMessage(ValueError, msg): ExpressionList() class FieldTransformTests(TestCase): @classmethod def setUpTestData(cls): cls.sday = sday = datetime.date(2010, 6, 25) cls.stime = stime = datetime.datetime(2010, 6, 25, 12, 15, 30, 747000) cls.ex1 = Experiment.objects.create( name='Experiment 1', assigned=sday, completed=sday + datetime.timedelta(2), estimated_time=datetime.timedelta(2), start=stime, end=stime + datetime.timedelta(2), ) def test_month_aggregation(self): self.assertEqual( Experiment.objects.aggregate(month_count=Count('assigned__month')), {'month_count': 1} ) def test_transform_in_values(self): self.assertQuerysetEqual( Experiment.objects.values('assigned__month'), ["{'assigned__month': 6}"] ) def test_multiple_transforms_in_values(self): self.assertQuerysetEqual( Experiment.objects.values('end__date__month'), ["{'end__date__month': 6}"] ) class ReprTests(SimpleTestCase): def test_expressions(self): self.assertEqual( repr(Case(When(a=1))), "<Case: CASE WHEN <Q: (AND: ('a', 1))> THEN Value(None), ELSE Value(None)>" ) self.assertEqual( repr(When(Q(age__gte=18), then=Value('legal'))), "<When: WHEN <Q: (AND: ('age__gte', 18))> THEN Value(legal)>" ) self.assertEqual(repr(Col('alias', 'field')), "Col(alias, field)") self.assertEqual(repr(F('published')), "F(published)") self.assertEqual(repr(F('cost') + F('tax')), "<CombinedExpression: F(cost) + F(tax)>") self.assertEqual( repr(ExpressionWrapper(F('cost') + F('tax'), models.IntegerField())), "ExpressionWrapper(F(cost) + F(tax))" ) self.assertEqual(repr(Func('published', function='TO_CHAR')), "Func(F(published), function=TO_CHAR)") self.assertEqual(repr(OrderBy(Value(1))), 'OrderBy(Value(1), descending=False)') self.assertEqual(repr(Random()), "Random()") self.assertEqual(repr(RawSQL('table.col', [])), "RawSQL(table.col, [])") self.assertEqual(repr(Ref('sum_cost', Sum('cost'))), "Ref(sum_cost, Sum(F(cost)))") self.assertEqual(repr(Value(1)), "Value(1)") self.assertEqual( repr(ExpressionList(F('col'), F('anothercol'))), 'ExpressionList(F(col), F(anothercol))' ) self.assertEqual( repr(ExpressionList(OrderBy(F('col'), descending=False))), 'ExpressionList(OrderBy(F(col), descending=False))' ) def test_functions(self): self.assertEqual(repr(Coalesce('a', 'b')), "Coalesce(F(a), F(b))") self.assertEqual(repr(Concat('a', 'b')), "Concat(ConcatPair(F(a), F(b)))") self.assertEqual(repr(Length('a')), "Length(F(a))") self.assertEqual(repr(Lower('a')), "Lower(F(a))") self.assertEqual(repr(Substr('a', 1, 3)), "Substr(F(a), Value(1), Value(3))") self.assertEqual(repr(Upper('a')), "Upper(F(a))") def test_aggregates(self): self.assertEqual(repr(Avg('a')), "Avg(F(a))") self.assertEqual(repr(Count('a')), "Count(F(a))") self.assertEqual(repr(Count('*')), "Count('*')") self.assertEqual(repr(Max('a')), "Max(F(a))") self.assertEqual(repr(Min('a')), "Min(F(a))") self.assertEqual(repr(StdDev('a')), "StdDev(F(a), sample=False)") self.assertEqual(repr(Sum('a')), "Sum(F(a))") self.assertEqual(repr(Variance('a', sample=True)), "Variance(F(a), sample=True)") def test_distinct_aggregates(self): self.assertEqual(repr(Count('a', distinct=True)), "Count(F(a), distinct=True)") self.assertEqual(repr(Count('*', distinct=True)), "Count('*', distinct=True)") def test_filtered_aggregates(self): filter = Q(a=1) self.assertEqual(repr(Avg('a', filter=filter)), "Avg(F(a), filter=(AND: ('a', 1)))") self.assertEqual(repr(Count('a', filter=filter)), "Count(F(a), filter=(AND: ('a', 1)))") self.assertEqual(repr(Max('a', filter=filter)), "Max(F(a), filter=(AND: ('a', 1)))") self.assertEqual(repr(Min('a', filter=filter)), "Min(F(a), filter=(AND: ('a', 1)))") self.assertEqual(repr(StdDev('a', filter=filter)), "StdDev(F(a), filter=(AND: ('a', 1)), sample=False)") self.assertEqual(repr(Sum('a', filter=filter)), "Sum(F(a), filter=(AND: ('a', 1)))") self.assertEqual( repr(Variance('a', sample=True, filter=filter)), "Variance(F(a), filter=(AND: ('a', 1)), sample=True)" ) self.assertEqual( repr(Count('a', filter=filter, distinct=True)), "Count(F(a), distinct=True, filter=(AND: ('a', 1)))" ) class CombinableTests(SimpleTestCase): bitwise_msg = 'Use .bitand() and .bitor() for bitwise logical operations.' def test_negation(self): c = Combinable() self.assertEqual(-c, c * -1) def test_and(self): with self.assertRaisesMessage(NotImplementedError, self.bitwise_msg): Combinable() & Combinable() def test_or(self): with self.assertRaisesMessage(NotImplementedError, self.bitwise_msg): Combinable() | Combinable() def test_reversed_and(self): with self.assertRaisesMessage(NotImplementedError, self.bitwise_msg): object() & Combinable() def test_reversed_or(self): with self.assertRaisesMessage(NotImplementedError, self.bitwise_msg): object() | Combinable()
98c21eb0ee4fc2ca7454fe8fbac4b83a4e1395be16df0dc25a5331790043e0d3
""" Tests for F() query expression syntax. """ import uuid from django.db import models class Employee(models.Model): firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) salary = models.IntegerField(blank=True, null=True) def __str__(self): return '%s %s' % (self.firstname, self.lastname) class RemoteEmployee(Employee): adjusted_salary = models.IntegerField() class Company(models.Model): name = models.CharField(max_length=100) num_employees = models.PositiveIntegerField() num_chairs = models.PositiveIntegerField() ceo = models.ForeignKey( Employee, models.CASCADE, related_name='company_ceo_set', ) point_of_contact = models.ForeignKey( Employee, models.SET_NULL, related_name='company_point_of_contact_set', null=True, ) based_in_eu = models.BooleanField(default=False) def __str__(self): return self.name class Number(models.Model): integer = models.BigIntegerField(db_column='the_integer') float = models.FloatField(null=True, db_column='the_float') def __str__(self): return '%i, %.3f' % (self.integer, self.float) class Experiment(models.Model): name = models.CharField(max_length=24) assigned = models.DateField() completed = models.DateField() estimated_time = models.DurationField() start = models.DateTimeField() end = models.DateTimeField() class Meta: db_table = 'expressions_ExPeRiMeNt' ordering = ('name',) def duration(self): return self.end - self.start class Result(models.Model): experiment = models.ForeignKey(Experiment, models.CASCADE) result_time = models.DateTimeField() def __str__(self): return "Result at %s" % self.result_time class Time(models.Model): time = models.TimeField(null=True) def __str__(self): return "%s" % self.time class SimulationRun(models.Model): start = models.ForeignKey(Time, models.CASCADE, null=True, related_name='+') end = models.ForeignKey(Time, models.CASCADE, null=True, related_name='+') midpoint = models.TimeField() def __str__(self): return "%s (%s to %s)" % (self.midpoint, self.start, self.end) class UUIDPK(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) class UUID(models.Model): uuid = models.UUIDField(null=True) uuid_fk = models.ForeignKey(UUIDPK, models.CASCADE, null=True) def __str__(self): return "%s" % self.uuid
d6b3b36988bfbd135ede0a2e002fa995e3c93aeaeb961a7eb4fc921b2179143a
import io from django.core.management import call_command from django.test import TestCase class CoreCommandsNoOutputTests(TestCase): available_apps = ['empty_models'] def test_sqlflush_no_tables(self): err = io.StringIO() call_command('sqlflush', stderr=err) self.assertEqual(err.getvalue(), 'No tables found.\n') def test_sqlsequencereset_no_sequences(self): err = io.StringIO() call_command('sqlsequencereset', 'empty_models', stderr=err) self.assertEqual(err.getvalue(), 'No sequences found.\n')
a48d9e3b2e3442f3af371bba11911dbe319e9dc374b6bac4fd4bb1f958a7c769
import datetime import re import sys from contextlib import contextmanager from unittest import SkipTest, skipIf from xml.dom.minidom import parseString import pytz from django.contrib.auth.models import User from django.core import serializers from django.core.exceptions import ImproperlyConfigured from django.db import connection, connections from django.db.models import F, Max, Min from django.http import HttpRequest from django.template import ( Context, RequestContext, Template, TemplateSyntaxError, context_processors, ) from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import requires_tz_support from django.urls import reverse from django.utils import timezone from django.utils.timezone import timedelta from .forms import ( EventForm, EventLocalizedForm, EventLocalizedModelForm, EventModelForm, EventSplitForm, ) from .models import ( AllDayEvent, Event, MaybeEvent, Session, SessionEvent, Timestamp, ) # These tests use the EAT (Eastern Africa Time) and ICT (Indochina Time) # who don't have Daylight Saving Time, so we can represent them easily # with fixed offset timezones and use them directly as tzinfo in the # constructors. # settings.TIME_ZONE is forced to EAT. Most tests use a variant of # datetime.datetime(2011, 9, 1, 13, 20, 30), which translates to # 10:20:30 in UTC and 17:20:30 in ICT. UTC = timezone.utc EAT = timezone.get_fixed_timezone(180) # Africa/Nairobi ICT = timezone.get_fixed_timezone(420) # Asia/Bangkok @contextmanager def override_database_connection_timezone(timezone): try: orig_timezone = connection.settings_dict['TIME_ZONE'] connection.settings_dict['TIME_ZONE'] = timezone # Clear cached properties, after first accessing them to ensure they exist. connection.timezone del connection.timezone connection.timezone_name del connection.timezone_name yield finally: connection.settings_dict['TIME_ZONE'] = orig_timezone # Clear cached properties, after first accessing them to ensure they exist. connection.timezone del connection.timezone connection.timezone_name del connection.timezone_name @override_settings(TIME_ZONE='Africa/Nairobi', USE_TZ=False) class LegacyDatabaseTests(TestCase): def test_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_naive_datetime_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) @skipUnlessDBFeature('supports_timezones') def test_aware_datetime_in_local_timezone(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertIsNone(event.dt.tzinfo) # interpret the naive datetime in local time to get the correct value self.assertEqual(event.dt.replace(tzinfo=EAT), dt) @skipUnlessDBFeature('supports_timezones') def test_aware_datetime_in_local_timezone_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060, tzinfo=EAT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertIsNone(event.dt.tzinfo) # interpret the naive datetime in local time to get the correct value self.assertEqual(event.dt.replace(tzinfo=EAT), dt) @skipUnlessDBFeature('supports_timezones') def test_aware_datetime_in_utc(self): dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) Event.objects.create(dt=dt) event = Event.objects.get() self.assertIsNone(event.dt.tzinfo) # interpret the naive datetime in local time to get the correct value self.assertEqual(event.dt.replace(tzinfo=EAT), dt) @skipUnlessDBFeature('supports_timezones') def test_aware_datetime_in_other_timezone(self): dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertIsNone(event.dt.tzinfo) # interpret the naive datetime in local time to get the correct value self.assertEqual(event.dt.replace(tzinfo=EAT), dt) @skipIfDBFeature('supports_timezones') def test_aware_datetime_unsupported(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) msg = 'backend does not support timezone-aware datetimes when USE_TZ is False.' with self.assertRaisesMessage(ValueError, msg): Event.objects.create(dt=dt) def test_auto_now_and_auto_now_add(self): now = datetime.datetime.now() past = now - datetime.timedelta(seconds=2) future = now + datetime.timedelta(seconds=2) Timestamp.objects.create() ts = Timestamp.objects.get() self.assertLess(past, ts.created) self.assertLess(past, ts.updated) self.assertGreater(future, ts.updated) self.assertGreater(future, ts.updated) def test_query_filter(self): dt1 = datetime.datetime(2011, 9, 1, 12, 20, 30) dt2 = datetime.datetime(2011, 9, 1, 14, 20, 30) Event.objects.create(dt=dt1) Event.objects.create(dt=dt2) self.assertEqual(Event.objects.filter(dt__gte=dt1).count(), 2) self.assertEqual(Event.objects.filter(dt__gt=dt1).count(), 1) self.assertEqual(Event.objects.filter(dt__gte=dt2).count(), 1) self.assertEqual(Event.objects.filter(dt__gt=dt2).count(), 0) def test_query_datetime_lookups(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0)) self.assertEqual(Event.objects.filter(dt__year=2011).count(), 2) self.assertEqual(Event.objects.filter(dt__month=1).count(), 2) self.assertEqual(Event.objects.filter(dt__day=1).count(), 2) self.assertEqual(Event.objects.filter(dt__week_day=7).count(), 2) self.assertEqual(Event.objects.filter(dt__iso_week_day=6).count(), 2) self.assertEqual(Event.objects.filter(dt__hour=1).count(), 1) self.assertEqual(Event.objects.filter(dt__minute=30).count(), 2) self.assertEqual(Event.objects.filter(dt__second=0).count(), 2) def test_query_aggregation(self): # Only min and max make sense for datetimes. Event.objects.create(dt=datetime.datetime(2011, 9, 1, 23, 20, 20)) Event.objects.create(dt=datetime.datetime(2011, 9, 1, 13, 20, 30)) Event.objects.create(dt=datetime.datetime(2011, 9, 1, 3, 20, 40)) result = Event.objects.all().aggregate(Min('dt'), Max('dt')) self.assertEqual(result, { 'dt__min': datetime.datetime(2011, 9, 1, 3, 20, 40), 'dt__max': datetime.datetime(2011, 9, 1, 23, 20, 20), }) def test_query_annotation(self): # Only min and max make sense for datetimes. morning = Session.objects.create(name='morning') afternoon = Session.objects.create(name='afternoon') SessionEvent.objects.create(dt=datetime.datetime(2011, 9, 1, 23, 20, 20), session=afternoon) SessionEvent.objects.create(dt=datetime.datetime(2011, 9, 1, 13, 20, 30), session=afternoon) SessionEvent.objects.create(dt=datetime.datetime(2011, 9, 1, 3, 20, 40), session=morning) morning_min_dt = datetime.datetime(2011, 9, 1, 3, 20, 40) afternoon_min_dt = datetime.datetime(2011, 9, 1, 13, 20, 30) self.assertQuerysetEqual( Session.objects.annotate(dt=Min('events__dt')).order_by('dt'), [morning_min_dt, afternoon_min_dt], transform=lambda d: d.dt, ) self.assertQuerysetEqual( Session.objects.annotate(dt=Min('events__dt')).filter(dt__lt=afternoon_min_dt), [morning_min_dt], transform=lambda d: d.dt, ) self.assertQuerysetEqual( Session.objects.annotate(dt=Min('events__dt')).filter(dt__gte=afternoon_min_dt), [afternoon_min_dt], transform=lambda d: d.dt, ) def test_query_datetimes(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0)) self.assertSequenceEqual(Event.objects.datetimes('dt', 'year'), [datetime.datetime(2011, 1, 1, 0, 0, 0)]) self.assertSequenceEqual(Event.objects.datetimes('dt', 'month'), [datetime.datetime(2011, 1, 1, 0, 0, 0)]) self.assertSequenceEqual(Event.objects.datetimes('dt', 'day'), [datetime.datetime(2011, 1, 1, 0, 0, 0)]) self.assertSequenceEqual( Event.objects.datetimes('dt', 'hour'), [datetime.datetime(2011, 1, 1, 1, 0, 0), datetime.datetime(2011, 1, 1, 4, 0, 0)] ) self.assertSequenceEqual( Event.objects.datetimes('dt', 'minute'), [datetime.datetime(2011, 1, 1, 1, 30, 0), datetime.datetime(2011, 1, 1, 4, 30, 0)] ) self.assertSequenceEqual( Event.objects.datetimes('dt', 'second'), [datetime.datetime(2011, 1, 1, 1, 30, 0), datetime.datetime(2011, 1, 1, 4, 30, 0)] ) def test_raw_sql(self): # Regression test for #17755 dt = datetime.datetime(2011, 9, 1, 13, 20, 30) event = Event.objects.create(dt=dt) self.assertEqual(list(Event.objects.raw('SELECT * FROM timezones_event WHERE dt = %s', [dt])), [event]) def test_cursor_execute_accepts_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) with connection.cursor() as cursor: cursor.execute('INSERT INTO timezones_event (dt) VALUES (%s)', [dt]) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_cursor_execute_returns_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) Event.objects.create(dt=dt) with connection.cursor() as cursor: cursor.execute('SELECT dt FROM timezones_event WHERE dt = %s', [dt]) self.assertEqual(cursor.fetchall()[0][0], dt) def test_filter_date_field_with_aware_datetime(self): # Regression test for #17742 day = datetime.date(2011, 9, 1) AllDayEvent.objects.create(day=day) # This is 2011-09-02T01:30:00+03:00 in EAT dt = datetime.datetime(2011, 9, 1, 22, 30, 0, tzinfo=UTC) self.assertTrue(AllDayEvent.objects.filter(day__gte=dt).exists()) @override_settings(TIME_ZONE='Africa/Nairobi', USE_TZ=True) class NewDatabaseTests(TestCase): naive_warning = 'DateTimeField Event.dt received a naive datetime' @requires_tz_support def test_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): Event.objects.create(dt=dt) event = Event.objects.get() # naive datetimes are interpreted in local time self.assertEqual(event.dt, dt.replace(tzinfo=EAT)) @requires_tz_support def test_datetime_from_date(self): dt = datetime.date(2011, 9, 1) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, datetime.datetime(2011, 9, 1, tzinfo=EAT)) @requires_tz_support def test_naive_datetime_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): Event.objects.create(dt=dt) event = Event.objects.get() # naive datetimes are interpreted in local time self.assertEqual(event.dt, dt.replace(tzinfo=EAT)) def test_aware_datetime_in_local_timezone(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_aware_datetime_in_local_timezone_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060, tzinfo=EAT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_aware_datetime_in_utc(self): dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_aware_datetime_in_other_timezone(self): dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_auto_now_and_auto_now_add(self): now = timezone.now() past = now - datetime.timedelta(seconds=2) future = now + datetime.timedelta(seconds=2) Timestamp.objects.create() ts = Timestamp.objects.get() self.assertLess(past, ts.created) self.assertLess(past, ts.updated) self.assertGreater(future, ts.updated) self.assertGreater(future, ts.updated) def test_query_filter(self): dt1 = datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=EAT) dt2 = datetime.datetime(2011, 9, 1, 14, 20, 30, tzinfo=EAT) Event.objects.create(dt=dt1) Event.objects.create(dt=dt2) self.assertEqual(Event.objects.filter(dt__gte=dt1).count(), 2) self.assertEqual(Event.objects.filter(dt__gt=dt1).count(), 1) self.assertEqual(Event.objects.filter(dt__gte=dt2).count(), 1) self.assertEqual(Event.objects.filter(dt__gt=dt2).count(), 0) def test_query_filter_with_pytz_timezones(self): tz = pytz.timezone('Europe/Paris') dt = datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=tz) Event.objects.create(dt=dt) next = dt + datetime.timedelta(seconds=3) prev = dt - datetime.timedelta(seconds=3) self.assertEqual(Event.objects.filter(dt__exact=dt).count(), 1) self.assertEqual(Event.objects.filter(dt__exact=next).count(), 0) self.assertEqual(Event.objects.filter(dt__in=(prev, next)).count(), 0) self.assertEqual(Event.objects.filter(dt__in=(prev, dt, next)).count(), 1) self.assertEqual(Event.objects.filter(dt__range=(prev, next)).count(), 1) def test_query_convert_timezones(self): # Connection timezone is equal to the current timezone, datetime # shouldn't be converted. with override_database_connection_timezone('Africa/Nairobi'): event_datetime = datetime.datetime(2016, 1, 2, 23, 10, 11, 123, tzinfo=EAT) event = Event.objects.create(dt=event_datetime) self.assertEqual(Event.objects.filter(dt__date=event_datetime.date()).first(), event) # Connection timezone is not equal to the current timezone, datetime # should be converted (-4h). with override_database_connection_timezone('Asia/Bangkok'): event_datetime = datetime.datetime(2016, 1, 2, 3, 10, 11, tzinfo=ICT) event = Event.objects.create(dt=event_datetime) self.assertEqual(Event.objects.filter(dt__date=datetime.date(2016, 1, 1)).first(), event) @requires_tz_support def test_query_filter_with_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=EAT) Event.objects.create(dt=dt) dt = dt.replace(tzinfo=None) # naive datetimes are interpreted in local time with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): self.assertEqual(Event.objects.filter(dt__exact=dt).count(), 1) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): self.assertEqual(Event.objects.filter(dt__lte=dt).count(), 1) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): self.assertEqual(Event.objects.filter(dt__gt=dt).count(), 0) @skipUnlessDBFeature('has_zoneinfo_database') def test_query_datetime_lookups(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)) self.assertEqual(Event.objects.filter(dt__year=2011).count(), 2) self.assertEqual(Event.objects.filter(dt__month=1).count(), 2) self.assertEqual(Event.objects.filter(dt__day=1).count(), 2) self.assertEqual(Event.objects.filter(dt__week_day=7).count(), 2) self.assertEqual(Event.objects.filter(dt__iso_week_day=6).count(), 2) self.assertEqual(Event.objects.filter(dt__hour=1).count(), 1) self.assertEqual(Event.objects.filter(dt__minute=30).count(), 2) self.assertEqual(Event.objects.filter(dt__second=0).count(), 2) @skipUnlessDBFeature('has_zoneinfo_database') def test_query_datetime_lookups_in_other_timezone(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)) with timezone.override(UTC): # These two dates fall in the same day in EAT, but in different days, # years and months in UTC. self.assertEqual(Event.objects.filter(dt__year=2011).count(), 1) self.assertEqual(Event.objects.filter(dt__month=1).count(), 1) self.assertEqual(Event.objects.filter(dt__day=1).count(), 1) self.assertEqual(Event.objects.filter(dt__week_day=7).count(), 1) self.assertEqual(Event.objects.filter(dt__iso_week_day=6).count(), 1) self.assertEqual(Event.objects.filter(dt__hour=22).count(), 1) self.assertEqual(Event.objects.filter(dt__minute=30).count(), 2) self.assertEqual(Event.objects.filter(dt__second=0).count(), 2) def test_query_aggregation(self): # Only min and max make sense for datetimes. Event.objects.create(dt=datetime.datetime(2011, 9, 1, 23, 20, 20, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT)) result = Event.objects.all().aggregate(Min('dt'), Max('dt')) self.assertEqual(result, { 'dt__min': datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT), 'dt__max': datetime.datetime(2011, 9, 1, 23, 20, 20, tzinfo=EAT), }) def test_query_annotation(self): # Only min and max make sense for datetimes. morning = Session.objects.create(name='morning') afternoon = Session.objects.create(name='afternoon') SessionEvent.objects.create(dt=datetime.datetime(2011, 9, 1, 23, 20, 20, tzinfo=EAT), session=afternoon) SessionEvent.objects.create(dt=datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), session=afternoon) SessionEvent.objects.create(dt=datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT), session=morning) morning_min_dt = datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT) afternoon_min_dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) self.assertQuerysetEqual( Session.objects.annotate(dt=Min('events__dt')).order_by('dt'), [morning_min_dt, afternoon_min_dt], transform=lambda d: d.dt, ) self.assertQuerysetEqual( Session.objects.annotate(dt=Min('events__dt')).filter(dt__lt=afternoon_min_dt), [morning_min_dt], transform=lambda d: d.dt, ) self.assertQuerysetEqual( Session.objects.annotate(dt=Min('events__dt')).filter(dt__gte=afternoon_min_dt), [afternoon_min_dt], transform=lambda d: d.dt, ) @skipUnlessDBFeature('has_zoneinfo_database') def test_query_datetimes(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)) self.assertSequenceEqual( Event.objects.datetimes('dt', 'year'), [datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=EAT)] ) self.assertSequenceEqual( Event.objects.datetimes('dt', 'month'), [datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=EAT)] ) self.assertSequenceEqual( Event.objects.datetimes('dt', 'day'), [datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=EAT)] ) self.assertSequenceEqual( Event.objects.datetimes('dt', 'hour'), [datetime.datetime(2011, 1, 1, 1, 0, 0, tzinfo=EAT), datetime.datetime(2011, 1, 1, 4, 0, 0, tzinfo=EAT)] ) self.assertSequenceEqual( Event.objects.datetimes('dt', 'minute'), [datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT), datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)] ) self.assertSequenceEqual( Event.objects.datetimes('dt', 'second'), [datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT), datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)] ) @skipUnlessDBFeature('has_zoneinfo_database') def test_query_datetimes_in_other_timezone(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)) with timezone.override(UTC): self.assertSequenceEqual( Event.objects.datetimes('dt', 'year'), [datetime.datetime(2010, 1, 1, 0, 0, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=UTC)] ) self.assertSequenceEqual( Event.objects.datetimes('dt', 'month'), [datetime.datetime(2010, 12, 1, 0, 0, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=UTC)] ) self.assertSequenceEqual( Event.objects.datetimes('dt', 'day'), [datetime.datetime(2010, 12, 31, 0, 0, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=UTC)] ) self.assertSequenceEqual( Event.objects.datetimes('dt', 'hour'), [datetime.datetime(2010, 12, 31, 22, 0, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 1, 0, 0, tzinfo=UTC)] ) self.assertSequenceEqual( Event.objects.datetimes('dt', 'minute'), [datetime.datetime(2010, 12, 31, 22, 30, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=UTC)] ) self.assertSequenceEqual( Event.objects.datetimes('dt', 'second'), [datetime.datetime(2010, 12, 31, 22, 30, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=UTC)] ) def test_raw_sql(self): # Regression test for #17755 dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) event = Event.objects.create(dt=dt) self.assertSequenceEqual(list(Event.objects.raw('SELECT * FROM timezones_event WHERE dt = %s', [dt])), [event]) @skipUnlessDBFeature('supports_timezones') def test_cursor_execute_accepts_aware_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) with connection.cursor() as cursor: cursor.execute('INSERT INTO timezones_event (dt) VALUES (%s)', [dt]) event = Event.objects.get() self.assertEqual(event.dt, dt) @skipIfDBFeature('supports_timezones') def test_cursor_execute_accepts_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) utc_naive_dt = timezone.make_naive(dt, timezone.utc) with connection.cursor() as cursor: cursor.execute('INSERT INTO timezones_event (dt) VALUES (%s)', [utc_naive_dt]) event = Event.objects.get() self.assertEqual(event.dt, dt) @skipUnlessDBFeature('supports_timezones') def test_cursor_execute_returns_aware_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) Event.objects.create(dt=dt) with connection.cursor() as cursor: cursor.execute('SELECT dt FROM timezones_event WHERE dt = %s', [dt]) self.assertEqual(cursor.fetchall()[0][0], dt) @skipIfDBFeature('supports_timezones') def test_cursor_execute_returns_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) utc_naive_dt = timezone.make_naive(dt, timezone.utc) Event.objects.create(dt=dt) with connection.cursor() as cursor: cursor.execute('SELECT dt FROM timezones_event WHERE dt = %s', [utc_naive_dt]) self.assertEqual(cursor.fetchall()[0][0], utc_naive_dt) @requires_tz_support def test_filter_date_field_with_aware_datetime(self): # Regression test for #17742 day = datetime.date(2011, 9, 1) AllDayEvent.objects.create(day=day) # This is 2011-09-02T01:30:00+03:00 in EAT dt = datetime.datetime(2011, 9, 1, 22, 30, 0, tzinfo=UTC) self.assertFalse(AllDayEvent.objects.filter(day__gte=dt).exists()) def test_null_datetime(self): # Regression test for #17294 e = MaybeEvent.objects.create() self.assertIsNone(e.dt) def test_update_with_timedelta(self): initial_dt = timezone.now().replace(microsecond=0) event = Event.objects.create(dt=initial_dt) Event.objects.update(dt=F('dt') + timedelta(hours=2)) event.refresh_from_db() self.assertEqual(event.dt, initial_dt + timedelta(hours=2)) @override_settings(TIME_ZONE='Africa/Nairobi', USE_TZ=True) class ForcedTimeZoneDatabaseTests(TransactionTestCase): """ Test the TIME_ZONE database configuration parameter. Since this involves reading and writing to the same database through two connections, this is a TransactionTestCase. """ available_apps = ['timezones'] @classmethod def setUpClass(cls): # @skipIfDBFeature and @skipUnlessDBFeature cannot be chained. The # outermost takes precedence. Handle skipping manually instead. if connection.features.supports_timezones: raise SkipTest("Database has feature(s) supports_timezones") if not connection.features.test_db_allows_multiple_connections: raise SkipTest("Database doesn't support feature(s): test_db_allows_multiple_connections") super().setUpClass() def test_read_datetime(self): fake_dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=UTC) Event.objects.create(dt=fake_dt) with override_database_connection_timezone('Asia/Bangkok'): event = Event.objects.get() dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) self.assertEqual(event.dt, dt) def test_write_datetime(self): dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) with override_database_connection_timezone('Asia/Bangkok'): Event.objects.create(dt=dt) event = Event.objects.get() fake_dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=UTC) self.assertEqual(event.dt, fake_dt) @skipUnlessDBFeature('supports_timezones') @override_settings(TIME_ZONE='Africa/Nairobi', USE_TZ=True) class UnsupportedTimeZoneDatabaseTests(TestCase): def test_time_zone_parameter_not_supported_if_database_supports_timezone(self): connections.databases['tz'] = connections.databases['default'].copy() connections.databases['tz']['TIME_ZONE'] = 'Asia/Bangkok' tz_conn = connections['tz'] try: msg = ( "Connection 'tz' cannot set TIME_ZONE because its engine " "handles time zones conversions natively." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): tz_conn.cursor() finally: connections['tz'].close() # in case the test fails del connections['tz'] del connections.databases['tz'] @override_settings(TIME_ZONE='Africa/Nairobi') class SerializationTests(SimpleTestCase): # Backend-specific notes: # - JSON supports only milliseconds, microseconds will be truncated. # - PyYAML dumps the UTC offset correctly for timezone-aware datetimes, # but when it loads this representation, it subtracts the offset and # returns a naive datetime object in UTC. See ticket #18867. # Tests are adapted to take these quirks into account. def assert_python_contains_datetime(self, objects, dt): self.assertEqual(objects[0]['fields']['dt'], dt) def assert_json_contains_datetime(self, json, dt): self.assertIn('"fields": {"dt": "%s"}' % dt, json) def assert_xml_contains_datetime(self, xml, dt): field = parseString(xml).getElementsByTagName('field')[0] self.assertXMLEqual(field.childNodes[0].wholeText, dt) def assert_yaml_contains_datetime(self, yaml, dt): # Depending on the yaml dumper, '!timestamp' might be absent self.assertRegex(yaml, r"\n fields: {dt: !(!timestamp)? '%s'}" % re.escape(dt)) def test_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) data = serializers.serialize('python', [Event(dt=dt)]) self.assert_python_contains_datetime(data, dt) obj = next(serializers.deserialize('python', data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize('json', [Event(dt=dt)]) self.assert_json_contains_datetime(data, "2011-09-01T13:20:30") obj = next(serializers.deserialize('json', data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize('xml', [Event(dt=dt)]) self.assert_xml_contains_datetime(data, "2011-09-01T13:20:30") obj = next(serializers.deserialize('xml', data)).object self.assertEqual(obj.dt, dt) if not isinstance(serializers.get_serializer('yaml'), serializers.BadSerializer): data = serializers.serialize('yaml', [Event(dt=dt)], default_flow_style=None) self.assert_yaml_contains_datetime(data, "2011-09-01 13:20:30") obj = next(serializers.deserialize('yaml', data)).object self.assertEqual(obj.dt, dt) def test_naive_datetime_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060) data = serializers.serialize('python', [Event(dt=dt)]) self.assert_python_contains_datetime(data, dt) obj = next(serializers.deserialize('python', data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize('json', [Event(dt=dt)]) self.assert_json_contains_datetime(data, "2011-09-01T13:20:30.405") obj = next(serializers.deserialize('json', data)).object self.assertEqual(obj.dt, dt.replace(microsecond=405000)) data = serializers.serialize('xml', [Event(dt=dt)]) self.assert_xml_contains_datetime(data, "2011-09-01T13:20:30.405060") obj = next(serializers.deserialize('xml', data)).object self.assertEqual(obj.dt, dt) if not isinstance(serializers.get_serializer('yaml'), serializers.BadSerializer): data = serializers.serialize('yaml', [Event(dt=dt)], default_flow_style=None) self.assert_yaml_contains_datetime(data, "2011-09-01 13:20:30.405060") obj = next(serializers.deserialize('yaml', data)).object self.assertEqual(obj.dt, dt) def test_aware_datetime_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 17, 20, 30, 405060, tzinfo=ICT) data = serializers.serialize('python', [Event(dt=dt)]) self.assert_python_contains_datetime(data, dt) obj = next(serializers.deserialize('python', data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize('json', [Event(dt=dt)]) self.assert_json_contains_datetime(data, "2011-09-01T17:20:30.405+07:00") obj = next(serializers.deserialize('json', data)).object self.assertEqual(obj.dt, dt.replace(microsecond=405000)) data = serializers.serialize('xml', [Event(dt=dt)]) self.assert_xml_contains_datetime(data, "2011-09-01T17:20:30.405060+07:00") obj = next(serializers.deserialize('xml', data)).object self.assertEqual(obj.dt, dt) if not isinstance(serializers.get_serializer('yaml'), serializers.BadSerializer): data = serializers.serialize('yaml', [Event(dt=dt)], default_flow_style=None) self.assert_yaml_contains_datetime(data, "2011-09-01 17:20:30.405060+07:00") obj = next(serializers.deserialize('yaml', data)).object self.assertEqual(obj.dt.replace(tzinfo=UTC), dt) def test_aware_datetime_in_utc(self): dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) data = serializers.serialize('python', [Event(dt=dt)]) self.assert_python_contains_datetime(data, dt) obj = next(serializers.deserialize('python', data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize('json', [Event(dt=dt)]) self.assert_json_contains_datetime(data, "2011-09-01T10:20:30Z") obj = next(serializers.deserialize('json', data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize('xml', [Event(dt=dt)]) self.assert_xml_contains_datetime(data, "2011-09-01T10:20:30+00:00") obj = next(serializers.deserialize('xml', data)).object self.assertEqual(obj.dt, dt) if not isinstance(serializers.get_serializer('yaml'), serializers.BadSerializer): data = serializers.serialize('yaml', [Event(dt=dt)], default_flow_style=None) self.assert_yaml_contains_datetime(data, "2011-09-01 10:20:30+00:00") obj = next(serializers.deserialize('yaml', data)).object self.assertEqual(obj.dt.replace(tzinfo=UTC), dt) def test_aware_datetime_in_local_timezone(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) data = serializers.serialize('python', [Event(dt=dt)]) self.assert_python_contains_datetime(data, dt) obj = next(serializers.deserialize('python', data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize('json', [Event(dt=dt)]) self.assert_json_contains_datetime(data, "2011-09-01T13:20:30+03:00") obj = next(serializers.deserialize('json', data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize('xml', [Event(dt=dt)]) self.assert_xml_contains_datetime(data, "2011-09-01T13:20:30+03:00") obj = next(serializers.deserialize('xml', data)).object self.assertEqual(obj.dt, dt) if not isinstance(serializers.get_serializer('yaml'), serializers.BadSerializer): data = serializers.serialize('yaml', [Event(dt=dt)], default_flow_style=None) self.assert_yaml_contains_datetime(data, "2011-09-01 13:20:30+03:00") obj = next(serializers.deserialize('yaml', data)).object self.assertEqual(obj.dt.replace(tzinfo=UTC), dt) def test_aware_datetime_in_other_timezone(self): dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT) data = serializers.serialize('python', [Event(dt=dt)]) self.assert_python_contains_datetime(data, dt) obj = next(serializers.deserialize('python', data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize('json', [Event(dt=dt)]) self.assert_json_contains_datetime(data, "2011-09-01T17:20:30+07:00") obj = next(serializers.deserialize('json', data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize('xml', [Event(dt=dt)]) self.assert_xml_contains_datetime(data, "2011-09-01T17:20:30+07:00") obj = next(serializers.deserialize('xml', data)).object self.assertEqual(obj.dt, dt) if not isinstance(serializers.get_serializer('yaml'), serializers.BadSerializer): data = serializers.serialize('yaml', [Event(dt=dt)], default_flow_style=None) self.assert_yaml_contains_datetime(data, "2011-09-01 17:20:30+07:00") obj = next(serializers.deserialize('yaml', data)).object self.assertEqual(obj.dt.replace(tzinfo=UTC), dt) @override_settings(DATETIME_FORMAT='c', TIME_ZONE='Africa/Nairobi', USE_L10N=False, USE_TZ=True) class TemplateTests(SimpleTestCase): @requires_tz_support def test_localtime_templatetag_and_filters(self): """ Test the {% localtime %} templatetag and related filters. """ datetimes = { 'utc': datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC), 'eat': datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), 'ict': datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT), 'naive': datetime.datetime(2011, 9, 1, 13, 20, 30), } templates = { 'notag': Template("{% load tz %}{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:ICT }}"), 'noarg': Template( "{% load tz %}{% localtime %}{{ dt }}|{{ dt|localtime }}|" "{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}" ), 'on': Template( "{% load tz %}{% localtime on %}{{ dt }}|{{ dt|localtime }}|" "{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}" ), 'off': Template( "{% load tz %}{% localtime off %}{{ dt }}|{{ dt|localtime }}|" "{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}" ), } # Transform a list of keys in 'datetimes' to the expected template # output. This makes the definition of 'results' more readable. def t(*result): return '|'.join(datetimes[key].isoformat() for key in result) # Results for USE_TZ = True results = { 'utc': { 'notag': t('eat', 'eat', 'utc', 'ict'), 'noarg': t('eat', 'eat', 'utc', 'ict'), 'on': t('eat', 'eat', 'utc', 'ict'), 'off': t('utc', 'eat', 'utc', 'ict'), }, 'eat': { 'notag': t('eat', 'eat', 'utc', 'ict'), 'noarg': t('eat', 'eat', 'utc', 'ict'), 'on': t('eat', 'eat', 'utc', 'ict'), 'off': t('eat', 'eat', 'utc', 'ict'), }, 'ict': { 'notag': t('eat', 'eat', 'utc', 'ict'), 'noarg': t('eat', 'eat', 'utc', 'ict'), 'on': t('eat', 'eat', 'utc', 'ict'), 'off': t('ict', 'eat', 'utc', 'ict'), }, 'naive': { 'notag': t('naive', 'eat', 'utc', 'ict'), 'noarg': t('naive', 'eat', 'utc', 'ict'), 'on': t('naive', 'eat', 'utc', 'ict'), 'off': t('naive', 'eat', 'utc', 'ict'), } } for k1, dt in datetimes.items(): for k2, tpl in templates.items(): ctx = Context({'dt': dt, 'ICT': ICT}) actual = tpl.render(ctx) expected = results[k1][k2] self.assertEqual(actual, expected, '%s / %s: %r != %r' % (k1, k2, actual, expected)) # Changes for USE_TZ = False results['utc']['notag'] = t('utc', 'eat', 'utc', 'ict') results['ict']['notag'] = t('ict', 'eat', 'utc', 'ict') with self.settings(USE_TZ=False): for k1, dt in datetimes.items(): for k2, tpl in templates.items(): ctx = Context({'dt': dt, 'ICT': ICT}) actual = tpl.render(ctx) expected = results[k1][k2] self.assertEqual(actual, expected, '%s / %s: %r != %r' % (k1, k2, actual, expected)) def test_localtime_filters_with_pytz(self): """ Test the |localtime, |utc, and |timezone filters with pytz. """ # Use a pytz timezone as local time tpl = Template("{% load tz %}{{ dt|localtime }}|{{ dt|utc }}") ctx = Context({'dt': datetime.datetime(2011, 9, 1, 12, 20, 30)}) with self.settings(TIME_ZONE='Europe/Paris'): self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00|2011-09-01T10:20:30+00:00") # Use a pytz timezone as argument tpl = Template("{% load tz %}{{ dt|timezone:tz }}") ctx = Context({ 'dt': datetime.datetime(2011, 9, 1, 13, 20, 30), 'tz': pytz.timezone('Europe/Paris'), }) self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00") # Use a pytz timezone name as argument tpl = Template("{% load tz %}{{ dt|timezone:'Europe/Paris' }}") ctx = Context({ 'dt': datetime.datetime(2011, 9, 1, 13, 20, 30), 'tz': pytz.timezone('Europe/Paris'), }) self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00") def test_localtime_templatetag_invalid_argument(self): with self.assertRaises(TemplateSyntaxError): Template("{% load tz %}{% localtime foo %}{% endlocaltime %}").render() def test_localtime_filters_do_not_raise_exceptions(self): """ Test the |localtime, |utc, and |timezone filters on bad inputs. """ tpl = Template("{% load tz %}{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:tz }}") with self.settings(USE_TZ=True): # bad datetime value ctx = Context({'dt': None, 'tz': ICT}) self.assertEqual(tpl.render(ctx), "None|||") ctx = Context({'dt': 'not a date', 'tz': ICT}) self.assertEqual(tpl.render(ctx), "not a date|||") # bad timezone value tpl = Template("{% load tz %}{{ dt|timezone:tz }}") ctx = Context({'dt': datetime.datetime(2011, 9, 1, 13, 20, 30), 'tz': None}) self.assertEqual(tpl.render(ctx), "") ctx = Context({'dt': datetime.datetime(2011, 9, 1, 13, 20, 30), 'tz': 'not a tz'}) self.assertEqual(tpl.render(ctx), "") @requires_tz_support def test_timezone_templatetag(self): """ Test the {% timezone %} templatetag. """ tpl = Template( "{% load tz %}" "{{ dt }}|" "{% timezone tz1 %}" "{{ dt }}|" "{% timezone tz2 %}" "{{ dt }}" "{% endtimezone %}" "{% endtimezone %}" ) ctx = Context({ 'dt': datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC), 'tz1': ICT, 'tz2': None, }) self.assertEqual( tpl.render(ctx), "2011-09-01T13:20:30+03:00|2011-09-01T17:20:30+07:00|2011-09-01T13:20:30+03:00" ) def test_timezone_templatetag_with_pytz(self): """ Test the {% timezone %} templatetag with pytz. """ tpl = Template("{% load tz %}{% timezone tz %}{{ dt }}{% endtimezone %}") # Use a pytz timezone as argument ctx = Context({ 'dt': datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), 'tz': pytz.timezone('Europe/Paris'), }) self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00") # Use a pytz timezone name as argument ctx = Context({ 'dt': datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), 'tz': 'Europe/Paris', }) self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00") def test_timezone_templatetag_invalid_argument(self): with self.assertRaises(TemplateSyntaxError): Template("{% load tz %}{% timezone %}{% endtimezone %}").render() with self.assertRaises(pytz.UnknownTimeZoneError): Template("{% load tz %}{% timezone tz %}{% endtimezone %}").render(Context({'tz': 'foobar'})) @skipIf(sys.platform.startswith('win'), "Windows uses non-standard time zone names") def test_get_current_timezone_templatetag(self): """ Test the {% get_current_timezone %} templatetag. """ tpl = Template("{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}") self.assertEqual(tpl.render(Context()), "Africa/Nairobi") with timezone.override(UTC): self.assertEqual(tpl.render(Context()), "UTC") tpl = Template( "{% load tz %}{% timezone tz %}{% get_current_timezone as time_zone %}" "{% endtimezone %}{{ time_zone }}" ) self.assertEqual(tpl.render(Context({'tz': ICT})), "+0700") with timezone.override(UTC): self.assertEqual(tpl.render(Context({'tz': ICT})), "+0700") def test_get_current_timezone_templatetag_with_pytz(self): """ Test the {% get_current_timezone %} templatetag with pytz. """ tpl = Template("{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}") with timezone.override(pytz.timezone('Europe/Paris')): self.assertEqual(tpl.render(Context()), "Europe/Paris") tpl = Template( "{% load tz %}{% timezone 'Europe/Paris' %}" "{% get_current_timezone as time_zone %}{% endtimezone %}" "{{ time_zone }}" ) self.assertEqual(tpl.render(Context()), "Europe/Paris") def test_get_current_timezone_templatetag_invalid_argument(self): msg = "'get_current_timezone' requires 'as variable' (got ['get_current_timezone'])" with self.assertRaisesMessage(TemplateSyntaxError, msg): Template("{% load tz %}{% get_current_timezone %}").render() @skipIf(sys.platform.startswith('win'), "Windows uses non-standard time zone names") def test_tz_template_context_processor(self): """ Test the django.template.context_processors.tz template context processor. """ tpl = Template("{{ TIME_ZONE }}") context = Context() self.assertEqual(tpl.render(context), "") request_context = RequestContext(HttpRequest(), processors=[context_processors.tz]) self.assertEqual(tpl.render(request_context), "Africa/Nairobi") @requires_tz_support def test_date_and_time_template_filters(self): tpl = Template("{{ dt|date:'Y-m-d' }} at {{ dt|time:'H:i:s' }}") ctx = Context({'dt': datetime.datetime(2011, 9, 1, 20, 20, 20, tzinfo=UTC)}) self.assertEqual(tpl.render(ctx), "2011-09-01 at 23:20:20") with timezone.override(ICT): self.assertEqual(tpl.render(ctx), "2011-09-02 at 03:20:20") def test_date_and_time_template_filters_honor_localtime(self): tpl = Template( "{% load tz %}{% localtime off %}{{ dt|date:'Y-m-d' }} at " "{{ dt|time:'H:i:s' }}{% endlocaltime %}" ) ctx = Context({'dt': datetime.datetime(2011, 9, 1, 20, 20, 20, tzinfo=UTC)}) self.assertEqual(tpl.render(ctx), "2011-09-01 at 20:20:20") with timezone.override(ICT): self.assertEqual(tpl.render(ctx), "2011-09-01 at 20:20:20") @requires_tz_support def test_now_template_tag_uses_current_time_zone(self): # Regression for #17343 tpl = Template("{% now \"O\" %}") self.assertEqual(tpl.render(Context({})), "+0300") with timezone.override(ICT): self.assertEqual(tpl.render(Context({})), "+0700") @override_settings(DATETIME_FORMAT='c', TIME_ZONE='Africa/Nairobi', USE_L10N=False, USE_TZ=False) class LegacyFormsTests(TestCase): def test_form(self): form = EventForm({'dt': '2011-09-01 13:20:30'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 9, 1, 13, 20, 30)) def test_form_with_non_existent_time(self): form = EventForm({'dt': '2011-03-27 02:30:00'}) with timezone.override(pytz.timezone('Europe/Paris')): # this is obviously a bug self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 3, 27, 2, 30, 0)) def test_form_with_ambiguous_time(self): form = EventForm({'dt': '2011-10-30 02:30:00'}) with timezone.override(pytz.timezone('Europe/Paris')): # this is obviously a bug self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 10, 30, 2, 30, 0)) def test_split_form(self): form = EventSplitForm({'dt_0': '2011-09-01', 'dt_1': '13:20:30'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 9, 1, 13, 20, 30)) def test_model_form(self): EventModelForm({'dt': '2011-09-01 13:20:30'}).save() e = Event.objects.get() self.assertEqual(e.dt, datetime.datetime(2011, 9, 1, 13, 20, 30)) @override_settings(DATETIME_FORMAT='c', TIME_ZONE='Africa/Nairobi', USE_L10N=False, USE_TZ=True) class NewFormsTests(TestCase): @requires_tz_support def test_form(self): form = EventForm({'dt': '2011-09-01 13:20:30'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)) def test_form_with_other_timezone(self): form = EventForm({'dt': '2011-09-01 17:20:30'}) with timezone.override(ICT): self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)) def test_form_with_explicit_timezone(self): form = EventForm({'dt': '2011-09-01 17:20:30+07:00'}) # Datetime inputs formats don't allow providing a time zone. self.assertFalse(form.is_valid()) def test_form_with_non_existent_time(self): with timezone.override(pytz.timezone('Europe/Paris')): form = EventForm({'dt': '2011-03-27 02:30:00'}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors['dt'], [ '2011-03-27 02:30:00 couldn’t be interpreted in time zone ' 'Europe/Paris; it may be ambiguous or it may not exist.' ] ) def test_form_with_ambiguous_time(self): with timezone.override(pytz.timezone('Europe/Paris')): form = EventForm({'dt': '2011-10-30 02:30:00'}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors['dt'], [ '2011-10-30 02:30:00 couldn’t be interpreted in time zone ' 'Europe/Paris; it may be ambiguous or it may not exist.' ] ) @requires_tz_support def test_split_form(self): form = EventSplitForm({'dt_0': '2011-09-01', 'dt_1': '13:20:30'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['dt'], datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)) @requires_tz_support def test_localized_form(self): form = EventLocalizedForm(initial={'dt': datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)}) with timezone.override(ICT): self.assertIn("2011-09-01 17:20:30", str(form)) @requires_tz_support def test_model_form(self): EventModelForm({'dt': '2011-09-01 13:20:30'}).save() e = Event.objects.get() self.assertEqual(e.dt, datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)) @requires_tz_support def test_localized_model_form(self): form = EventLocalizedModelForm(instance=Event(dt=datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT))) with timezone.override(ICT): self.assertIn("2011-09-01 17:20:30", str(form)) @override_settings( DATETIME_FORMAT='c', TIME_ZONE='Africa/Nairobi', USE_L10N=False, USE_TZ=True, ROOT_URLCONF='timezones.urls', ) class AdminTests(TestCase): @classmethod def setUpTestData(cls): cls.u1 = User.objects.create_user( password='secret', last_login=datetime.datetime(2007, 5, 30, 13, 20, 10, tzinfo=UTC), is_superuser=True, username='super', first_name='Super', last_name='User', email='[email protected]', is_staff=True, is_active=True, date_joined=datetime.datetime(2007, 5, 30, 13, 20, 10, tzinfo=UTC), ) def setUp(self): self.client.force_login(self.u1) @requires_tz_support def test_changelist(self): e = Event.objects.create(dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)) response = self.client.get(reverse('admin_tz:timezones_event_changelist')) self.assertContains(response, e.dt.astimezone(EAT).isoformat()) def test_changelist_in_other_timezone(self): e = Event.objects.create(dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)) with timezone.override(ICT): response = self.client.get(reverse('admin_tz:timezones_event_changelist')) self.assertContains(response, e.dt.astimezone(ICT).isoformat()) @requires_tz_support def test_change_editable(self): e = Event.objects.create(dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)) response = self.client.get(reverse('admin_tz:timezones_event_change', args=(e.pk,))) self.assertContains(response, e.dt.astimezone(EAT).date().isoformat()) self.assertContains(response, e.dt.astimezone(EAT).time().isoformat()) def test_change_editable_in_other_timezone(self): e = Event.objects.create(dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)) with timezone.override(ICT): response = self.client.get(reverse('admin_tz:timezones_event_change', args=(e.pk,))) self.assertContains(response, e.dt.astimezone(ICT).date().isoformat()) self.assertContains(response, e.dt.astimezone(ICT).time().isoformat()) @requires_tz_support def test_change_readonly(self): Timestamp.objects.create() # re-fetch the object for backends that lose microseconds (MySQL) t = Timestamp.objects.get() response = self.client.get(reverse('admin_tz:timezones_timestamp_change', args=(t.pk,))) self.assertContains(response, t.created.astimezone(EAT).isoformat()) def test_change_readonly_in_other_timezone(self): Timestamp.objects.create() # re-fetch the object for backends that lose microseconds (MySQL) t = Timestamp.objects.get() with timezone.override(ICT): response = self.client.get(reverse('admin_tz:timezones_timestamp_change', args=(t.pk,))) self.assertContains(response, t.created.astimezone(ICT).isoformat())
98cf14215e73f9c124307b2d04e52d9a03f1b3b6112fc33918985efba1432d29
import datetime import decimal import ipaddress import uuid from django.db import models from django.test import SimpleTestCase from django.utils.functional import Promise from django.utils.translation import gettext_lazy as _ class Suit(models.IntegerChoices): DIAMOND = 1, _('Diamond') SPADE = 2, _('Spade') HEART = 3, _('Heart') CLUB = 4, _('Club') class YearInSchool(models.TextChoices): FRESHMAN = 'FR', _('Freshman') SOPHOMORE = 'SO', _('Sophomore') JUNIOR = 'JR', _('Junior') SENIOR = 'SR', _('Senior') GRADUATE = 'GR', _('Graduate') class Vehicle(models.IntegerChoices): CAR = 1, 'Carriage' TRUCK = 2 JET_SKI = 3 __empty__ = _('(Unknown)') class Gender(models.TextChoices): MALE = 'M' FEMALE = 'F' NOT_SPECIFIED = 'X' __empty__ = '(Undeclared)' class ChoicesTests(SimpleTestCase): def test_integerchoices(self): self.assertEqual(Suit.choices, [(1, 'Diamond'), (2, 'Spade'), (3, 'Heart'), (4, 'Club')]) self.assertEqual(Suit.labels, ['Diamond', 'Spade', 'Heart', 'Club']) self.assertEqual(Suit.values, [1, 2, 3, 4]) self.assertEqual(Suit.names, ['DIAMOND', 'SPADE', 'HEART', 'CLUB']) self.assertEqual(repr(Suit.DIAMOND), '<Suit.DIAMOND: 1>') self.assertEqual(Suit.DIAMOND.label, 'Diamond') self.assertEqual(Suit.DIAMOND.value, 1) self.assertEqual(Suit['DIAMOND'], Suit.DIAMOND) self.assertEqual(Suit(1), Suit.DIAMOND) self.assertIsInstance(Suit, type(models.Choices)) self.assertIsInstance(Suit.DIAMOND, Suit) self.assertIsInstance(Suit.DIAMOND.label, Promise) self.assertIsInstance(Suit.DIAMOND.value, int) def test_integerchoices_auto_label(self): self.assertEqual(Vehicle.CAR.label, 'Carriage') self.assertEqual(Vehicle.TRUCK.label, 'Truck') self.assertEqual(Vehicle.JET_SKI.label, 'Jet Ski') def test_integerchoices_empty_label(self): self.assertEqual(Vehicle.choices[0], (None, '(Unknown)')) self.assertEqual(Vehicle.labels[0], '(Unknown)') self.assertEqual(Vehicle.values[0], None) self.assertEqual(Vehicle.names[0], '__empty__') def test_integerchoices_functional_api(self): Place = models.IntegerChoices('Place', 'FIRST SECOND THIRD') self.assertEqual(Place.labels, ['First', 'Second', 'Third']) self.assertEqual(Place.values, [1, 2, 3]) self.assertEqual(Place.names, ['FIRST', 'SECOND', 'THIRD']) def test_integerchoices_containment(self): self.assertIn(Suit.DIAMOND, Suit) self.assertIn(1, Suit) self.assertNotIn(0, Suit) def test_textchoices(self): self.assertEqual(YearInSchool.choices, [ ('FR', 'Freshman'), ('SO', 'Sophomore'), ('JR', 'Junior'), ('SR', 'Senior'), ('GR', 'Graduate'), ]) self.assertEqual(YearInSchool.labels, ['Freshman', 'Sophomore', 'Junior', 'Senior', 'Graduate']) self.assertEqual(YearInSchool.values, ['FR', 'SO', 'JR', 'SR', 'GR']) self.assertEqual(YearInSchool.names, ['FRESHMAN', 'SOPHOMORE', 'JUNIOR', 'SENIOR', 'GRADUATE']) self.assertEqual(repr(YearInSchool.FRESHMAN), "<YearInSchool.FRESHMAN: 'FR'>") self.assertEqual(YearInSchool.FRESHMAN.label, 'Freshman') self.assertEqual(YearInSchool.FRESHMAN.value, 'FR') self.assertEqual(YearInSchool['FRESHMAN'], YearInSchool.FRESHMAN) self.assertEqual(YearInSchool('FR'), YearInSchool.FRESHMAN) self.assertIsInstance(YearInSchool, type(models.Choices)) self.assertIsInstance(YearInSchool.FRESHMAN, YearInSchool) self.assertIsInstance(YearInSchool.FRESHMAN.label, Promise) self.assertIsInstance(YearInSchool.FRESHMAN.value, str) def test_textchoices_auto_label(self): self.assertEqual(Gender.MALE.label, 'Male') self.assertEqual(Gender.FEMALE.label, 'Female') self.assertEqual(Gender.NOT_SPECIFIED.label, 'Not Specified') def test_textchoices_empty_label(self): self.assertEqual(Gender.choices[0], (None, '(Undeclared)')) self.assertEqual(Gender.labels[0], '(Undeclared)') self.assertEqual(Gender.values[0], None) self.assertEqual(Gender.names[0], '__empty__') def test_textchoices_functional_api(self): Medal = models.TextChoices('Medal', 'GOLD SILVER BRONZE') self.assertEqual(Medal.labels, ['Gold', 'Silver', 'Bronze']) self.assertEqual(Medal.values, ['GOLD', 'SILVER', 'BRONZE']) self.assertEqual(Medal.names, ['GOLD', 'SILVER', 'BRONZE']) def test_textchoices_containment(self): self.assertIn(YearInSchool.FRESHMAN, YearInSchool) self.assertIn('FR', YearInSchool) self.assertNotIn('XX', YearInSchool) def test_textchoices_blank_value(self): class BlankStr(models.TextChoices): EMPTY = '', '(Empty)' ONE = 'ONE', 'One' self.assertEqual(BlankStr.labels, ['(Empty)', 'One']) self.assertEqual(BlankStr.values, ['', 'ONE']) self.assertEqual(BlankStr.names, ['EMPTY', 'ONE']) def test_invalid_definition(self): msg = "'str' object cannot be interpreted as an integer" with self.assertRaisesMessage(TypeError, msg): class InvalidArgumentEnum(models.IntegerChoices): # A string is not permitted as the second argument to int(). ONE = 1, 'X', 'Invalid' msg = "duplicate values found in <enum 'Fruit'>: PINEAPPLE -> APPLE" with self.assertRaisesMessage(ValueError, msg): class Fruit(models.IntegerChoices): APPLE = 1, 'Apple' PINEAPPLE = 1, 'Pineapple' class Separator(bytes, models.Choices): FS = b'\x1c', 'File Separator' GS = b'\x1d', 'Group Separator' RS = b'\x1e', 'Record Separator' US = b'\x1f', 'Unit Separator' class Constants(float, models.Choices): PI = 3.141592653589793, 'π' TAU = 6.283185307179586, 'τ' class Set(frozenset, models.Choices): A = {1, 2} B = {2, 3} UNION = A | B DIFFERENCE = A - B INTERSECTION = A & B class MoonLandings(datetime.date, models.Choices): APOLLO_11 = 1969, 7, 20, 'Apollo 11 (Eagle)' APOLLO_12 = 1969, 11, 19, 'Apollo 12 (Intrepid)' APOLLO_14 = 1971, 2, 5, 'Apollo 14 (Antares)' APOLLO_15 = 1971, 7, 30, 'Apollo 15 (Falcon)' APOLLO_16 = 1972, 4, 21, 'Apollo 16 (Orion)' APOLLO_17 = 1972, 12, 11, 'Apollo 17 (Challenger)' class DateAndTime(datetime.datetime, models.Choices): A = 2010, 10, 10, 10, 10, 10 B = 2011, 11, 11, 11, 11, 11 C = 2012, 12, 12, 12, 12, 12 class MealTimes(datetime.time, models.Choices): BREAKFAST = 7, 0 LUNCH = 13, 0 DINNER = 18, 30 class Frequency(datetime.timedelta, models.Choices): WEEK = 0, 0, 0, 0, 0, 0, 1, 'Week' DAY = 1, 'Day' HOUR = 0, 0, 0, 0, 0, 1, 'Hour' MINUTE = 0, 0, 0, 0, 1, 'Hour' SECOND = 0, 1, 'Second' class Number(decimal.Decimal, models.Choices): E = 2.718281828459045, 'e' PI = '3.141592653589793', 'π' TAU = decimal.Decimal('6.283185307179586'), 'τ' class IPv4Address(ipaddress.IPv4Address, models.Choices): LOCALHOST = '127.0.0.1', 'Localhost' GATEWAY = '192.168.0.1', 'Gateway' BROADCAST = '192.168.0.255', 'Broadcast' class IPv6Address(ipaddress.IPv6Address, models.Choices): LOCALHOST = '::1', 'Localhost' UNSPECIFIED = '::', 'Unspecified' class IPv4Network(ipaddress.IPv4Network, models.Choices): LOOPBACK = '127.0.0.0/8', 'Loopback' LINK_LOCAL = '169.254.0.0/16', 'Link-Local' PRIVATE_USE_A = '10.0.0.0/8', 'Private-Use (Class A)' class IPv6Network(ipaddress.IPv6Network, models.Choices): LOOPBACK = '::1/128', 'Loopback' UNSPECIFIED = '::/128', 'Unspecified' UNIQUE_LOCAL = 'fc00::/7', 'Unique-Local' LINK_LOCAL_UNICAST = 'fe80::/10', 'Link-Local Unicast' class CustomChoicesTests(SimpleTestCase): def test_labels_valid(self): enums = ( Separator, Constants, Set, MoonLandings, DateAndTime, MealTimes, Frequency, Number, IPv4Address, IPv6Address, IPv4Network, IPv6Network, ) for choice_enum in enums: with self.subTest(choice_enum.__name__): self.assertNotIn(None, choice_enum.labels) def test_bool_unsupported(self): msg = "type 'bool' is not an acceptable base type" with self.assertRaisesMessage(TypeError, msg): class Boolean(bool, models.Choices): pass def test_timezone_unsupported(self): msg = "type 'datetime.timezone' is not an acceptable base type" with self.assertRaisesMessage(TypeError, msg): class Timezone(datetime.timezone, models.Choices): pass def test_uuid_unsupported(self): msg = 'UUID objects are immutable' with self.assertRaisesMessage(TypeError, msg): class Identifier(uuid.UUID, models.Choices): A = '972ce4eb-a95f-4a56-9339-68c208a76f18'
ce8a66105b069164482db6424233d314271b12c7e499b1d38f0a4fa2fadcf15c
from unittest import mock from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist from django.db import connection from django.db.models import Prefetch, QuerySet from django.db.models.query import get_prefetcher, prefetch_related_objects from django.test import TestCase, override_settings from django.test.utils import CaptureQueriesContext from .models import ( Article, Author, Author2, AuthorAddress, AuthorWithAge, Bio, Book, Bookmark, BookReview, BookWithYear, Comment, Department, Employee, FavoriteAuthors, House, LessonEntry, ModelIterableSubclass, Person, Qualification, Reader, Room, TaggedItem, Teacher, WordEntry, ) class TestDataMixin: @classmethod def setUpTestData(cls): cls.book1 = Book.objects.create(title='Poems') cls.book2 = Book.objects.create(title='Jane Eyre') cls.book3 = Book.objects.create(title='Wuthering Heights') cls.book4 = Book.objects.create(title='Sense and Sensibility') cls.author1 = Author.objects.create(name='Charlotte', first_book=cls.book1) cls.author2 = Author.objects.create(name='Anne', first_book=cls.book1) cls.author3 = Author.objects.create(name='Emily', first_book=cls.book1) cls.author4 = Author.objects.create(name='Jane', first_book=cls.book4) cls.book1.authors.add(cls.author1, cls.author2, cls.author3) cls.book2.authors.add(cls.author1) cls.book3.authors.add(cls.author3) cls.book4.authors.add(cls.author4) cls.reader1 = Reader.objects.create(name='Amy') cls.reader2 = Reader.objects.create(name='Belinda') cls.reader1.books_read.add(cls.book1, cls.book4) cls.reader2.books_read.add(cls.book2, cls.book4) class PrefetchRelatedTests(TestDataMixin, TestCase): def assertWhereContains(self, sql, needle): where_idx = sql.index('WHERE') self.assertEqual( sql.count(str(needle), where_idx), 1, msg="WHERE clause doesn't contain %s, actual SQL: %s" % (needle, sql[where_idx:]) ) def test_m2m_forward(self): with self.assertNumQueries(2): lists = [list(b.authors.all()) for b in Book.objects.prefetch_related('authors')] normal_lists = [list(b.authors.all()) for b in Book.objects.all()] self.assertEqual(lists, normal_lists) def test_m2m_reverse(self): with self.assertNumQueries(2): lists = [list(a.books.all()) for a in Author.objects.prefetch_related('books')] normal_lists = [list(a.books.all()) for a in Author.objects.all()] self.assertEqual(lists, normal_lists) def test_foreignkey_forward(self): with self.assertNumQueries(2): books = [a.first_book for a in Author.objects.prefetch_related('first_book')] normal_books = [a.first_book for a in Author.objects.all()] self.assertEqual(books, normal_books) def test_foreignkey_reverse(self): with self.assertNumQueries(2): [list(b.first_time_authors.all()) for b in Book.objects.prefetch_related('first_time_authors')] self.assertQuerysetEqual(self.book2.authors.all(), ["<Author: Charlotte>"]) def test_onetoone_reverse_no_match(self): # Regression for #17439 with self.assertNumQueries(2): book = Book.objects.prefetch_related('bookwithyear').all()[0] with self.assertNumQueries(0): with self.assertRaises(BookWithYear.DoesNotExist): book.bookwithyear def test_onetoone_reverse_with_to_field_pk(self): """ A model (Bio) with a OneToOneField primary key (author) that references a non-pk field (name) on the related model (Author) is prefetchable. """ Bio.objects.bulk_create([ Bio(author=self.author1), Bio(author=self.author2), Bio(author=self.author3), ]) authors = Author.objects.filter( name__in=[self.author1, self.author2, self.author3], ).prefetch_related('bio') with self.assertNumQueries(2): for author in authors: self.assertEqual(author.name, author.bio.author.name) def test_survives_clone(self): with self.assertNumQueries(2): [list(b.first_time_authors.all()) for b in Book.objects.prefetch_related('first_time_authors').exclude(id=1000)] def test_len(self): with self.assertNumQueries(2): qs = Book.objects.prefetch_related('first_time_authors') len(qs) [list(b.first_time_authors.all()) for b in qs] def test_bool(self): with self.assertNumQueries(2): qs = Book.objects.prefetch_related('first_time_authors') bool(qs) [list(b.first_time_authors.all()) for b in qs] def test_count(self): with self.assertNumQueries(2): qs = Book.objects.prefetch_related('first_time_authors') [b.first_time_authors.count() for b in qs] def test_exists(self): with self.assertNumQueries(2): qs = Book.objects.prefetch_related('first_time_authors') [b.first_time_authors.exists() for b in qs] def test_in_and_prefetch_related(self): """ Regression test for #20242 - QuerySet "in" didn't work the first time when using prefetch_related. This was fixed by the removal of chunked reads from QuerySet iteration in 70679243d1786e03557c28929f9762a119e3ac14. """ qs = Book.objects.prefetch_related('first_time_authors') self.assertIn(qs[0], qs) def test_clear(self): with self.assertNumQueries(5): with_prefetch = Author.objects.prefetch_related('books') without_prefetch = with_prefetch.prefetch_related(None) [list(a.books.all()) for a in without_prefetch] def test_m2m_then_m2m(self): """A m2m can be followed through another m2m.""" with self.assertNumQueries(3): qs = Author.objects.prefetch_related('books__read_by') lists = [[[str(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs] self.assertEqual(lists, [ [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre [["Amy"]], # Anne - Poems [["Amy"], []], # Emily - Poems, Wuthering Heights [["Amy", "Belinda"]], # Jane - Sense and Sense ]) def test_overriding_prefetch(self): with self.assertNumQueries(3): qs = Author.objects.prefetch_related('books', 'books__read_by') lists = [[[str(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs] self.assertEqual(lists, [ [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre [["Amy"]], # Anne - Poems [["Amy"], []], # Emily - Poems, Wuthering Heights [["Amy", "Belinda"]], # Jane - Sense and Sense ]) with self.assertNumQueries(3): qs = Author.objects.prefetch_related('books__read_by', 'books') lists = [[[str(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs] self.assertEqual(lists, [ [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre [["Amy"]], # Anne - Poems [["Amy"], []], # Emily - Poems, Wuthering Heights [["Amy", "Belinda"]], # Jane - Sense and Sense ]) def test_get(self): """ Objects retrieved with .get() get the prefetch behavior. """ # Need a double with self.assertNumQueries(3): author = Author.objects.prefetch_related('books__read_by').get(name="Charlotte") lists = [[str(r) for r in b.read_by.all()] for b in author.books.all()] self.assertEqual(lists, [["Amy"], ["Belinda"]]) # Poems, Jane Eyre def test_foreign_key_then_m2m(self): """ A m2m relation can be followed after a relation like ForeignKey that doesn't have many objects. """ with self.assertNumQueries(2): qs = Author.objects.select_related('first_book').prefetch_related('first_book__read_by') lists = [[str(r) for r in a.first_book.read_by.all()] for a in qs] self.assertEqual(lists, [["Amy"], ["Amy"], ["Amy"], ["Amy", "Belinda"]]) def test_reverse_one_to_one_then_m2m(self): """ A m2m relation can be followed after going through the select_related reverse of an o2o. """ qs = Author.objects.prefetch_related('bio__books').select_related('bio') with self.assertNumQueries(1): list(qs.all()) Bio.objects.create(author=self.author1) with self.assertNumQueries(2): list(qs.all()) def test_attribute_error(self): qs = Reader.objects.all().prefetch_related('books_read__xyz') msg = ( "Cannot find 'xyz' on Book object, 'books_read__xyz' " "is an invalid parameter to prefetch_related()" ) with self.assertRaisesMessage(AttributeError, msg) as cm: list(qs) self.assertIn('prefetch_related', str(cm.exception)) def test_invalid_final_lookup(self): qs = Book.objects.prefetch_related('authors__name') msg = ( "'authors__name' does not resolve to an item that supports " "prefetching - this is an invalid parameter to prefetch_related()." ) with self.assertRaisesMessage(ValueError, msg) as cm: list(qs) self.assertIn('prefetch_related', str(cm.exception)) self.assertIn("name", str(cm.exception)) def test_prefetch_eq(self): prefetch_1 = Prefetch('authors', queryset=Author.objects.all()) prefetch_2 = Prefetch('books', queryset=Book.objects.all()) self.assertEqual(prefetch_1, prefetch_1) self.assertEqual(prefetch_1, mock.ANY) self.assertNotEqual(prefetch_1, prefetch_2) def test_forward_m2m_to_attr_conflict(self): msg = 'to_attr=authors conflicts with a field on the Book model.' authors = Author.objects.all() with self.assertRaisesMessage(ValueError, msg): list(Book.objects.prefetch_related( Prefetch('authors', queryset=authors, to_attr='authors'), )) # Without the ValueError, an author was deleted due to the implicit # save of the relation assignment. self.assertEqual(self.book1.authors.count(), 3) def test_reverse_m2m_to_attr_conflict(self): msg = 'to_attr=books conflicts with a field on the Author model.' poems = Book.objects.filter(title='Poems') with self.assertRaisesMessage(ValueError, msg): list(Author.objects.prefetch_related( Prefetch('books', queryset=poems, to_attr='books'), )) # Without the ValueError, a book was deleted due to the implicit # save of reverse relation assignment. self.assertEqual(self.author1.books.count(), 2) def test_m2m_then_reverse_fk_object_ids(self): with CaptureQueriesContext(connection) as queries: list(Book.objects.prefetch_related('authors__addresses')) sql = queries[-1]['sql'] self.assertWhereContains(sql, self.author1.name) def test_m2m_then_m2m_object_ids(self): with CaptureQueriesContext(connection) as queries: list(Book.objects.prefetch_related('authors__favorite_authors')) sql = queries[-1]['sql'] self.assertWhereContains(sql, self.author1.name) def test_m2m_then_reverse_one_to_one_object_ids(self): with CaptureQueriesContext(connection) as queries: list(Book.objects.prefetch_related('authors__authorwithage')) sql = queries[-1]['sql'] self.assertWhereContains(sql, self.author1.id) class RawQuerySetTests(TestDataMixin, TestCase): def test_basic(self): with self.assertNumQueries(2): books = Book.objects.raw( "SELECT * FROM prefetch_related_book WHERE id = %s", (self.book1.id,) ).prefetch_related('authors') book1 = list(books)[0] with self.assertNumQueries(0): self.assertCountEqual(book1.authors.all(), [self.author1, self.author2, self.author3]) def test_prefetch_before_raw(self): with self.assertNumQueries(2): books = Book.objects.prefetch_related('authors').raw( "SELECT * FROM prefetch_related_book WHERE id = %s", (self.book1.id,) ) book1 = list(books)[0] with self.assertNumQueries(0): self.assertCountEqual(book1.authors.all(), [self.author1, self.author2, self.author3]) def test_clear(self): with self.assertNumQueries(5): with_prefetch = Author.objects.raw( "SELECT * FROM prefetch_related_author" ).prefetch_related('books') without_prefetch = with_prefetch.prefetch_related(None) [list(a.books.all()) for a in without_prefetch] class CustomPrefetchTests(TestCase): @classmethod def traverse_qs(cls, obj_iter, path): """ Helper method that returns a list containing a list of the objects in the obj_iter. Then for each object in the obj_iter, the path will be recursively travelled and the found objects are added to the return value. """ ret_val = [] if hasattr(obj_iter, 'all'): obj_iter = obj_iter.all() try: iter(obj_iter) except TypeError: obj_iter = [obj_iter] for obj in obj_iter: rel_objs = [] for part in path: if not part: continue try: related = getattr(obj, part[0]) except ObjectDoesNotExist: continue if related is not None: rel_objs.extend(cls.traverse_qs(related, [part[1:]])) ret_val.append((obj, rel_objs)) return ret_val @classmethod def setUpTestData(cls): cls.person1 = Person.objects.create(name='Joe') cls.person2 = Person.objects.create(name='Mary') # Set main_room for each house before creating the next one for # databases where supports_nullable_unique_constraints is False. cls.house1 = House.objects.create(name='House 1', address='123 Main St', owner=cls.person1) cls.room1_1 = Room.objects.create(name='Dining room', house=cls.house1) cls.room1_2 = Room.objects.create(name='Lounge', house=cls.house1) cls.room1_3 = Room.objects.create(name='Kitchen', house=cls.house1) cls.house1.main_room = cls.room1_1 cls.house1.save() cls.person1.houses.add(cls.house1) cls.house2 = House.objects.create(name='House 2', address='45 Side St', owner=cls.person1) cls.room2_1 = Room.objects.create(name='Dining room', house=cls.house2) cls.room2_2 = Room.objects.create(name='Lounge', house=cls.house2) cls.room2_3 = Room.objects.create(name='Kitchen', house=cls.house2) cls.house2.main_room = cls.room2_1 cls.house2.save() cls.person1.houses.add(cls.house2) cls.house3 = House.objects.create(name='House 3', address='6 Downing St', owner=cls.person2) cls.room3_1 = Room.objects.create(name='Dining room', house=cls.house3) cls.room3_2 = Room.objects.create(name='Lounge', house=cls.house3) cls.room3_3 = Room.objects.create(name='Kitchen', house=cls.house3) cls.house3.main_room = cls.room3_1 cls.house3.save() cls.person2.houses.add(cls.house3) cls.house4 = House.objects.create(name='house 4', address="7 Regents St", owner=cls.person2) cls.room4_1 = Room.objects.create(name='Dining room', house=cls.house4) cls.room4_2 = Room.objects.create(name='Lounge', house=cls.house4) cls.room4_3 = Room.objects.create(name='Kitchen', house=cls.house4) cls.house4.main_room = cls.room4_1 cls.house4.save() cls.person2.houses.add(cls.house4) def test_traverse_qs(self): qs = Person.objects.prefetch_related('houses') related_objs_normal = [list(p.houses.all()) for p in qs], related_objs_from_traverse = [[inner[0] for inner in o[1]] for o in self.traverse_qs(qs, [['houses']])] self.assertEqual(related_objs_normal, (related_objs_from_traverse,)) def test_ambiguous(self): # Ambiguous: Lookup was already seen with a different queryset. msg = ( "'houses' lookup was already seen with a different queryset. You " "may need to adjust the ordering of your lookups." ) # lookup.queryset shouldn't be evaluated. with self.assertNumQueries(3): with self.assertRaisesMessage(ValueError, msg): self.traverse_qs( Person.objects.prefetch_related( 'houses__rooms', Prefetch('houses', queryset=House.objects.all()), ), [['houses', 'rooms']], ) # Ambiguous: Lookup houses_lst doesn't yet exist when performing houses_lst__rooms. msg = ( "Cannot find 'houses_lst' on Person object, 'houses_lst__rooms' is " "an invalid parameter to prefetch_related()" ) with self.assertRaisesMessage(AttributeError, msg): self.traverse_qs( Person.objects.prefetch_related( 'houses_lst__rooms', Prefetch('houses', queryset=House.objects.all(), to_attr='houses_lst') ), [['houses', 'rooms']] ) # Not ambiguous. self.traverse_qs( Person.objects.prefetch_related('houses__rooms', 'houses'), [['houses', 'rooms']] ) self.traverse_qs( Person.objects.prefetch_related( 'houses__rooms', Prefetch('houses', queryset=House.objects.all(), to_attr='houses_lst') ), [['houses', 'rooms']] ) def test_m2m(self): # Control lookups. with self.assertNumQueries(2): lst1 = self.traverse_qs( Person.objects.prefetch_related('houses'), [['houses']] ) # Test lookups. with self.assertNumQueries(2): lst2 = self.traverse_qs( Person.objects.prefetch_related(Prefetch('houses')), [['houses']] ) self.assertEqual(lst1, lst2) with self.assertNumQueries(2): lst2 = self.traverse_qs( Person.objects.prefetch_related(Prefetch('houses', to_attr='houses_lst')), [['houses_lst']] ) self.assertEqual(lst1, lst2) def test_reverse_m2m(self): # Control lookups. with self.assertNumQueries(2): lst1 = self.traverse_qs( House.objects.prefetch_related('occupants'), [['occupants']] ) # Test lookups. with self.assertNumQueries(2): lst2 = self.traverse_qs( House.objects.prefetch_related(Prefetch('occupants')), [['occupants']] ) self.assertEqual(lst1, lst2) with self.assertNumQueries(2): lst2 = self.traverse_qs( House.objects.prefetch_related(Prefetch('occupants', to_attr='occupants_lst')), [['occupants_lst']] ) self.assertEqual(lst1, lst2) def test_m2m_through_fk(self): # Control lookups. with self.assertNumQueries(3): lst1 = self.traverse_qs( Room.objects.prefetch_related('house__occupants'), [['house', 'occupants']] ) # Test lookups. with self.assertNumQueries(3): lst2 = self.traverse_qs( Room.objects.prefetch_related(Prefetch('house__occupants')), [['house', 'occupants']] ) self.assertEqual(lst1, lst2) with self.assertNumQueries(3): lst2 = self.traverse_qs( Room.objects.prefetch_related(Prefetch('house__occupants', to_attr='occupants_lst')), [['house', 'occupants_lst']] ) self.assertEqual(lst1, lst2) def test_m2m_through_gfk(self): TaggedItem.objects.create(tag="houses", content_object=self.house1) TaggedItem.objects.create(tag="houses", content_object=self.house2) # Control lookups. with self.assertNumQueries(3): lst1 = self.traverse_qs( TaggedItem.objects.filter(tag='houses').prefetch_related('content_object__rooms'), [['content_object', 'rooms']] ) # Test lookups. with self.assertNumQueries(3): lst2 = self.traverse_qs( TaggedItem.objects.prefetch_related( Prefetch('content_object'), Prefetch('content_object__rooms', to_attr='rooms_lst') ), [['content_object', 'rooms_lst']] ) self.assertEqual(lst1, lst2) def test_o2m_through_m2m(self): # Control lookups. with self.assertNumQueries(3): lst1 = self.traverse_qs( Person.objects.prefetch_related('houses', 'houses__rooms'), [['houses', 'rooms']] ) # Test lookups. with self.assertNumQueries(3): lst2 = self.traverse_qs( Person.objects.prefetch_related(Prefetch('houses'), 'houses__rooms'), [['houses', 'rooms']] ) self.assertEqual(lst1, lst2) with self.assertNumQueries(3): lst2 = self.traverse_qs( Person.objects.prefetch_related(Prefetch('houses'), Prefetch('houses__rooms')), [['houses', 'rooms']] ) self.assertEqual(lst1, lst2) with self.assertNumQueries(3): lst2 = self.traverse_qs( Person.objects.prefetch_related(Prefetch('houses', to_attr='houses_lst'), 'houses_lst__rooms'), [['houses_lst', 'rooms']] ) self.assertEqual(lst1, lst2) with self.assertNumQueries(3): lst2 = self.traverse_qs( Person.objects.prefetch_related( Prefetch('houses', to_attr='houses_lst'), Prefetch('houses_lst__rooms', to_attr='rooms_lst') ), [['houses_lst', 'rooms_lst']] ) self.assertEqual(lst1, lst2) def test_generic_rel(self): bookmark = Bookmark.objects.create(url='http://www.djangoproject.com/') TaggedItem.objects.create(content_object=bookmark, tag='django') TaggedItem.objects.create(content_object=bookmark, favorite=bookmark, tag='python') # Control lookups. with self.assertNumQueries(4): lst1 = self.traverse_qs( Bookmark.objects.prefetch_related('tags', 'tags__content_object', 'favorite_tags'), [['tags', 'content_object'], ['favorite_tags']] ) # Test lookups. with self.assertNumQueries(4): lst2 = self.traverse_qs( Bookmark.objects.prefetch_related( Prefetch('tags', to_attr='tags_lst'), Prefetch('tags_lst__content_object'), Prefetch('favorite_tags'), ), [['tags_lst', 'content_object'], ['favorite_tags']] ) self.assertEqual(lst1, lst2) def test_traverse_single_item_property(self): # Control lookups. with self.assertNumQueries(5): lst1 = self.traverse_qs( Person.objects.prefetch_related( 'houses__rooms', 'primary_house__occupants__houses', ), [['primary_house', 'occupants', 'houses']] ) # Test lookups. with self.assertNumQueries(5): lst2 = self.traverse_qs( Person.objects.prefetch_related( 'houses__rooms', Prefetch('primary_house__occupants', to_attr='occupants_lst'), 'primary_house__occupants_lst__houses', ), [['primary_house', 'occupants_lst', 'houses']] ) self.assertEqual(lst1, lst2) def test_traverse_multiple_items_property(self): # Control lookups. with self.assertNumQueries(4): lst1 = self.traverse_qs( Person.objects.prefetch_related( 'houses', 'all_houses__occupants__houses', ), [['all_houses', 'occupants', 'houses']] ) # Test lookups. with self.assertNumQueries(4): lst2 = self.traverse_qs( Person.objects.prefetch_related( 'houses', Prefetch('all_houses__occupants', to_attr='occupants_lst'), 'all_houses__occupants_lst__houses', ), [['all_houses', 'occupants_lst', 'houses']] ) self.assertEqual(lst1, lst2) def test_custom_qs(self): # Test basic. with self.assertNumQueries(2): lst1 = list(Person.objects.prefetch_related('houses')) with self.assertNumQueries(2): lst2 = list(Person.objects.prefetch_related( Prefetch('houses', queryset=House.objects.all(), to_attr='houses_lst'))) self.assertEqual( self.traverse_qs(lst1, [['houses']]), self.traverse_qs(lst2, [['houses_lst']]) ) # Test queryset filtering. with self.assertNumQueries(2): lst2 = list( Person.objects.prefetch_related( Prefetch( 'houses', queryset=House.objects.filter(pk__in=[self.house1.pk, self.house3.pk]), to_attr='houses_lst', ) ) ) self.assertEqual(len(lst2[0].houses_lst), 1) self.assertEqual(lst2[0].houses_lst[0], self.house1) self.assertEqual(len(lst2[1].houses_lst), 1) self.assertEqual(lst2[1].houses_lst[0], self.house3) # Test flattened. with self.assertNumQueries(3): lst1 = list(Person.objects.prefetch_related('houses__rooms')) with self.assertNumQueries(3): lst2 = list(Person.objects.prefetch_related( Prefetch('houses__rooms', queryset=Room.objects.all(), to_attr='rooms_lst'))) self.assertEqual( self.traverse_qs(lst1, [['houses', 'rooms']]), self.traverse_qs(lst2, [['houses', 'rooms_lst']]) ) # Test inner select_related. with self.assertNumQueries(3): lst1 = list(Person.objects.prefetch_related('houses__owner')) with self.assertNumQueries(2): lst2 = list(Person.objects.prefetch_related( Prefetch('houses', queryset=House.objects.select_related('owner')))) self.assertEqual( self.traverse_qs(lst1, [['houses', 'owner']]), self.traverse_qs(lst2, [['houses', 'owner']]) ) # Test inner prefetch. inner_rooms_qs = Room.objects.filter(pk__in=[self.room1_1.pk, self.room1_2.pk]) houses_qs_prf = House.objects.prefetch_related( Prefetch('rooms', queryset=inner_rooms_qs, to_attr='rooms_lst')) with self.assertNumQueries(4): lst2 = list(Person.objects.prefetch_related( Prefetch('houses', queryset=houses_qs_prf.filter(pk=self.house1.pk), to_attr='houses_lst'), Prefetch('houses_lst__rooms_lst__main_room_of') )) self.assertEqual(len(lst2[0].houses_lst[0].rooms_lst), 2) self.assertEqual(lst2[0].houses_lst[0].rooms_lst[0], self.room1_1) self.assertEqual(lst2[0].houses_lst[0].rooms_lst[1], self.room1_2) self.assertEqual(lst2[0].houses_lst[0].rooms_lst[0].main_room_of, self.house1) self.assertEqual(len(lst2[1].houses_lst), 0) # Test ForwardManyToOneDescriptor. houses = House.objects.select_related('owner') with self.assertNumQueries(6): rooms = Room.objects.all().prefetch_related('house') lst1 = self.traverse_qs(rooms, [['house', 'owner']]) with self.assertNumQueries(2): rooms = Room.objects.all().prefetch_related(Prefetch('house', queryset=houses.all())) lst2 = self.traverse_qs(rooms, [['house', 'owner']]) self.assertEqual(lst1, lst2) with self.assertNumQueries(2): houses = House.objects.select_related('owner') rooms = Room.objects.all().prefetch_related(Prefetch('house', queryset=houses.all(), to_attr='house_attr')) lst2 = self.traverse_qs(rooms, [['house_attr', 'owner']]) self.assertEqual(lst1, lst2) room = Room.objects.all().prefetch_related( Prefetch('house', queryset=houses.filter(address='DoesNotExist')) ).first() with self.assertRaises(ObjectDoesNotExist): getattr(room, 'house') room = Room.objects.all().prefetch_related( Prefetch('house', queryset=houses.filter(address='DoesNotExist'), to_attr='house_attr') ).first() self.assertIsNone(room.house_attr) rooms = Room.objects.all().prefetch_related(Prefetch('house', queryset=House.objects.only('name'))) with self.assertNumQueries(2): getattr(rooms.first().house, 'name') with self.assertNumQueries(3): getattr(rooms.first().house, 'address') # Test ReverseOneToOneDescriptor. houses = House.objects.select_related('owner') with self.assertNumQueries(6): rooms = Room.objects.all().prefetch_related('main_room_of') lst1 = self.traverse_qs(rooms, [['main_room_of', 'owner']]) with self.assertNumQueries(2): rooms = Room.objects.all().prefetch_related(Prefetch('main_room_of', queryset=houses.all())) lst2 = self.traverse_qs(rooms, [['main_room_of', 'owner']]) self.assertEqual(lst1, lst2) with self.assertNumQueries(2): rooms = list( Room.objects.all().prefetch_related( Prefetch('main_room_of', queryset=houses.all(), to_attr='main_room_of_attr') ) ) lst2 = self.traverse_qs(rooms, [['main_room_of_attr', 'owner']]) self.assertEqual(lst1, lst2) room = Room.objects.filter(main_room_of__isnull=False).prefetch_related( Prefetch('main_room_of', queryset=houses.filter(address='DoesNotExist')) ).first() with self.assertRaises(ObjectDoesNotExist): getattr(room, 'main_room_of') room = Room.objects.filter(main_room_of__isnull=False).prefetch_related( Prefetch('main_room_of', queryset=houses.filter(address='DoesNotExist'), to_attr='main_room_of_attr') ).first() self.assertIsNone(room.main_room_of_attr) # The custom queryset filters should be applied to the queryset # instance returned by the manager. person = Person.objects.prefetch_related( Prefetch('houses', queryset=House.objects.filter(name='House 1')), ).get(pk=self.person1.pk) self.assertEqual( list(person.houses.all()), list(person.houses.all().all()), ) def test_nested_prefetch_related_are_not_overwritten(self): # Regression test for #24873 houses_2 = House.objects.prefetch_related(Prefetch('rooms')) persons = Person.objects.prefetch_related(Prefetch('houses', queryset=houses_2)) houses = House.objects.prefetch_related(Prefetch('occupants', queryset=persons)) list(houses) # queryset must be evaluated once to reproduce the bug. self.assertEqual( houses.all()[0].occupants.all()[0].houses.all()[1].rooms.all()[0], self.room2_1 ) def test_nested_prefetch_related_with_duplicate_prefetcher(self): """ Nested prefetches whose name clashes with descriptor names (Person.houses here) are allowed. """ occupants = Person.objects.prefetch_related( Prefetch('houses', to_attr='some_attr_name'), Prefetch('houses', queryset=House.objects.prefetch_related('main_room')), ) houses = House.objects.prefetch_related(Prefetch('occupants', queryset=occupants)) with self.assertNumQueries(5): self.traverse_qs(list(houses), [['occupants', 'houses', 'main_room']]) def test_values_queryset(self): with self.assertRaisesMessage(ValueError, 'Prefetch querysets cannot use values().'): Prefetch('houses', House.objects.values('pk')) # That error doesn't affect managers with custom ModelIterable subclasses self.assertIs(Teacher.objects_custom.all()._iterable_class, ModelIterableSubclass) Prefetch('teachers', Teacher.objects_custom.all()) def test_to_attr_doesnt_cache_through_attr_as_list(self): house = House.objects.prefetch_related( Prefetch('rooms', queryset=Room.objects.all(), to_attr='to_rooms'), ).get(pk=self.house3.pk) self.assertIsInstance(house.rooms.all(), QuerySet) def test_to_attr_cached_property(self): persons = Person.objects.prefetch_related( Prefetch('houses', House.objects.all(), to_attr='cached_all_houses'), ) for person in persons: # To bypass caching at the related descriptor level, don't use # person.houses.all() here. all_houses = list(House.objects.filter(occupants=person)) with self.assertNumQueries(0): self.assertEqual(person.cached_all_houses, all_houses) class DefaultManagerTests(TestCase): def setUp(self): self.qual1 = Qualification.objects.create(name="BA") self.qual2 = Qualification.objects.create(name="BSci") self.qual3 = Qualification.objects.create(name="MA") self.qual4 = Qualification.objects.create(name="PhD") self.teacher1 = Teacher.objects.create(name="Mr Cleese") self.teacher2 = Teacher.objects.create(name="Mr Idle") self.teacher3 = Teacher.objects.create(name="Mr Chapman") self.teacher1.qualifications.add(self.qual1, self.qual2, self.qual3, self.qual4) self.teacher2.qualifications.add(self.qual1) self.teacher3.qualifications.add(self.qual2) self.dept1 = Department.objects.create(name="English") self.dept2 = Department.objects.create(name="Physics") self.dept1.teachers.add(self.teacher1, self.teacher2) self.dept2.teachers.add(self.teacher1, self.teacher3) def test_m2m_then_m2m(self): with self.assertNumQueries(3): # When we prefetch the teachers, and force the query, we don't want # the default manager on teachers to immediately get all the related # qualifications, since this will do one query per teacher. qs = Department.objects.prefetch_related('teachers') depts = "".join("%s department: %s\n" % (dept.name, ", ".join(str(t) for t in dept.teachers.all())) for dept in qs) self.assertEqual(depts, "English department: Mr Cleese (BA, BSci, MA, PhD), Mr Idle (BA)\n" "Physics department: Mr Cleese (BA, BSci, MA, PhD), Mr Chapman (BSci)\n") class GenericRelationTests(TestCase): @classmethod def setUpTestData(cls): book1 = Book.objects.create(title="Winnie the Pooh") book2 = Book.objects.create(title="Do you like green eggs and spam?") book3 = Book.objects.create(title="Three Men In A Boat") reader1 = Reader.objects.create(name="me") reader2 = Reader.objects.create(name="you") reader3 = Reader.objects.create(name="someone") book1.read_by.add(reader1, reader2) book2.read_by.add(reader2) book3.read_by.add(reader3) cls.book1, cls.book2, cls.book3 = book1, book2, book3 cls.reader1, cls.reader2, cls.reader3 = reader1, reader2, reader3 def test_prefetch_GFK(self): TaggedItem.objects.create(tag="awesome", content_object=self.book1) TaggedItem.objects.create(tag="great", content_object=self.reader1) TaggedItem.objects.create(tag="outstanding", content_object=self.book2) TaggedItem.objects.create(tag="amazing", content_object=self.reader3) # 1 for TaggedItem table, 1 for Book table, 1 for Reader table with self.assertNumQueries(3): qs = TaggedItem.objects.prefetch_related('content_object') list(qs) def test_prefetch_GFK_nonint_pk(self): Comment.objects.create(comment="awesome", content_object=self.book1) # 1 for Comment table, 1 for Book table with self.assertNumQueries(2): qs = Comment.objects.prefetch_related('content_object') [c.content_object for c in qs] def test_prefetch_GFK_uuid_pk(self): article = Article.objects.create(name='Django') Comment.objects.create(comment='awesome', content_object_uuid=article) qs = Comment.objects.prefetch_related('content_object_uuid') self.assertEqual([c.content_object_uuid for c in qs], [article]) def test_prefetch_GFK_fk_pk(self): book = Book.objects.create(title='Poems') book_with_year = BookWithYear.objects.create(book=book, published_year=2019) Comment.objects.create(comment='awesome', content_object=book_with_year) qs = Comment.objects.prefetch_related('content_object') self.assertEqual([c.content_object for c in qs], [book_with_year]) def test_traverse_GFK(self): """ A 'content_object' can be traversed with prefetch_related() and get to related objects on the other side (assuming it is suitably filtered) """ TaggedItem.objects.create(tag="awesome", content_object=self.book1) TaggedItem.objects.create(tag="awesome", content_object=self.book2) TaggedItem.objects.create(tag="awesome", content_object=self.book3) TaggedItem.objects.create(tag="awesome", content_object=self.reader1) TaggedItem.objects.create(tag="awesome", content_object=self.reader2) ct = ContentType.objects.get_for_model(Book) # We get 3 queries - 1 for main query, 1 for content_objects since they # all use the same table, and 1 for the 'read_by' relation. with self.assertNumQueries(3): # If we limit to books, we know that they will have 'read_by' # attributes, so the following makes sense: qs = TaggedItem.objects.filter(content_type=ct, tag='awesome').prefetch_related('content_object__read_by') readers_of_awesome_books = {r.name for tag in qs for r in tag.content_object.read_by.all()} self.assertEqual(readers_of_awesome_books, {"me", "you", "someone"}) def test_nullable_GFK(self): TaggedItem.objects.create(tag="awesome", content_object=self.book1, created_by=self.reader1) TaggedItem.objects.create(tag="great", content_object=self.book2) TaggedItem.objects.create(tag="rubbish", content_object=self.book3) with self.assertNumQueries(2): result = [t.created_by for t in TaggedItem.objects.prefetch_related('created_by')] self.assertEqual(result, [t.created_by for t in TaggedItem.objects.all()]) def test_generic_relation(self): bookmark = Bookmark.objects.create(url='http://www.djangoproject.com/') TaggedItem.objects.create(content_object=bookmark, tag='django') TaggedItem.objects.create(content_object=bookmark, tag='python') with self.assertNumQueries(2): tags = [t.tag for b in Bookmark.objects.prefetch_related('tags') for t in b.tags.all()] self.assertEqual(sorted(tags), ["django", "python"]) def test_charfield_GFK(self): b = Bookmark.objects.create(url='http://www.djangoproject.com/') TaggedItem.objects.create(content_object=b, tag='django') TaggedItem.objects.create(content_object=b, favorite=b, tag='python') with self.assertNumQueries(3): bookmark = Bookmark.objects.filter(pk=b.pk).prefetch_related('tags', 'favorite_tags')[0] self.assertEqual(sorted(i.tag for i in bookmark.tags.all()), ["django", "python"]) self.assertEqual([i.tag for i in bookmark.favorite_tags.all()], ["python"]) def test_custom_queryset(self): bookmark = Bookmark.objects.create(url='http://www.djangoproject.com/') django_tag = TaggedItem.objects.create(content_object=bookmark, tag='django') TaggedItem.objects.create(content_object=bookmark, tag='python') with self.assertNumQueries(2): bookmark = Bookmark.objects.prefetch_related( Prefetch('tags', TaggedItem.objects.filter(tag='django')), ).get() with self.assertNumQueries(0): self.assertEqual(list(bookmark.tags.all()), [django_tag]) # The custom queryset filters should be applied to the queryset # instance returned by the manager. self.assertEqual(list(bookmark.tags.all()), list(bookmark.tags.all().all())) class MultiTableInheritanceTest(TestCase): @classmethod def setUpTestData(cls): cls.book1 = BookWithYear.objects.create(title='Poems', published_year=2010) cls.book2 = BookWithYear.objects.create(title='More poems', published_year=2011) cls.author1 = AuthorWithAge.objects.create(name='Jane', first_book=cls.book1, age=50) cls.author2 = AuthorWithAge.objects.create(name='Tom', first_book=cls.book1, age=49) cls.author3 = AuthorWithAge.objects.create(name='Robert', first_book=cls.book2, age=48) cls.author_address = AuthorAddress.objects.create(author=cls.author1, address='SomeStreet 1') cls.book2.aged_authors.add(cls.author2, cls.author3) cls.br1 = BookReview.objects.create(book=cls.book1, notes='review book1') cls.br2 = BookReview.objects.create(book=cls.book2, notes='review book2') def test_foreignkey(self): with self.assertNumQueries(2): qs = AuthorWithAge.objects.prefetch_related('addresses') addresses = [[str(address) for address in obj.addresses.all()] for obj in qs] self.assertEqual(addresses, [[str(self.author_address)], [], []]) def test_foreignkey_to_inherited(self): with self.assertNumQueries(2): qs = BookReview.objects.prefetch_related('book') titles = [obj.book.title for obj in qs] self.assertEqual(titles, ["Poems", "More poems"]) def test_m2m_to_inheriting_model(self): qs = AuthorWithAge.objects.prefetch_related('books_with_year') with self.assertNumQueries(2): lst = [[str(book) for book in author.books_with_year.all()] for author in qs] qs = AuthorWithAge.objects.all() lst2 = [[str(book) for book in author.books_with_year.all()] for author in qs] self.assertEqual(lst, lst2) qs = BookWithYear.objects.prefetch_related('aged_authors') with self.assertNumQueries(2): lst = [[str(author) for author in book.aged_authors.all()] for book in qs] qs = BookWithYear.objects.all() lst2 = [[str(author) for author in book.aged_authors.all()] for book in qs] self.assertEqual(lst, lst2) def test_parent_link_prefetch(self): with self.assertNumQueries(2): [a.author for a in AuthorWithAge.objects.prefetch_related('author')] @override_settings(DEBUG=True) def test_child_link_prefetch(self): with self.assertNumQueries(2): authors = [a.authorwithage for a in Author.objects.prefetch_related('authorwithage')] # Regression for #18090: the prefetching query must include an IN clause. # Note that on Oracle the table name is upper case in the generated SQL, # thus the .lower() call. self.assertIn('authorwithage', connection.queries[-1]['sql'].lower()) self.assertIn(' IN ', connection.queries[-1]['sql']) self.assertEqual(authors, [a.authorwithage for a in Author.objects.all()]) class ForeignKeyToFieldTest(TestCase): @classmethod def setUpTestData(cls): cls.book = Book.objects.create(title='Poems') cls.author1 = Author.objects.create(name='Jane', first_book=cls.book) cls.author2 = Author.objects.create(name='Tom', first_book=cls.book) cls.author3 = Author.objects.create(name='Robert', first_book=cls.book) cls.author_address = AuthorAddress.objects.create(author=cls.author1, address='SomeStreet 1') FavoriteAuthors.objects.create(author=cls.author1, likes_author=cls.author2) FavoriteAuthors.objects.create(author=cls.author2, likes_author=cls.author3) FavoriteAuthors.objects.create(author=cls.author3, likes_author=cls.author1) def test_foreignkey(self): with self.assertNumQueries(2): qs = Author.objects.prefetch_related('addresses') addresses = [[str(address) for address in obj.addresses.all()] for obj in qs] self.assertEqual(addresses, [[str(self.author_address)], [], []]) def test_m2m(self): with self.assertNumQueries(3): qs = Author.objects.all().prefetch_related('favorite_authors', 'favors_me') favorites = [( [str(i_like) for i_like in author.favorite_authors.all()], [str(likes_me) for likes_me in author.favors_me.all()] ) for author in qs] self.assertEqual( favorites, [ ([str(self.author2)], [str(self.author3)]), ([str(self.author3)], [str(self.author1)]), ([str(self.author1)], [str(self.author2)]) ] ) class LookupOrderingTest(TestCase): """ Test cases that demonstrate that ordering of lookups is important, and ensure it is preserved. """ def setUp(self): self.person1 = Person.objects.create(name="Joe") self.person2 = Person.objects.create(name="Mary") # Set main_room for each house before creating the next one for # databases where supports_nullable_unique_constraints is False. self.house1 = House.objects.create(address="123 Main St") self.room1_1 = Room.objects.create(name="Dining room", house=self.house1) self.room1_2 = Room.objects.create(name="Lounge", house=self.house1) self.room1_3 = Room.objects.create(name="Kitchen", house=self.house1) self.house1.main_room = self.room1_1 self.house1.save() self.person1.houses.add(self.house1) self.house2 = House.objects.create(address="45 Side St") self.room2_1 = Room.objects.create(name="Dining room", house=self.house2) self.room2_2 = Room.objects.create(name="Lounge", house=self.house2) self.house2.main_room = self.room2_1 self.house2.save() self.person1.houses.add(self.house2) self.house3 = House.objects.create(address="6 Downing St") self.room3_1 = Room.objects.create(name="Dining room", house=self.house3) self.room3_2 = Room.objects.create(name="Lounge", house=self.house3) self.room3_3 = Room.objects.create(name="Kitchen", house=self.house3) self.house3.main_room = self.room3_1 self.house3.save() self.person2.houses.add(self.house3) self.house4 = House.objects.create(address="7 Regents St") self.room4_1 = Room.objects.create(name="Dining room", house=self.house4) self.room4_2 = Room.objects.create(name="Lounge", house=self.house4) self.house4.main_room = self.room4_1 self.house4.save() self.person2.houses.add(self.house4) def test_order(self): with self.assertNumQueries(4): # The following two queries must be done in the same order as written, # otherwise 'primary_house' will cause non-prefetched lookups qs = Person.objects.prefetch_related('houses__rooms', 'primary_house__occupants') [list(p.primary_house.occupants.all()) for p in qs] class NullableTest(TestCase): @classmethod def setUpTestData(cls): boss = Employee.objects.create(name="Peter") Employee.objects.create(name="Joe", boss=boss) Employee.objects.create(name="Angela", boss=boss) def test_traverse_nullable(self): # Because we use select_related() for 'boss', it doesn't need to be # prefetched, but we can still traverse it although it contains some nulls with self.assertNumQueries(2): qs = Employee.objects.select_related('boss').prefetch_related('boss__serfs') co_serfs = [list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs] qs2 = Employee.objects.select_related('boss') co_serfs2 = [list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs2] self.assertEqual(co_serfs, co_serfs2) def test_prefetch_nullable(self): # One for main employee, one for boss, one for serfs with self.assertNumQueries(3): qs = Employee.objects.prefetch_related('boss__serfs') co_serfs = [list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs] qs2 = Employee.objects.all() co_serfs2 = [list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs2] self.assertEqual(co_serfs, co_serfs2) def test_in_bulk(self): """ In-bulk does correctly prefetch objects by not using .iterator() directly. """ boss1 = Employee.objects.create(name="Peter") boss2 = Employee.objects.create(name="Jack") with self.assertNumQueries(2): # Prefetch is done and it does not cause any errors. bulk = Employee.objects.prefetch_related('serfs').in_bulk([boss1.pk, boss2.pk]) for b in bulk.values(): list(b.serfs.all()) class MultiDbTests(TestCase): databases = {'default', 'other'} def test_using_is_honored_m2m(self): B = Book.objects.using('other') A = Author.objects.using('other') book1 = B.create(title="Poems") book2 = B.create(title="Jane Eyre") book3 = B.create(title="Wuthering Heights") book4 = B.create(title="Sense and Sensibility") author1 = A.create(name="Charlotte", first_book=book1) author2 = A.create(name="Anne", first_book=book1) author3 = A.create(name="Emily", first_book=book1) author4 = A.create(name="Jane", first_book=book4) book1.authors.add(author1, author2, author3) book2.authors.add(author1) book3.authors.add(author3) book4.authors.add(author4) # Forward qs1 = B.prefetch_related('authors') with self.assertNumQueries(2, using='other'): books = "".join("%s (%s)\n" % (book.title, ", ".join(a.name for a in book.authors.all())) for book in qs1) self.assertEqual(books, "Poems (Charlotte, Anne, Emily)\n" "Jane Eyre (Charlotte)\n" "Wuthering Heights (Emily)\n" "Sense and Sensibility (Jane)\n") # Reverse qs2 = A.prefetch_related('books') with self.assertNumQueries(2, using='other'): authors = "".join("%s: %s\n" % (author.name, ", ".join(b.title for b in author.books.all())) for author in qs2) self.assertEqual(authors, "Charlotte: Poems, Jane Eyre\n" "Anne: Poems\n" "Emily: Poems, Wuthering Heights\n" "Jane: Sense and Sensibility\n") def test_using_is_honored_fkey(self): B = Book.objects.using('other') A = Author.objects.using('other') book1 = B.create(title="Poems") book2 = B.create(title="Sense and Sensibility") A.create(name="Charlotte Bronte", first_book=book1) A.create(name="Jane Austen", first_book=book2) # Forward with self.assertNumQueries(2, using='other'): books = ", ".join(a.first_book.title for a in A.prefetch_related('first_book')) self.assertEqual("Poems, Sense and Sensibility", books) # Reverse with self.assertNumQueries(2, using='other'): books = "".join("%s (%s)\n" % (b.title, ", ".join(a.name for a in b.first_time_authors.all())) for b in B.prefetch_related('first_time_authors')) self.assertEqual(books, "Poems (Charlotte Bronte)\n" "Sense and Sensibility (Jane Austen)\n") def test_using_is_honored_inheritance(self): B = BookWithYear.objects.using('other') A = AuthorWithAge.objects.using('other') book1 = B.create(title="Poems", published_year=2010) B.create(title="More poems", published_year=2011) A.create(name='Jane', first_book=book1, age=50) A.create(name='Tom', first_book=book1, age=49) # parent link with self.assertNumQueries(2, using='other'): authors = ", ".join(a.author.name for a in A.prefetch_related('author')) self.assertEqual(authors, "Jane, Tom") # child link with self.assertNumQueries(2, using='other'): ages = ", ".join(str(a.authorwithage.age) for a in A.prefetch_related('authorwithage')) self.assertEqual(ages, "50, 49") def test_using_is_honored_custom_qs(self): B = Book.objects.using('other') A = Author.objects.using('other') book1 = B.create(title="Poems") book2 = B.create(title="Sense and Sensibility") A.create(name="Charlotte Bronte", first_book=book1) A.create(name="Jane Austen", first_book=book2) # Implicit hinting with self.assertNumQueries(2, using='other'): prefetch = Prefetch('first_time_authors', queryset=Author.objects.all()) books = "".join("%s (%s)\n" % (b.title, ", ".join(a.name for a in b.first_time_authors.all())) for b in B.prefetch_related(prefetch)) self.assertEqual(books, "Poems (Charlotte Bronte)\n" "Sense and Sensibility (Jane Austen)\n") # Explicit using on the same db. with self.assertNumQueries(2, using='other'): prefetch = Prefetch('first_time_authors', queryset=Author.objects.using('other')) books = "".join("%s (%s)\n" % (b.title, ", ".join(a.name for a in b.first_time_authors.all())) for b in B.prefetch_related(prefetch)) self.assertEqual(books, "Poems (Charlotte Bronte)\n" "Sense and Sensibility (Jane Austen)\n") # Explicit using on a different db. with self.assertNumQueries(1, using='default'), self.assertNumQueries(1, using='other'): prefetch = Prefetch('first_time_authors', queryset=Author.objects.using('default')) books = "".join("%s (%s)\n" % (b.title, ", ".join(a.name for a in b.first_time_authors.all())) for b in B.prefetch_related(prefetch)) self.assertEqual(books, "Poems ()\n" "Sense and Sensibility ()\n") class Ticket19607Tests(TestCase): def setUp(self): for id, name1, name2 in [ (1, 'einfach', 'simple'), (2, 'schwierig', 'difficult'), ]: LessonEntry.objects.create(id=id, name1=name1, name2=name2) for id, lesson_entry_id, name in [ (1, 1, 'einfach'), (2, 1, 'simple'), (3, 2, 'schwierig'), (4, 2, 'difficult'), ]: WordEntry.objects.create(id=id, lesson_entry_id=lesson_entry_id, name=name) def test_bug(self): list(WordEntry.objects.prefetch_related('lesson_entry', 'lesson_entry__wordentry_set')) class Ticket21410Tests(TestCase): def setUp(self): self.book1 = Book.objects.create(title="Poems") self.book2 = Book.objects.create(title="Jane Eyre") self.book3 = Book.objects.create(title="Wuthering Heights") self.book4 = Book.objects.create(title="Sense and Sensibility") self.author1 = Author2.objects.create(name="Charlotte", first_book=self.book1) self.author2 = Author2.objects.create(name="Anne", first_book=self.book1) self.author3 = Author2.objects.create(name="Emily", first_book=self.book1) self.author4 = Author2.objects.create(name="Jane", first_book=self.book4) self.author1.favorite_books.add(self.book1, self.book2, self.book3) self.author2.favorite_books.add(self.book1) self.author3.favorite_books.add(self.book2) self.author4.favorite_books.add(self.book3) def test_bug(self): list(Author2.objects.prefetch_related('first_book', 'favorite_books')) class Ticket21760Tests(TestCase): def setUp(self): self.rooms = [] for _ in range(3): house = House.objects.create() for _ in range(3): self.rooms.append(Room.objects.create(house=house)) # Set main_room for each house before creating the next one for # databases where supports_nullable_unique_constraints is False. house.main_room = self.rooms[-3] house.save() def test_bug(self): prefetcher = get_prefetcher(self.rooms[0], 'house', 'house')[0] queryset = prefetcher.get_prefetch_queryset(list(Room.objects.all()))[0] self.assertNotIn(' JOIN ', str(queryset.query)) class DirectPrefetchedObjectCacheReuseTests(TestCase): """ prefetch_related() reuses objects fetched in _prefetched_objects_cache. When objects are prefetched and not stored as an instance attribute (often intermediary relationships), they are saved to the _prefetched_objects_cache attribute. prefetch_related() takes _prefetched_objects_cache into account when determining whether an object has been fetched[1] and retrieves results from it when it is populated [2]. [1]: #25546 (duplicate queries on nested Prefetch) [2]: #27554 (queryset evaluation fails with a mix of nested and flattened prefetches) """ @classmethod def setUpTestData(cls): cls.book1, cls.book2 = [ Book.objects.create(title='book1'), Book.objects.create(title='book2'), ] cls.author11, cls.author12, cls.author21 = [ Author.objects.create(first_book=cls.book1, name='Author11'), Author.objects.create(first_book=cls.book1, name='Author12'), Author.objects.create(first_book=cls.book2, name='Author21'), ] cls.author1_address1, cls.author1_address2, cls.author2_address1 = [ AuthorAddress.objects.create(author=cls.author11, address='Happy place'), AuthorAddress.objects.create(author=cls.author12, address='Haunted house'), AuthorAddress.objects.create(author=cls.author21, address='Happy place'), ] cls.bookwithyear1 = BookWithYear.objects.create(title='Poems', published_year=2010) cls.bookreview1 = BookReview.objects.create(book=cls.bookwithyear1) def test_detect_is_fetched(self): """ Nested prefetch_related() shouldn't trigger duplicate queries for the same lookup. """ with self.assertNumQueries(3): books = Book.objects.filter( title__in=['book1', 'book2'], ).prefetch_related( Prefetch( 'first_time_authors', Author.objects.prefetch_related( Prefetch( 'addresses', AuthorAddress.objects.filter(address='Happy place'), ) ), ), ) book1, book2 = list(books) with self.assertNumQueries(0): self.assertSequenceEqual(book1.first_time_authors.all(), [self.author11, self.author12]) self.assertSequenceEqual(book2.first_time_authors.all(), [self.author21]) self.assertSequenceEqual(book1.first_time_authors.all()[0].addresses.all(), [self.author1_address1]) self.assertSequenceEqual(book1.first_time_authors.all()[1].addresses.all(), []) self.assertSequenceEqual(book2.first_time_authors.all()[0].addresses.all(), [self.author2_address1]) self.assertEqual( list(book1.first_time_authors.all()), list(book1.first_time_authors.all().all()) ) self.assertEqual( list(book2.first_time_authors.all()), list(book2.first_time_authors.all().all()) ) self.assertEqual( list(book1.first_time_authors.all()[0].addresses.all()), list(book1.first_time_authors.all()[0].addresses.all().all()) ) self.assertEqual( list(book1.first_time_authors.all()[1].addresses.all()), list(book1.first_time_authors.all()[1].addresses.all().all()) ) self.assertEqual( list(book2.first_time_authors.all()[0].addresses.all()), list(book2.first_time_authors.all()[0].addresses.all().all()) ) def test_detect_is_fetched_with_to_attr(self): with self.assertNumQueries(3): books = Book.objects.filter( title__in=['book1', 'book2'], ).prefetch_related( Prefetch( 'first_time_authors', Author.objects.prefetch_related( Prefetch( 'addresses', AuthorAddress.objects.filter(address='Happy place'), to_attr='happy_place', ) ), to_attr='first_authors', ), ) book1, book2 = list(books) with self.assertNumQueries(0): self.assertEqual(book1.first_authors, [self.author11, self.author12]) self.assertEqual(book2.first_authors, [self.author21]) self.assertEqual(book1.first_authors[0].happy_place, [self.author1_address1]) self.assertEqual(book1.first_authors[1].happy_place, []) self.assertEqual(book2.first_authors[0].happy_place, [self.author2_address1]) def test_prefetch_reverse_foreign_key(self): with self.assertNumQueries(2): bookwithyear1, = BookWithYear.objects.prefetch_related('bookreview_set') with self.assertNumQueries(0): self.assertCountEqual(bookwithyear1.bookreview_set.all(), [self.bookreview1]) with self.assertNumQueries(0): prefetch_related_objects([bookwithyear1], 'bookreview_set') def test_add_clears_prefetched_objects(self): bookwithyear = BookWithYear.objects.get(pk=self.bookwithyear1.pk) prefetch_related_objects([bookwithyear], 'bookreview_set') self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1]) new_review = BookReview.objects.create() bookwithyear.bookreview_set.add(new_review) self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1, new_review]) def test_remove_clears_prefetched_objects(self): bookwithyear = BookWithYear.objects.get(pk=self.bookwithyear1.pk) prefetch_related_objects([bookwithyear], 'bookreview_set') self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1]) bookwithyear.bookreview_set.remove(self.bookreview1) self.assertCountEqual(bookwithyear.bookreview_set.all(), []) class ReadPrefetchedObjectsCacheTests(TestCase): @classmethod def setUpTestData(cls): cls.book1 = Book.objects.create(title='Les confessions Volume I') cls.book2 = Book.objects.create(title='Candide') cls.author1 = AuthorWithAge.objects.create(name='Rousseau', first_book=cls.book1, age=70) cls.author2 = AuthorWithAge.objects.create(name='Voltaire', first_book=cls.book2, age=65) cls.book1.authors.add(cls.author1) cls.book2.authors.add(cls.author2) FavoriteAuthors.objects.create(author=cls.author1, likes_author=cls.author2) def test_retrieves_results_from_prefetched_objects_cache(self): """ When intermediary results are prefetched without a destination attribute, they are saved in the RelatedManager's cache (_prefetched_objects_cache). prefetch_related() uses this cache (#27554). """ authors = AuthorWithAge.objects.prefetch_related( Prefetch( 'author', queryset=Author.objects.prefetch_related( # Results are saved in the RelatedManager's cache # (_prefetched_objects_cache) and do not replace the # RelatedManager on Author instances (favorite_authors) Prefetch('favorite_authors__first_book'), ), ), ) with self.assertNumQueries(4): # AuthorWithAge -> Author -> FavoriteAuthors, Book self.assertQuerysetEqual(authors, ['<AuthorWithAge: Rousseau>', '<AuthorWithAge: Voltaire>'])
256f09fa360ba8abcdc8702acdb1ab7db87fb6ccb8ce0e436e1792243fbbbf2d
from unittest import mock, skipUnless from django.db import connection from django.db.models import Index from django.db.utils import DatabaseError from django.test import TransactionTestCase, skipUnlessDBFeature from .models import ( Article, ArticleReporter, CheckConstraintModel, City, Comment, Country, District, Reporter, ) class IntrospectionTests(TransactionTestCase): available_apps = ['introspection'] def test_table_names(self): tl = connection.introspection.table_names() self.assertEqual(tl, sorted(tl)) self.assertIn(Reporter._meta.db_table, tl, "'%s' isn't in table_list()." % Reporter._meta.db_table) self.assertIn(Article._meta.db_table, tl, "'%s' isn't in table_list()." % Article._meta.db_table) def test_django_table_names(self): with connection.cursor() as cursor: cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);') tl = connection.introspection.django_table_names() cursor.execute("DROP TABLE django_ixn_test_table;") self.assertNotIn('django_ixn_test_table', tl, "django_table_names() returned a non-Django table") def test_django_table_names_retval_type(self): # Table name is a list #15216 tl = connection.introspection.django_table_names(only_existing=True) self.assertIs(type(tl), list) tl = connection.introspection.django_table_names(only_existing=False) self.assertIs(type(tl), list) def test_table_names_with_views(self): with connection.cursor() as cursor: try: cursor.execute( 'CREATE VIEW introspection_article_view AS SELECT headline ' 'from introspection_article;') except DatabaseError as e: if 'insufficient privileges' in str(e): self.fail("The test user has no CREATE VIEW privileges") else: raise try: self.assertIn('introspection_article_view', connection.introspection.table_names(include_views=True)) self.assertNotIn('introspection_article_view', connection.introspection.table_names()) finally: with connection.cursor() as cursor: cursor.execute('DROP VIEW introspection_article_view') def test_unmanaged_through_model(self): tables = connection.introspection.django_table_names() self.assertNotIn(ArticleReporter._meta.db_table, tables) def test_installed_models(self): tables = [Article._meta.db_table, Reporter._meta.db_table] models = connection.introspection.installed_models(tables) self.assertEqual(models, {Article, Reporter}) def test_sequence_list(self): sequences = connection.introspection.sequence_list() reporter_seqs = [seq for seq in sequences if seq['table'] == Reporter._meta.db_table] self.assertEqual(len(reporter_seqs), 1, 'Reporter sequence not found in sequence_list()') self.assertEqual(reporter_seqs[0]['column'], 'id') def test_get_table_description_names(self): with connection.cursor() as cursor: desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table) self.assertEqual([r[0] for r in desc], [f.column for f in Reporter._meta.fields]) def test_get_table_description_types(self): with connection.cursor() as cursor: desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table) self.assertEqual( [connection.introspection.get_field_type(r[1], r) for r in desc], [ 'AutoField' if connection.features.can_introspect_autofield else 'IntegerField', 'CharField', 'CharField', 'CharField', 'BigIntegerField' if connection.features.can_introspect_big_integer_field else 'IntegerField', 'BinaryField' if connection.features.can_introspect_binary_field else 'TextField', 'SmallIntegerField' if connection.features.can_introspect_small_integer_field else 'IntegerField', 'DurationField' if connection.features.can_introspect_duration_field else 'BigIntegerField', ] ) def test_get_table_description_col_lengths(self): with connection.cursor() as cursor: desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table) self.assertEqual( [r[3] for r in desc if connection.introspection.get_field_type(r[1], r) == 'CharField'], [30, 30, 254] ) def test_get_table_description_nullable(self): with connection.cursor() as cursor: desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table) nullable_by_backend = connection.features.interprets_empty_strings_as_nulls self.assertEqual( [r[6] for r in desc], [False, nullable_by_backend, nullable_by_backend, nullable_by_backend, True, True, False, False] ) @skipUnlessDBFeature('can_introspect_autofield') def test_bigautofield(self): with connection.cursor() as cursor: desc = connection.introspection.get_table_description(cursor, City._meta.db_table) self.assertIn( connection.features.introspected_big_auto_field_type, [connection.introspection.get_field_type(r[1], r) for r in desc], ) @skipUnlessDBFeature('can_introspect_autofield') def test_smallautofield(self): with connection.cursor() as cursor: desc = connection.introspection.get_table_description(cursor, Country._meta.db_table) self.assertIn( connection.features.introspected_small_auto_field_type, [connection.introspection.get_field_type(r[1], r) for r in desc], ) # Regression test for #9991 - 'real' types in postgres @skipUnlessDBFeature('has_real_datatype') def test_postgresql_real_type(self): with connection.cursor() as cursor: cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);") desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table') cursor.execute('DROP TABLE django_ixn_real_test_table;') self.assertEqual(connection.introspection.get_field_type(desc[0][1], desc[0]), 'FloatField') @skipUnlessDBFeature('can_introspect_foreign_keys') def test_get_relations(self): with connection.cursor() as cursor: relations = connection.introspection.get_relations(cursor, Article._meta.db_table) # That's {field_name: (field_name_other_table, other_table)} expected_relations = { 'reporter_id': ('id', Reporter._meta.db_table), 'response_to_id': ('id', Article._meta.db_table), } self.assertEqual(relations, expected_relations) # Removing a field shouldn't disturb get_relations (#17785) body = Article._meta.get_field('body') with connection.schema_editor() as editor: editor.remove_field(Article, body) with connection.cursor() as cursor: relations = connection.introspection.get_relations(cursor, Article._meta.db_table) with connection.schema_editor() as editor: editor.add_field(Article, body) self.assertEqual(relations, expected_relations) @skipUnless(connection.vendor == 'sqlite', "This is an sqlite-specific issue") def test_get_relations_alt_format(self): """ With SQLite, foreign keys can be added with different syntaxes and formatting. """ create_table_statements = [ "CREATE TABLE track(id, art_id INTEGER, FOREIGN KEY(art_id) REFERENCES {}(id));", "CREATE TABLE track(id, art_id INTEGER, FOREIGN KEY (art_id) REFERENCES {}(id));" ] for statement in create_table_statements: with connection.cursor() as cursor: cursor.fetchone = mock.Mock(return_value=[statement.format(Article._meta.db_table), 'table']) relations = connection.introspection.get_relations(cursor, 'mocked_table') self.assertEqual(relations, {'art_id': ('id', Article._meta.db_table)}) @skipUnlessDBFeature('can_introspect_foreign_keys') def test_get_key_columns(self): with connection.cursor() as cursor: key_columns = connection.introspection.get_key_columns(cursor, Article._meta.db_table) self.assertEqual(set(key_columns), { ('reporter_id', Reporter._meta.db_table, 'id'), ('response_to_id', Article._meta.db_table, 'id'), }) def test_get_primary_key_column(self): with connection.cursor() as cursor: primary_key_column = connection.introspection.get_primary_key_column(cursor, Article._meta.db_table) pk_fk_column = connection.introspection.get_primary_key_column(cursor, District._meta.db_table) self.assertEqual(primary_key_column, 'id') self.assertEqual(pk_fk_column, 'city_id') def test_get_constraints_index_types(self): with connection.cursor() as cursor: constraints = connection.introspection.get_constraints(cursor, Article._meta.db_table) index = {} index2 = {} for val in constraints.values(): if val['columns'] == ['headline', 'pub_date']: index = val if val['columns'] == ['headline', 'response_to_id', 'pub_date', 'reporter_id']: index2 = val self.assertEqual(index['type'], Index.suffix) self.assertEqual(index2['type'], Index.suffix) @skipUnlessDBFeature('supports_index_column_ordering') def test_get_constraints_indexes_orders(self): """ Indexes have the 'orders' key with a list of 'ASC'/'DESC' values. """ with connection.cursor() as cursor: constraints = connection.introspection.get_constraints(cursor, Article._meta.db_table) indexes_verified = 0 expected_columns = [ ['reporter_id'], ['headline', 'pub_date'], ['response_to_id'], ['headline', 'response_to_id', 'pub_date', 'reporter_id'], ] for val in constraints.values(): if val['index'] and not (val['primary_key'] or val['unique']): self.assertIn(val['columns'], expected_columns) self.assertEqual(val['orders'], ['ASC'] * len(val['columns'])) indexes_verified += 1 self.assertEqual(indexes_verified, 4) def test_get_constraints(self): def assertDetails(details, cols, primary_key=False, unique=False, index=False, check=False, foreign_key=None): # Different backends have different values for same constraints: # PRIMARY KEY UNIQUE CONSTRAINT UNIQUE INDEX # MySQL pk=1 uniq=1 idx=1 pk=0 uniq=1 idx=1 pk=0 uniq=1 idx=1 # PostgreSQL pk=1 uniq=1 idx=0 pk=0 uniq=1 idx=0 pk=0 uniq=1 idx=1 # SQLite pk=1 uniq=0 idx=0 pk=0 uniq=1 idx=0 pk=0 uniq=1 idx=1 if details['primary_key']: details['unique'] = True if details['unique']: details['index'] = False self.assertEqual(details['columns'], cols) self.assertEqual(details['primary_key'], primary_key) self.assertEqual(details['unique'], unique) self.assertEqual(details['index'], index) self.assertEqual(details['check'], check) self.assertEqual(details['foreign_key'], foreign_key) # Test custom constraints custom_constraints = { 'article_email_pub_date_uniq', 'email_pub_date_idx', } with connection.cursor() as cursor: constraints = connection.introspection.get_constraints(cursor, Comment._meta.db_table) if ( connection.features.supports_column_check_constraints and connection.features.can_introspect_check_constraints ): constraints.update( connection.introspection.get_constraints(cursor, CheckConstraintModel._meta.db_table) ) custom_constraints.add('up_votes_gte_0_check') assertDetails(constraints['up_votes_gte_0_check'], ['up_votes'], check=True) assertDetails(constraints['article_email_pub_date_uniq'], ['article_id', 'email', 'pub_date'], unique=True) assertDetails(constraints['email_pub_date_idx'], ['email', 'pub_date'], index=True) # Test field constraints field_constraints = set() for name, details in constraints.items(): if name in custom_constraints: continue elif details['columns'] == ['up_votes'] and details['check']: assertDetails(details, ['up_votes'], check=True) field_constraints.add(name) elif details['columns'] == ['voting_number'] and details['check']: assertDetails(details, ['voting_number'], check=True) field_constraints.add(name) elif details['columns'] == ['ref'] and details['unique']: assertDetails(details, ['ref'], unique=True) field_constraints.add(name) elif details['columns'] == ['voting_number'] and details['unique']: assertDetails(details, ['voting_number'], unique=True) field_constraints.add(name) elif details['columns'] == ['article_id'] and details['index']: assertDetails(details, ['article_id'], index=True) field_constraints.add(name) elif details['columns'] == ['id'] and details['primary_key']: assertDetails(details, ['id'], primary_key=True, unique=True) field_constraints.add(name) elif details['columns'] == ['article_id'] and details['foreign_key']: assertDetails(details, ['article_id'], foreign_key=('introspection_article', 'id')) field_constraints.add(name) elif details['check']: # Some databases (e.g. Oracle) include additional check # constraints. field_constraints.add(name) # All constraints are accounted for. self.assertEqual(constraints.keys() ^ (custom_constraints | field_constraints), set())
606c2d65f706d0e9776068edb9c5029670b7871ceffe3763a176442218540d05
from django.db import models class City(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=50) def __str__(self): return self.name class Country(models.Model): id = models.SmallAutoField(primary_key=True) name = models.CharField(max_length=50) class District(models.Model): city = models.ForeignKey(City, models.CASCADE, primary_key=True) name = models.CharField(max_length=50) def __str__(self): return self.name class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() facebook_user_id = models.BigIntegerField(null=True) raw_data = models.BinaryField(null=True) small_int = models.SmallIntegerField() interval = models.DurationField() class Meta: unique_together = ('first_name', 'last_name') def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() body = models.TextField(default='') reporter = models.ForeignKey(Reporter, models.CASCADE) response_to = models.ForeignKey('self', models.SET_NULL, null=True) unmanaged_reporters = models.ManyToManyField(Reporter, through='ArticleReporter', related_name='+') class Meta: ordering = ('headline',) index_together = [ ["headline", "pub_date"], ['headline', 'response_to', 'pub_date', 'reporter'], ] def __str__(self): return self.headline class ArticleReporter(models.Model): article = models.ForeignKey(Article, models.CASCADE) reporter = models.ForeignKey(Reporter, models.CASCADE) class Meta: managed = False class Comment(models.Model): ref = models.UUIDField(unique=True) article = models.ForeignKey(Article, models.CASCADE, db_index=True) email = models.EmailField() pub_date = models.DateTimeField() body = models.TextField() class Meta: constraints = [ models.UniqueConstraint(fields=['article', 'email', 'pub_date'], name='article_email_pub_date_uniq'), ] indexes = [ models.Index(fields=['email', 'pub_date'], name='email_pub_date_idx'), ] class CheckConstraintModel(models.Model): up_votes = models.PositiveIntegerField() voting_number = models.PositiveIntegerField(unique=True) class Meta: required_db_features = { 'supports_table_check_constraints', } constraints = [ models.CheckConstraint(name='up_votes_gte_0_check', check=models.Q(up_votes__gte=0)), ]
2023337c7e9ea73fea12a393e0e1c1a46f6eeb634090b19b84279506768430f2
import datetime import decimal import gettext as gettext_module import os import pickle import re import tempfile from contextlib import contextmanager from importlib import import_module from pathlib import Path from unittest import mock from asgiref.local import Local from django import forms from django.apps import AppConfig from django.conf import settings from django.conf.locale import LANG_INFO from django.conf.urls.i18n import i18n_patterns from django.template import Context, Template from django.test import ( RequestFactory, SimpleTestCase, TestCase, override_settings, ) from django.utils import translation from django.utils.deprecation import RemovedInDjango40Warning from django.utils.formats import ( date_format, get_format, get_format_modules, iter_format_modules, localize, localize_input, reset_format_cache, sanitize_separators, time_format, ) from django.utils.numberformat import format as nformat from django.utils.safestring import SafeString, mark_safe from django.utils.translation import ( LANGUAGE_SESSION_KEY, activate, check_for_language, deactivate, get_language, get_language_bidi, get_language_from_request, get_language_info, gettext, gettext_lazy, ngettext, ngettext_lazy, npgettext, npgettext_lazy, pgettext, round_away_from_one, to_language, to_locale, trans_null, trans_real, ugettext, ugettext_lazy, ugettext_noop, ungettext, ungettext_lazy, ) from django.utils.translation.reloader import ( translation_file_changed, watch_for_translation_changes, ) from .forms import CompanyForm, I18nForm, SelectDateForm from .models import Company, TestModel here = os.path.dirname(os.path.abspath(__file__)) extended_locale_paths = settings.LOCALE_PATHS + [ os.path.join(here, 'other', 'locale'), ] class AppModuleStub: def __init__(self, **kwargs): self.__dict__.update(kwargs) @contextmanager def patch_formats(lang, **settings): from django.utils.formats import _format_cache # Populate _format_cache with temporary values for key, value in settings.items(): _format_cache[(key, lang)] = value try: yield finally: reset_format_cache() class TranslationTests(SimpleTestCase): @translation.override('de') def test_legacy_aliases(self): """ Pre-Django 2.0 aliases with u prefix are still available. """ msg = ( 'django.utils.translation.ugettext_noop() is deprecated in favor ' 'of django.utils.translation.gettext_noop().' ) with self.assertWarnsMessage(RemovedInDjango40Warning, msg): self.assertEqual(ugettext_noop("Image"), "Image") msg = ( 'django.utils.translation.ugettext() is deprecated in favor of ' 'django.utils.translation.gettext().' ) with self.assertWarnsMessage(RemovedInDjango40Warning, msg): self.assertEqual(ugettext("Image"), "Bild") msg = ( 'django.utils.translation.ugettext_lazy() is deprecated in favor ' 'of django.utils.translation.gettext_lazy().' ) with self.assertWarnsMessage(RemovedInDjango40Warning, msg): self.assertEqual(ugettext_lazy("Image"), gettext_lazy("Image")) msg = ( 'django.utils.translation.ungettext() is deprecated in favor of ' 'django.utils.translation.ngettext().' ) with self.assertWarnsMessage(RemovedInDjango40Warning, msg): self.assertEqual(ungettext("%d year", "%d years", 0) % 0, "0 Jahre") msg = ( 'django.utils.translation.ungettext_lazy() is deprecated in favor ' 'of django.utils.translation.ngettext_lazy().' ) with self.assertWarnsMessage(RemovedInDjango40Warning, msg): self.assertEqual( ungettext_lazy("%d year", "%d years", 0) % 0, ngettext_lazy("%d year", "%d years", 0) % 0, ) @translation.override('fr') def test_plural(self): """ Test plurals with ngettext. French differs from English in that 0 is singular. """ self.assertEqual(ngettext("%d year", "%d years", 0) % 0, "0 année") self.assertEqual(ngettext("%d year", "%d years", 2) % 2, "2 années") self.assertEqual(ngettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0}, "0 octet") self.assertEqual(ngettext("%(size)d byte", "%(size)d bytes", 2) % {'size': 2}, "2 octets") def test_plural_null(self): g = trans_null.ngettext self.assertEqual(g('%d year', '%d years', 0) % 0, '0 years') self.assertEqual(g('%d year', '%d years', 1) % 1, '1 year') self.assertEqual(g('%d year', '%d years', 2) % 2, '2 years') def test_override(self): activate('de') try: with translation.override('pl'): self.assertEqual(get_language(), 'pl') self.assertEqual(get_language(), 'de') with translation.override(None): self.assertIsNone(get_language()) with translation.override('pl'): pass self.assertIsNone(get_language()) self.assertEqual(get_language(), 'de') finally: deactivate() def test_override_decorator(self): @translation.override('pl') def func_pl(): self.assertEqual(get_language(), 'pl') @translation.override(None) def func_none(): self.assertIsNone(get_language()) try: activate('de') func_pl() self.assertEqual(get_language(), 'de') func_none() self.assertEqual(get_language(), 'de') finally: deactivate() def test_override_exit(self): """ The language restored is the one used when the function was called, not the one used when the decorator was initialized (#23381). """ activate('fr') @translation.override('pl') def func_pl(): pass deactivate() try: activate('en') func_pl() self.assertEqual(get_language(), 'en') finally: deactivate() def test_lazy_objects(self): """ Format string interpolation should work with *_lazy objects. """ s = gettext_lazy('Add %(name)s') d = {'name': 'Ringo'} self.assertEqual('Add Ringo', s % d) with translation.override('de', deactivate=True): self.assertEqual('Ringo hinzuf\xfcgen', s % d) with translation.override('pl'): self.assertEqual('Dodaj Ringo', s % d) # It should be possible to compare *_lazy objects. s1 = gettext_lazy('Add %(name)s') self.assertEqual(s, s1) s2 = gettext_lazy('Add %(name)s') s3 = gettext_lazy('Add %(name)s') self.assertEqual(s2, s3) self.assertEqual(s, s2) s4 = gettext_lazy('Some other string') self.assertNotEqual(s, s4) def test_lazy_pickle(self): s1 = gettext_lazy("test") self.assertEqual(str(s1), "test") s2 = pickle.loads(pickle.dumps(s1)) self.assertEqual(str(s2), "test") @override_settings(LOCALE_PATHS=extended_locale_paths) def test_ngettext_lazy(self): simple_with_format = ngettext_lazy('%d good result', '%d good results') simple_context_with_format = npgettext_lazy('Exclamation', '%d good result', '%d good results') simple_without_format = ngettext_lazy('good result', 'good results') with translation.override('de'): self.assertEqual(simple_with_format % 1, '1 gutes Resultat') self.assertEqual(simple_with_format % 4, '4 guten Resultate') self.assertEqual(simple_context_with_format % 1, '1 gutes Resultat!') self.assertEqual(simple_context_with_format % 4, '4 guten Resultate!') self.assertEqual(simple_without_format % 1, 'gutes Resultat') self.assertEqual(simple_without_format % 4, 'guten Resultate') complex_nonlazy = ngettext_lazy('Hi %(name)s, %(num)d good result', 'Hi %(name)s, %(num)d good results', 4) complex_deferred = ngettext_lazy( 'Hi %(name)s, %(num)d good result', 'Hi %(name)s, %(num)d good results', 'num' ) complex_context_nonlazy = npgettext_lazy( 'Greeting', 'Hi %(name)s, %(num)d good result', 'Hi %(name)s, %(num)d good results', 4 ) complex_context_deferred = npgettext_lazy( 'Greeting', 'Hi %(name)s, %(num)d good result', 'Hi %(name)s, %(num)d good results', 'num' ) with translation.override('de'): self.assertEqual(complex_nonlazy % {'num': 4, 'name': 'Jim'}, 'Hallo Jim, 4 guten Resultate') self.assertEqual(complex_deferred % {'name': 'Jim', 'num': 1}, 'Hallo Jim, 1 gutes Resultat') self.assertEqual(complex_deferred % {'name': 'Jim', 'num': 5}, 'Hallo Jim, 5 guten Resultate') with self.assertRaisesMessage(KeyError, 'Your dictionary lacks key'): complex_deferred % {'name': 'Jim'} self.assertEqual(complex_context_nonlazy % {'num': 4, 'name': 'Jim'}, 'Willkommen Jim, 4 guten Resultate') self.assertEqual(complex_context_deferred % {'name': 'Jim', 'num': 1}, 'Willkommen Jim, 1 gutes Resultat') self.assertEqual(complex_context_deferred % {'name': 'Jim', 'num': 5}, 'Willkommen Jim, 5 guten Resultate') with self.assertRaisesMessage(KeyError, 'Your dictionary lacks key'): complex_context_deferred % {'name': 'Jim'} @override_settings(LOCALE_PATHS=extended_locale_paths) def test_ngettext_lazy_format_style(self): simple_with_format = ngettext_lazy('{} good result', '{} good results') simple_context_with_format = npgettext_lazy('Exclamation', '{} good result', '{} good results') with translation.override('de'): self.assertEqual(simple_with_format.format(1), '1 gutes Resultat') self.assertEqual(simple_with_format.format(4), '4 guten Resultate') self.assertEqual(simple_context_with_format.format(1), '1 gutes Resultat!') self.assertEqual(simple_context_with_format.format(4), '4 guten Resultate!') complex_nonlazy = ngettext_lazy('Hi {name}, {num} good result', 'Hi {name}, {num} good results', 4) complex_deferred = ngettext_lazy( 'Hi {name}, {num} good result', 'Hi {name}, {num} good results', 'num' ) complex_context_nonlazy = npgettext_lazy( 'Greeting', 'Hi {name}, {num} good result', 'Hi {name}, {num} good results', 4 ) complex_context_deferred = npgettext_lazy( 'Greeting', 'Hi {name}, {num} good result', 'Hi {name}, {num} good results', 'num' ) with translation.override('de'): self.assertEqual(complex_nonlazy.format(num=4, name='Jim'), 'Hallo Jim, 4 guten Resultate') self.assertEqual(complex_deferred.format(name='Jim', num=1), 'Hallo Jim, 1 gutes Resultat') self.assertEqual(complex_deferred.format(name='Jim', num=5), 'Hallo Jim, 5 guten Resultate') with self.assertRaisesMessage(KeyError, 'Your dictionary lacks key'): complex_deferred.format(name='Jim') self.assertEqual(complex_context_nonlazy.format(num=4, name='Jim'), 'Willkommen Jim, 4 guten Resultate') self.assertEqual(complex_context_deferred.format(name='Jim', num=1), 'Willkommen Jim, 1 gutes Resultat') self.assertEqual(complex_context_deferred.format(name='Jim', num=5), 'Willkommen Jim, 5 guten Resultate') with self.assertRaisesMessage(KeyError, 'Your dictionary lacks key'): complex_context_deferred.format(name='Jim') def test_ngettext_lazy_bool(self): self.assertTrue(ngettext_lazy('%d good result', '%d good results')) self.assertFalse(ngettext_lazy('', '')) def test_ngettext_lazy_pickle(self): s1 = ngettext_lazy('%d good result', '%d good results') self.assertEqual(s1 % 1, '1 good result') self.assertEqual(s1 % 8, '8 good results') s2 = pickle.loads(pickle.dumps(s1)) self.assertEqual(s2 % 1, '1 good result') self.assertEqual(s2 % 8, '8 good results') @override_settings(LOCALE_PATHS=extended_locale_paths) def test_pgettext(self): trans_real._active = Local() trans_real._translations = {} with translation.override('de'): self.assertEqual(pgettext("unexisting", "May"), "May") self.assertEqual(pgettext("month name", "May"), "Mai") self.assertEqual(pgettext("verb", "May"), "Kann") self.assertEqual(npgettext("search", "%d result", "%d results", 4) % 4, "4 Resultate") def test_empty_value(self): """Empty value must stay empty after being translated (#23196).""" with translation.override('de'): self.assertEqual('', gettext('')) s = mark_safe('') self.assertEqual(s, gettext(s)) @override_settings(LOCALE_PATHS=extended_locale_paths) def test_safe_status(self): """ Translating a string requiring no auto-escaping with gettext or pgettext shouldn't change the "safe" status. """ trans_real._active = Local() trans_real._translations = {} s1 = mark_safe('Password') s2 = mark_safe('May') with translation.override('de', deactivate=True): self.assertIs(type(gettext(s1)), SafeString) self.assertIs(type(pgettext('month name', s2)), SafeString) self.assertEqual('aPassword', SafeString('a') + s1) self.assertEqual('Passworda', s1 + SafeString('a')) self.assertEqual('Passworda', s1 + mark_safe('a')) self.assertEqual('aPassword', mark_safe('a') + s1) self.assertEqual('as', mark_safe('a') + mark_safe('s')) def test_maclines(self): """ Translations on files with Mac or DOS end of lines will be converted to unix EOF in .po catalogs. """ ca_translation = trans_real.translation('ca') ca_translation._catalog['Mac\nEOF\n'] = 'Catalan Mac\nEOF\n' ca_translation._catalog['Win\nEOF\n'] = 'Catalan Win\nEOF\n' with translation.override('ca', deactivate=True): self.assertEqual('Catalan Mac\nEOF\n', gettext('Mac\rEOF\r')) self.assertEqual('Catalan Win\nEOF\n', gettext('Win\r\nEOF\r\n')) def test_to_locale(self): tests = ( ('en', 'en'), ('EN', 'en'), ('en-us', 'en_US'), ('EN-US', 'en_US'), # With > 2 characters after the dash. ('sr-latn', 'sr_Latn'), ('sr-LATN', 'sr_Latn'), # With private use subtag (x-informal). ('nl-nl-x-informal', 'nl_NL-x-informal'), ('NL-NL-X-INFORMAL', 'nl_NL-x-informal'), ('sr-latn-x-informal', 'sr_Latn-x-informal'), ('SR-LATN-X-INFORMAL', 'sr_Latn-x-informal'), ) for lang, locale in tests: with self.subTest(lang=lang): self.assertEqual(to_locale(lang), locale) def test_to_language(self): self.assertEqual(to_language('en_US'), 'en-us') self.assertEqual(to_language('sr_Lat'), 'sr-lat') def test_language_bidi(self): self.assertIs(get_language_bidi(), False) with translation.override(None): self.assertIs(get_language_bidi(), False) def test_language_bidi_null(self): self.assertIs(trans_null.get_language_bidi(), False) with override_settings(LANGUAGE_CODE='he'): self.assertIs(get_language_bidi(), True) class TranslationThreadSafetyTests(SimpleTestCase): def setUp(self): self._old_language = get_language() self._translations = trans_real._translations # here we rely on .split() being called inside the _fetch() # in trans_real.translation() class sideeffect_str(str): def split(self, *args, **kwargs): res = str.split(self, *args, **kwargs) trans_real._translations['en-YY'] = None return res trans_real._translations = {sideeffect_str('en-XX'): None} def tearDown(self): trans_real._translations = self._translations activate(self._old_language) def test_bug14894_translation_activate_thread_safety(self): translation_count = len(trans_real._translations) # May raise RuntimeError if translation.activate() isn't thread-safe. translation.activate('pl') # make sure sideeffect_str actually added a new translation self.assertLess(translation_count, len(trans_real._translations)) @override_settings(USE_L10N=True) class FormattingTests(SimpleTestCase): def setUp(self): super().setUp() self.n = decimal.Decimal('66666.666') self.f = 99999.999 self.d = datetime.date(2009, 12, 31) self.dt = datetime.datetime(2009, 12, 31, 20, 50) self.t = datetime.time(10, 15, 48) self.long = 10000 self.ctxt = Context({ 'n': self.n, 't': self.t, 'd': self.d, 'dt': self.dt, 'f': self.f, 'l': self.long, }) def test_all_format_strings(self): all_locales = LANG_INFO.keys() some_date = datetime.date(2017, 10, 14) some_datetime = datetime.datetime(2017, 10, 14, 10, 23) for locale in all_locales: with self.subTest(locale=locale), translation.override(locale): self.assertIn('2017', date_format(some_date)) # Uses DATE_FORMAT by default self.assertIn('23', time_format(some_datetime)) # Uses TIME_FORMAT by default self.assertIn('2017', date_format(some_datetime, format=get_format('DATETIME_FORMAT'))) self.assertIn('2017', date_format(some_date, format=get_format('YEAR_MONTH_FORMAT'))) self.assertIn('14', date_format(some_date, format=get_format('MONTH_DAY_FORMAT'))) self.assertIn('2017', date_format(some_date, format=get_format('SHORT_DATE_FORMAT'))) self.assertIn('2017', date_format(some_datetime, format=get_format('SHORT_DATETIME_FORMAT'))) def test_locale_independent(self): """ Localization of numbers """ with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual('66666.66', nformat(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=',')) self.assertEqual('66666A6', nformat(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B')) self.assertEqual('66666', nformat(self.n, decimal_sep='X', decimal_pos=0, grouping=1, thousand_sep='Y')) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual( '66,666.66', nformat(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=',') ) self.assertEqual( '6B6B6B6B6A6', nformat(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B') ) self.assertEqual('-66666.6', nformat(-66666.666, decimal_sep='.', decimal_pos=1)) self.assertEqual('-66666.0', nformat(int('-66666'), decimal_sep='.', decimal_pos=1)) self.assertEqual('10000.0', nformat(self.long, decimal_sep='.', decimal_pos=1)) self.assertEqual( '10,00,00,000.00', nformat(100000000.00, decimal_sep='.', decimal_pos=2, grouping=(3, 2, 0), thousand_sep=',') ) self.assertEqual( '1,0,00,000,0000.00', nformat(10000000000.00, decimal_sep='.', decimal_pos=2, grouping=(4, 3, 2, 1, 0), thousand_sep=',') ) self.assertEqual( '10000,00,000.00', nformat(1000000000.00, decimal_sep='.', decimal_pos=2, grouping=(3, 2, -1), thousand_sep=',') ) # This unusual grouping/force_grouping combination may be triggered by the intcomma filter (#17414) self.assertEqual( '10000', nformat(self.long, decimal_sep='.', decimal_pos=0, grouping=0, force_grouping=True) ) # date filter self.assertEqual('31.12.2009 в 20:50', Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt)) self.assertEqual('⌚ 10:15', Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt)) @override_settings(USE_L10N=False) def test_l10n_disabled(self): """ Catalan locale with format i18n disabled translations will be used, but not formats """ with translation.override('ca', deactivate=True): self.maxDiff = 3000 self.assertEqual('N j, Y', get_format('DATE_FORMAT')) self.assertEqual(0, get_format('FIRST_DAY_OF_WEEK')) self.assertEqual('.', get_format('DECIMAL_SEPARATOR')) self.assertEqual('10:15 a.m.', time_format(self.t)) self.assertEqual('des. 31, 2009', date_format(self.d)) self.assertEqual('desembre 2009', date_format(self.d, 'YEAR_MONTH_FORMAT')) self.assertEqual('12/31/2009 8:50 p.m.', date_format(self.dt, 'SHORT_DATETIME_FORMAT')) self.assertEqual('No localizable', localize('No localizable')) self.assertEqual('66666.666', localize(self.n)) self.assertEqual('99999.999', localize(self.f)) self.assertEqual('10000', localize(self.long)) self.assertEqual('des. 31, 2009', localize(self.d)) self.assertEqual('des. 31, 2009, 8:50 p.m.', localize(self.dt)) self.assertEqual('66666.666', Template('{{ n }}').render(self.ctxt)) self.assertEqual('99999.999', Template('{{ f }}').render(self.ctxt)) self.assertEqual('des. 31, 2009', Template('{{ d }}').render(self.ctxt)) self.assertEqual('des. 31, 2009, 8:50 p.m.', Template('{{ dt }}').render(self.ctxt)) self.assertEqual('66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt)) self.assertEqual('100000.0', Template('{{ f|floatformat }}').render(self.ctxt)) self.assertEqual('10:15 a.m.', Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt)) self.assertEqual('12/31/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt)) self.assertEqual( '12/31/2009 8:50 p.m.', Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt) ) form = I18nForm({ 'decimal_field': '66666,666', 'float_field': '99999,999', 'date_field': '31/12/2009', 'datetime_field': '31/12/2009 20:50', 'time_field': '20:50', 'integer_field': '1.234', }) self.assertFalse(form.is_valid()) self.assertEqual(['Introdu\xefu un n\xfamero.'], form.errors['float_field']) self.assertEqual(['Introdu\xefu un n\xfamero.'], form.errors['decimal_field']) self.assertEqual(['Introdu\xefu una data v\xe0lida.'], form.errors['date_field']) self.assertEqual(['Introdu\xefu una data/hora v\xe0lides.'], form.errors['datetime_field']) self.assertEqual(['Introdu\xefu un n\xfamero sencer.'], form.errors['integer_field']) form2 = SelectDateForm({ 'date_field_month': '12', 'date_field_day': '31', 'date_field_year': '2009' }) self.assertTrue(form2.is_valid()) self.assertEqual(datetime.date(2009, 12, 31), form2.cleaned_data['date_field']) self.assertHTMLEqual( '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">gener</option>' '<option value="2">febrer</option>' '<option value="3">mar\xe7</option>' '<option value="4">abril</option>' '<option value="5">maig</option>' '<option value="6">juny</option>' '<option value="7">juliol</option>' '<option value="8">agost</option>' '<option value="9">setembre</option>' '<option value="10">octubre</option>' '<option value="11">novembre</option>' '<option value="12" selected>desembre</option>' '</select>' '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' '</select>' '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' '</select>', forms.SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31)) ) # We shouldn't change the behavior of the floatformat filter re: # thousand separator and grouping when USE_L10N is False even # if the USE_THOUSAND_SEPARATOR, NUMBER_GROUPING and # THOUSAND_SEPARATOR settings are specified with self.settings(USE_THOUSAND_SEPARATOR=True, NUMBER_GROUPING=1, THOUSAND_SEPARATOR='!'): self.assertEqual('66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt)) self.assertEqual('100000.0', Template('{{ f|floatformat }}').render(self.ctxt)) def test_false_like_locale_formats(self): """ The active locale's formats take precedence over the default settings even if they would be interpreted as False in a conditional test (e.g. 0 or empty string) (#16938). """ with translation.override('fr'): with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR='!'): self.assertEqual('\xa0', get_format('THOUSAND_SEPARATOR')) # Even a second time (after the format has been cached)... self.assertEqual('\xa0', get_format('THOUSAND_SEPARATOR')) with self.settings(FIRST_DAY_OF_WEEK=0): self.assertEqual(1, get_format('FIRST_DAY_OF_WEEK')) # Even a second time (after the format has been cached)... self.assertEqual(1, get_format('FIRST_DAY_OF_WEEK')) def test_l10n_enabled(self): self.maxDiff = 3000 # Catalan locale with translation.override('ca', deactivate=True): self.assertEqual(r'j \d\e F \d\e Y', get_format('DATE_FORMAT')) self.assertEqual(1, get_format('FIRST_DAY_OF_WEEK')) self.assertEqual(',', get_format('DECIMAL_SEPARATOR')) self.assertEqual('10:15', time_format(self.t)) self.assertEqual('31 de desembre de 2009', date_format(self.d)) self.assertEqual('desembre del 2009', date_format(self.d, 'YEAR_MONTH_FORMAT')) self.assertEqual('31/12/2009 20:50', date_format(self.dt, 'SHORT_DATETIME_FORMAT')) self.assertEqual('No localizable', localize('No localizable')) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual('66.666,666', localize(self.n)) self.assertEqual('99.999,999', localize(self.f)) self.assertEqual('10.000', localize(self.long)) self.assertEqual('True', localize(True)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual('66666,666', localize(self.n)) self.assertEqual('99999,999', localize(self.f)) self.assertEqual('10000', localize(self.long)) self.assertEqual('31 de desembre de 2009', localize(self.d)) self.assertEqual('31 de desembre de 2009 a les 20:50', localize(self.dt)) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual('66.666,666', Template('{{ n }}').render(self.ctxt)) self.assertEqual('99.999,999', Template('{{ f }}').render(self.ctxt)) self.assertEqual('10.000', Template('{{ l }}').render(self.ctxt)) with self.settings(USE_THOUSAND_SEPARATOR=True): form3 = I18nForm({ 'decimal_field': '66.666,666', 'float_field': '99.999,999', 'date_field': '31/12/2009', 'datetime_field': '31/12/2009 20:50', 'time_field': '20:50', 'integer_field': '1.234', }) self.assertTrue(form3.is_valid()) self.assertEqual(decimal.Decimal('66666.666'), form3.cleaned_data['decimal_field']) self.assertEqual(99999.999, form3.cleaned_data['float_field']) self.assertEqual(datetime.date(2009, 12, 31), form3.cleaned_data['date_field']) self.assertEqual(datetime.datetime(2009, 12, 31, 20, 50), form3.cleaned_data['datetime_field']) self.assertEqual(datetime.time(20, 50), form3.cleaned_data['time_field']) self.assertEqual(1234, form3.cleaned_data['integer_field']) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual('66666,666', Template('{{ n }}').render(self.ctxt)) self.assertEqual('99999,999', Template('{{ f }}').render(self.ctxt)) self.assertEqual('31 de desembre de 2009', Template('{{ d }}').render(self.ctxt)) self.assertEqual('31 de desembre de 2009 a les 20:50', Template('{{ dt }}').render(self.ctxt)) self.assertEqual('66666,67', Template('{{ n|floatformat:2 }}').render(self.ctxt)) self.assertEqual('100000,0', Template('{{ f|floatformat }}').render(self.ctxt)) self.assertEqual('10:15', Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt)) self.assertEqual('31/12/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt)) self.assertEqual( '31/12/2009 20:50', Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt) ) self.assertEqual(date_format(datetime.datetime.now(), "DATE_FORMAT"), Template('{% now "DATE_FORMAT" %}').render(self.ctxt)) with self.settings(USE_THOUSAND_SEPARATOR=False): form4 = I18nForm({ 'decimal_field': '66666,666', 'float_field': '99999,999', 'date_field': '31/12/2009', 'datetime_field': '31/12/2009 20:50', 'time_field': '20:50', 'integer_field': '1234', }) self.assertTrue(form4.is_valid()) self.assertEqual(decimal.Decimal('66666.666'), form4.cleaned_data['decimal_field']) self.assertEqual(99999.999, form4.cleaned_data['float_field']) self.assertEqual(datetime.date(2009, 12, 31), form4.cleaned_data['date_field']) self.assertEqual(datetime.datetime(2009, 12, 31, 20, 50), form4.cleaned_data['datetime_field']) self.assertEqual(datetime.time(20, 50), form4.cleaned_data['time_field']) self.assertEqual(1234, form4.cleaned_data['integer_field']) form5 = SelectDateForm({ 'date_field_month': '12', 'date_field_day': '31', 'date_field_year': '2009' }) self.assertTrue(form5.is_valid()) self.assertEqual(datetime.date(2009, 12, 31), form5.cleaned_data['date_field']) self.assertHTMLEqual( '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' '</select>' '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">gener</option>' '<option value="2">febrer</option>' '<option value="3">mar\xe7</option>' '<option value="4">abril</option>' '<option value="5">maig</option>' '<option value="6">juny</option>' '<option value="7">juliol</option>' '<option value="8">agost</option>' '<option value="9">setembre</option>' '<option value="10">octubre</option>' '<option value="11">novembre</option>' '<option value="12" selected>desembre</option>' '</select>' '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' '</select>', forms.SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31)) ) # Russian locale (with E as month) with translation.override('ru', deactivate=True): self.assertHTMLEqual( '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' '</select>' '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">\u042f\u043d\u0432\u0430\u0440\u044c</option>' '<option value="2">\u0424\u0435\u0432\u0440\u0430\u043b\u044c</option>' '<option value="3">\u041c\u0430\u0440\u0442</option>' '<option value="4">\u0410\u043f\u0440\u0435\u043b\u044c</option>' '<option value="5">\u041c\u0430\u0439</option>' '<option value="6">\u0418\u044e\u043d\u044c</option>' '<option value="7">\u0418\u044e\u043b\u044c</option>' '<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>' '<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c</option>' '<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>' '<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>' '<option value="12" selected>\u0414\u0435\u043a\u0430\u0431\u0440\u044c</option>' '</select>' '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' '</select>', forms.SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31)) ) # English locale with translation.override('en', deactivate=True): self.assertEqual('N j, Y', get_format('DATE_FORMAT')) self.assertEqual(0, get_format('FIRST_DAY_OF_WEEK')) self.assertEqual('.', get_format('DECIMAL_SEPARATOR')) self.assertEqual('Dec. 31, 2009', date_format(self.d)) self.assertEqual('December 2009', date_format(self.d, 'YEAR_MONTH_FORMAT')) self.assertEqual('12/31/2009 8:50 p.m.', date_format(self.dt, 'SHORT_DATETIME_FORMAT')) self.assertEqual('No localizable', localize('No localizable')) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual('66,666.666', localize(self.n)) self.assertEqual('99,999.999', localize(self.f)) self.assertEqual('10,000', localize(self.long)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual('66666.666', localize(self.n)) self.assertEqual('99999.999', localize(self.f)) self.assertEqual('10000', localize(self.long)) self.assertEqual('Dec. 31, 2009', localize(self.d)) self.assertEqual('Dec. 31, 2009, 8:50 p.m.', localize(self.dt)) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual('66,666.666', Template('{{ n }}').render(self.ctxt)) self.assertEqual('99,999.999', Template('{{ f }}').render(self.ctxt)) self.assertEqual('10,000', Template('{{ l }}').render(self.ctxt)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual('66666.666', Template('{{ n }}').render(self.ctxt)) self.assertEqual('99999.999', Template('{{ f }}').render(self.ctxt)) self.assertEqual('Dec. 31, 2009', Template('{{ d }}').render(self.ctxt)) self.assertEqual('Dec. 31, 2009, 8:50 p.m.', Template('{{ dt }}').render(self.ctxt)) self.assertEqual('66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt)) self.assertEqual('100000.0', Template('{{ f|floatformat }}').render(self.ctxt)) self.assertEqual('12/31/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt)) self.assertEqual( '12/31/2009 8:50 p.m.', Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt) ) form5 = I18nForm({ 'decimal_field': '66666.666', 'float_field': '99999.999', 'date_field': '12/31/2009', 'datetime_field': '12/31/2009 20:50', 'time_field': '20:50', 'integer_field': '1234', }) self.assertTrue(form5.is_valid()) self.assertEqual(decimal.Decimal('66666.666'), form5.cleaned_data['decimal_field']) self.assertEqual(99999.999, form5.cleaned_data['float_field']) self.assertEqual(datetime.date(2009, 12, 31), form5.cleaned_data['date_field']) self.assertEqual(datetime.datetime(2009, 12, 31, 20, 50), form5.cleaned_data['datetime_field']) self.assertEqual(datetime.time(20, 50), form5.cleaned_data['time_field']) self.assertEqual(1234, form5.cleaned_data['integer_field']) form6 = SelectDateForm({ 'date_field_month': '12', 'date_field_day': '31', 'date_field_year': '2009' }) self.assertTrue(form6.is_valid()) self.assertEqual(datetime.date(2009, 12, 31), form6.cleaned_data['date_field']) self.assertHTMLEqual( '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">January</option>' '<option value="2">February</option>' '<option value="3">March</option>' '<option value="4">April</option>' '<option value="5">May</option>' '<option value="6">June</option>' '<option value="7">July</option>' '<option value="8">August</option>' '<option value="9">September</option>' '<option value="10">October</option>' '<option value="11">November</option>' '<option value="12" selected>December</option>' '</select>' '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' '</select>' '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' '</select>', forms.SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31)) ) def test_sub_locales(self): """ Check if sublocales fall back to the main locale """ with self.settings(USE_THOUSAND_SEPARATOR=True): with translation.override('de-at', deactivate=True): self.assertEqual('66.666,666', Template('{{ n }}').render(self.ctxt)) with translation.override('es-us', deactivate=True): self.assertEqual('31 de Diciembre de 2009', date_format(self.d)) def test_localized_input(self): """ Tests if form input is correctly localized """ self.maxDiff = 1200 with translation.override('de-at', deactivate=True): form6 = CompanyForm({ 'name': 'acme', 'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0), 'cents_paid': decimal.Decimal('59.47'), 'products_delivered': 12000, }) self.assertTrue(form6.is_valid()) self.assertHTMLEqual( form6.as_ul(), '<li><label for="id_name">Name:</label>' '<input id="id_name" type="text" name="name" value="acme" maxlength="50" required></li>' '<li><label for="id_date_added">Date added:</label>' '<input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" required></li>' '<li><label for="id_cents_paid">Cents paid:</label>' '<input type="text" name="cents_paid" value="59,47" id="id_cents_paid" required></li>' '<li><label for="id_products_delivered">Products delivered:</label>' '<input type="text" name="products_delivered" value="12000" id="id_products_delivered" required>' '</li>' ) self.assertEqual(localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), '31.12.2009 06:00:00') self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data['date_added']) with self.settings(USE_THOUSAND_SEPARATOR=True): # Checking for the localized "products_delivered" field self.assertInHTML( '<input type="text" name="products_delivered" ' 'value="12.000" id="id_products_delivered" required>', form6.as_ul() ) def test_localized_input_func(self): tests = ( (True, 'True'), (datetime.date(1, 1, 1), '0001-01-01'), (datetime.datetime(1, 1, 1), '0001-01-01 00:00:00'), ) with self.settings(USE_THOUSAND_SEPARATOR=True): for value, expected in tests: with self.subTest(value=value): self.assertEqual(localize_input(value), expected) def test_sanitize_separators(self): """ Tests django.utils.formats.sanitize_separators. """ # Non-strings are untouched self.assertEqual(sanitize_separators(123), 123) with translation.override('ru', deactivate=True): # Russian locale has non-breaking space (\xa0) as thousand separator # Usual space is accepted too when sanitizing inputs with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual(sanitize_separators('1\xa0234\xa0567'), '1234567') self.assertEqual(sanitize_separators('77\xa0777,777'), '77777.777') self.assertEqual(sanitize_separators('12 345'), '12345') self.assertEqual(sanitize_separators('77 777,777'), '77777.777') with self.settings(USE_THOUSAND_SEPARATOR=True, USE_L10N=False): self.assertEqual(sanitize_separators('12\xa0345'), '12\xa0345') with self.settings(USE_THOUSAND_SEPARATOR=True): with patch_formats(get_language(), THOUSAND_SEPARATOR='.', DECIMAL_SEPARATOR=','): self.assertEqual(sanitize_separators('10.234'), '10234') # Suspicion that user entered dot as decimal separator (#22171) self.assertEqual(sanitize_separators('10.10'), '10.10') with self.settings(USE_L10N=False, DECIMAL_SEPARATOR=','): self.assertEqual(sanitize_separators('1001,10'), '1001.10') self.assertEqual(sanitize_separators('1001.10'), '1001.10') with self.settings( USE_L10N=False, DECIMAL_SEPARATOR=',', USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR='.' ): self.assertEqual(sanitize_separators('1.001,10'), '1001.10') self.assertEqual(sanitize_separators('1001,10'), '1001.10') self.assertEqual(sanitize_separators('1001.10'), '1001.10') self.assertEqual(sanitize_separators('1,001.10'), '1.001.10') # Invalid output def test_iter_format_modules(self): """ Tests the iter_format_modules function. """ # Importing some format modules so that we can compare the returned # modules with these expected modules default_mod = import_module('django.conf.locale.de.formats') test_mod = import_module('i18n.other.locale.de.formats') test_mod2 = import_module('i18n.other2.locale.de.formats') with translation.override('de-at', deactivate=True): # Should return the correct default module when no setting is set self.assertEqual(list(iter_format_modules('de')), [default_mod]) # When the setting is a string, should return the given module and # the default module self.assertEqual( list(iter_format_modules('de', 'i18n.other.locale')), [test_mod, default_mod]) # When setting is a list of strings, should return the given # modules and the default module self.assertEqual( list(iter_format_modules('de', ['i18n.other.locale', 'i18n.other2.locale'])), [test_mod, test_mod2, default_mod]) def test_iter_format_modules_stability(self): """ Tests the iter_format_modules function always yields format modules in a stable and correct order in presence of both base ll and ll_CC formats. """ en_format_mod = import_module('django.conf.locale.en.formats') en_gb_format_mod = import_module('django.conf.locale.en_GB.formats') self.assertEqual(list(iter_format_modules('en-gb')), [en_gb_format_mod, en_format_mod]) def test_get_format_modules_lang(self): with translation.override('de', deactivate=True): self.assertEqual('.', get_format('DECIMAL_SEPARATOR', lang='en')) def test_get_format_modules_stability(self): with self.settings(FORMAT_MODULE_PATH='i18n.other.locale'): with translation.override('de', deactivate=True): old = "%r" % get_format_modules(reverse=True) new = "%r" % get_format_modules(reverse=True) # second try self.assertEqual(new, old, 'Value returned by get_formats_modules() must be preserved between calls.') def test_localize_templatetag_and_filter(self): """ Test the {% localize %} templatetag and the localize/unlocalize filters. """ context = Context({'int': 1455, 'float': 3.14, 'date': datetime.date(2016, 12, 31)}) template1 = Template( '{% load l10n %}{% localize %}{{ int }}/{{ float }}/{{ date }}{% endlocalize %}; ' '{% localize on %}{{ int }}/{{ float }}/{{ date }}{% endlocalize %}' ) template2 = Template( '{% load l10n %}{{ int }}/{{ float }}/{{ date }}; ' '{% localize off %}{{ int }}/{{ float }}/{{ date }};{% endlocalize %} ' '{{ int }}/{{ float }}/{{ date }}' ) template3 = Template( '{% load l10n %}{{ int }}/{{ float }}/{{ date }}; ' '{{ int|unlocalize }}/{{ float|unlocalize }}/{{ date|unlocalize }}' ) template4 = Template( '{% load l10n %}{{ int }}/{{ float }}/{{ date }}; ' '{{ int|localize }}/{{ float|localize }}/{{ date|localize }}' ) expected_localized = '1.455/3,14/31. Dezember 2016' expected_unlocalized = '1455/3.14/Dez. 31, 2016' output1 = '; '.join([expected_localized, expected_localized]) output2 = '; '.join([expected_localized, expected_unlocalized, expected_localized]) output3 = '; '.join([expected_localized, expected_unlocalized]) output4 = '; '.join([expected_unlocalized, expected_localized]) with translation.override('de', deactivate=True): with self.settings(USE_L10N=False, USE_THOUSAND_SEPARATOR=True): self.assertEqual(template1.render(context), output1) self.assertEqual(template4.render(context), output4) with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True): self.assertEqual(template1.render(context), output1) self.assertEqual(template2.render(context), output2) self.assertEqual(template3.render(context), output3) def test_localized_as_text_as_hidden_input(self): """ Tests if form input with 'as_hidden' or 'as_text' is correctly localized. Ticket #18777 """ self.maxDiff = 1200 with translation.override('de-at', deactivate=True): template = Template('{% load l10n %}{{ form.date_added }}; {{ form.cents_paid }}') template_as_text = Template('{% load l10n %}{{ form.date_added.as_text }}; {{ form.cents_paid.as_text }}') template_as_hidden = Template( '{% load l10n %}{{ form.date_added.as_hidden }}; {{ form.cents_paid.as_hidden }}' ) form = CompanyForm({ 'name': 'acme', 'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0), 'cents_paid': decimal.Decimal('59.47'), 'products_delivered': 12000, }) context = Context({'form': form}) self.assertTrue(form.is_valid()) self.assertHTMLEqual( template.render(context), '<input id="id_date_added" name="date_added" type="text" value="31.12.2009 06:00:00" required>;' '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" required>' ) self.assertHTMLEqual( template_as_text.render(context), '<input id="id_date_added" name="date_added" type="text" value="31.12.2009 06:00:00" required>;' ' <input id="id_cents_paid" name="cents_paid" type="text" value="59,47" required>' ) self.assertHTMLEqual( template_as_hidden.render(context), '<input id="id_date_added" name="date_added" type="hidden" value="31.12.2009 06:00:00">;' '<input id="id_cents_paid" name="cents_paid" type="hidden" value="59,47">' ) def test_format_arbitrary_settings(self): self.assertEqual(get_format('DEBUG'), 'DEBUG') def test_get_custom_format(self): with self.settings(FORMAT_MODULE_PATH='i18n.other.locale'): with translation.override('fr', deactivate=True): self.assertEqual('d/m/Y CUSTOM', get_format('CUSTOM_DAY_FORMAT')) def test_admin_javascript_supported_input_formats(self): """ The first input format for DATE_INPUT_FORMATS, TIME_INPUT_FORMATS, and DATETIME_INPUT_FORMATS must not contain %f since that's unsupported by the admin's time picker widget. """ regex = re.compile('%([^BcdHImMpSwxXyY%])') for language_code, language_name in settings.LANGUAGES: for format_name in ('DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS', 'DATETIME_INPUT_FORMATS'): with self.subTest(language=language_code, format=format_name): formatter = get_format(format_name, lang=language_code)[0] self.assertEqual( regex.findall(formatter), [], "%s locale's %s uses an unsupported format code." % (language_code, format_name) ) class MiscTests(SimpleTestCase): rf = RequestFactory() @override_settings(LANGUAGE_CODE='de') def test_english_fallback(self): """ With a non-English LANGUAGE_CODE and if the active language is English or one of its variants, the untranslated string should be returned (instead of falling back to LANGUAGE_CODE) (See #24413). """ self.assertEqual(gettext("Image"), "Bild") with translation.override('en'): self.assertEqual(gettext("Image"), "Image") with translation.override('en-us'): self.assertEqual(gettext("Image"), "Image") with translation.override('en-ca'): self.assertEqual(gettext("Image"), "Image") def test_parse_spec_http_header(self): """ Testing HTTP header parsing. First, we test that we can parse the values according to the spec (and that we extract all the pieces in the right order). """ tests = [ # Good headers ('de', [('de', 1.0)]), ('en-AU', [('en-au', 1.0)]), ('es-419', [('es-419', 1.0)]), ('*;q=1.00', [('*', 1.0)]), ('en-AU;q=0.123', [('en-au', 0.123)]), ('en-au;q=0.5', [('en-au', 0.5)]), ('en-au;q=1.0', [('en-au', 1.0)]), ('da, en-gb;q=0.25, en;q=0.5', [('da', 1.0), ('en', 0.5), ('en-gb', 0.25)]), ('en-au-xx', [('en-au-xx', 1.0)]), ('de,en-au;q=0.75,en-us;q=0.5,en;q=0.25,es;q=0.125,fa;q=0.125', [('de', 1.0), ('en-au', 0.75), ('en-us', 0.5), ('en', 0.25), ('es', 0.125), ('fa', 0.125)]), ('*', [('*', 1.0)]), ('de;q=0.', [('de', 0.0)]), ('en; q=1,', [('en', 1.0)]), ('en; q=1.0, * ; q=0.5', [('en', 1.0), ('*', 0.5)]), # Bad headers ('en-gb;q=1.0000', []), ('en;q=0.1234', []), ('en;q=.2', []), ('abcdefghi-au', []), ('**', []), ('en,,gb', []), ('en-au;q=0.1.0', []), (('X' * 97) + 'Z,en', []), ('da, en-gb;q=0.8, en;q=0.7,#', []), ('de;q=2.0', []), ('de;q=0.a', []), ('12-345', []), ('', []), ('en;q=1e0', []), ] for value, expected in tests: with self.subTest(value=value): self.assertEqual(trans_real.parse_accept_lang_header(value), tuple(expected)) def test_parse_literal_http_header(self): """ Now test that we parse a literal HTTP header correctly. """ g = get_language_from_request r = self.rf.get('/') r.COOKIES = {} r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt-br'} self.assertEqual('pt-br', g(r)) r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt'} self.assertEqual('pt', g(r)) r.META = {'HTTP_ACCEPT_LANGUAGE': 'es,de'} self.assertEqual('es', g(r)) r.META = {'HTTP_ACCEPT_LANGUAGE': 'es-ar,de'} self.assertEqual('es-ar', g(r)) # This test assumes there won't be a Django translation to a US # variation of the Spanish language, a safe assumption. When the # user sets it as the preferred language, the main 'es' # translation should be selected instead. r.META = {'HTTP_ACCEPT_LANGUAGE': 'es-us'} self.assertEqual(g(r), 'es') # This tests the following scenario: there isn't a main language (zh) # translation of Django but there is a translation to variation (zh-hans) # the user sets zh-hans as the preferred language, it should be selected # by Django without falling back nor ignoring it. r.META = {'HTTP_ACCEPT_LANGUAGE': 'zh-hans,de'} self.assertEqual(g(r), 'zh-hans') r.META = {'HTTP_ACCEPT_LANGUAGE': 'NL'} self.assertEqual('nl', g(r)) r.META = {'HTTP_ACCEPT_LANGUAGE': 'fy'} self.assertEqual('fy', g(r)) r.META = {'HTTP_ACCEPT_LANGUAGE': 'ia'} self.assertEqual('ia', g(r)) r.META = {'HTTP_ACCEPT_LANGUAGE': 'sr-latn'} self.assertEqual('sr-latn', g(r)) r.META = {'HTTP_ACCEPT_LANGUAGE': 'zh-hans'} self.assertEqual('zh-hans', g(r)) r.META = {'HTTP_ACCEPT_LANGUAGE': 'zh-hant'} self.assertEqual('zh-hant', g(r)) @override_settings( LANGUAGES=[ ('en', 'English'), ('zh-hans', 'Simplified Chinese'), ('zh-hant', 'Traditional Chinese'), ] ) def test_support_for_deprecated_chinese_language_codes(self): """ Some browsers (Firefox, IE, etc.) use deprecated language codes. As these language codes will be removed in Django 1.9, these will be incorrectly matched. For example zh-tw (traditional) will be interpreted as zh-hans (simplified), which is wrong. So we should also accept these deprecated language codes. refs #18419 -- this is explicitly for browser compatibility """ g = get_language_from_request r = self.rf.get('/') r.COOKIES = {} r.META = {'HTTP_ACCEPT_LANGUAGE': 'zh-cn,en'} self.assertEqual(g(r), 'zh-hans') r.META = {'HTTP_ACCEPT_LANGUAGE': 'zh-tw,en'} self.assertEqual(g(r), 'zh-hant') def test_special_fallback_language(self): """ Some languages may have special fallbacks that don't follow the simple 'fr-ca' -> 'fr' logic (notably Chinese codes). """ r = self.rf.get('/') r.COOKIES = {} r.META = {'HTTP_ACCEPT_LANGUAGE': 'zh-my,en'} self.assertEqual(get_language_from_request(r), 'zh-hans') def test_parse_language_cookie(self): """ Now test that we parse language preferences stored in a cookie correctly. """ g = get_language_from_request r = self.rf.get('/') r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'pt-br'} r.META = {} self.assertEqual('pt-br', g(r)) r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'pt'} r.META = {} self.assertEqual('pt', g(r)) r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'es'} r.META = {'HTTP_ACCEPT_LANGUAGE': 'de'} self.assertEqual('es', g(r)) # This test assumes there won't be a Django translation to a US # variation of the Spanish language, a safe assumption. When the # user sets it as the preferred language, the main 'es' # translation should be selected instead. r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'es-us'} r.META = {} self.assertEqual(g(r), 'es') # This tests the following scenario: there isn't a main language (zh) # translation of Django but there is a translation to variation (zh-hans) # the user sets zh-hans as the preferred language, it should be selected # by Django without falling back nor ignoring it. r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'zh-hans'} r.META = {'HTTP_ACCEPT_LANGUAGE': 'de'} self.assertEqual(g(r), 'zh-hans') @override_settings( USE_I18N=True, LANGUAGES=[ ('en', 'English'), ('de', 'German'), ('de-at', 'Austrian German'), ('pt-br', 'Portuguese (Brazil)'), ], ) def test_get_supported_language_variant_real(self): g = trans_real.get_supported_language_variant self.assertEqual(g('en'), 'en') self.assertEqual(g('en-gb'), 'en') self.assertEqual(g('de'), 'de') self.assertEqual(g('de-at'), 'de-at') self.assertEqual(g('de-ch'), 'de') self.assertEqual(g('pt-br'), 'pt-br') self.assertEqual(g('pt'), 'pt-br') self.assertEqual(g('pt-pt'), 'pt-br') with self.assertRaises(LookupError): g('pt', strict=True) with self.assertRaises(LookupError): g('pt-pt', strict=True) with self.assertRaises(LookupError): g('xyz') with self.assertRaises(LookupError): g('xy-zz') def test_get_supported_language_variant_null(self): g = trans_null.get_supported_language_variant self.assertEqual(g(settings.LANGUAGE_CODE), settings.LANGUAGE_CODE) with self.assertRaises(LookupError): g('pt') with self.assertRaises(LookupError): g('de') with self.assertRaises(LookupError): g('de-at') with self.assertRaises(LookupError): g('de', strict=True) with self.assertRaises(LookupError): g('de-at', strict=True) with self.assertRaises(LookupError): g('xyz') @override_settings( LANGUAGES=[ ('en', 'English'), ('de', 'German'), ('de-at', 'Austrian German'), ('pl', 'Polish'), ], ) def test_get_language_from_path_real(self): g = trans_real.get_language_from_path self.assertEqual(g('/pl/'), 'pl') self.assertEqual(g('/pl'), 'pl') self.assertIsNone(g('/xyz/')) self.assertEqual(g('/en/'), 'en') self.assertEqual(g('/en-gb/'), 'en') self.assertEqual(g('/de/'), 'de') self.assertEqual(g('/de-at/'), 'de-at') self.assertEqual(g('/de-ch/'), 'de') self.assertIsNone(g('/de-simple-page/')) def test_get_language_from_path_null(self): g = trans_null.get_language_from_path self.assertIsNone(g('/pl/')) self.assertIsNone(g('/pl')) self.assertIsNone(g('/xyz/')) def test_cache_resetting(self): """ After setting LANGUAGE, the cache should be cleared and languages previously valid should not be used (#14170). """ g = get_language_from_request r = self.rf.get('/') r.COOKIES = {} r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt-br'} self.assertEqual('pt-br', g(r)) with self.settings(LANGUAGES=[('en', 'English')]): self.assertNotEqual('pt-br', g(r)) def test_i18n_patterns_returns_list(self): with override_settings(USE_I18N=False): self.assertIsInstance(i18n_patterns([]), list) with override_settings(USE_I18N=True): self.assertIsInstance(i18n_patterns([]), list) class ResolutionOrderI18NTests(SimpleTestCase): def setUp(self): super().setUp() activate('de') def tearDown(self): deactivate() super().tearDown() def assertGettext(self, msgid, msgstr): result = gettext(msgid) self.assertIn( msgstr, result, "The string '%s' isn't in the translation of '%s'; the actual result is '%s'." % (msgstr, msgid, result) ) class AppResolutionOrderI18NTests(ResolutionOrderI18NTests): @override_settings(LANGUAGE_CODE='de') def test_app_translation(self): # Original translation. self.assertGettext('Date/time', 'Datum/Zeit') # Different translation. with self.modify_settings(INSTALLED_APPS={'append': 'i18n.resolution'}): # Force refreshing translations. activate('de') # Doesn't work because it's added later in the list. self.assertGettext('Date/time', 'Datum/Zeit') with self.modify_settings(INSTALLED_APPS={'remove': 'django.contrib.admin.apps.SimpleAdminConfig'}): # Force refreshing translations. activate('de') # Unless the original is removed from the list. self.assertGettext('Date/time', 'Datum/Zeit (APP)') @override_settings(LOCALE_PATHS=extended_locale_paths) class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_locale_paths_translation(self): self.assertGettext('Time', 'LOCALE_PATHS') def test_locale_paths_override_app_translation(self): with self.settings(INSTALLED_APPS=['i18n.resolution']): self.assertGettext('Time', 'LOCALE_PATHS') class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_django_fallback(self): self.assertEqual(gettext('Date/time'), 'Datum/Zeit') @override_settings(INSTALLED_APPS=['i18n.territorial_fallback']) class TranslationFallbackI18NTests(ResolutionOrderI18NTests): def test_sparse_territory_catalog(self): """ Untranslated strings for territorial language variants use the translations of the generic language. In this case, the de-de translation falls back to de. """ with translation.override('de-de'): self.assertGettext('Test 1 (en)', '(de-de)') self.assertGettext('Test 2 (en)', '(de)') class TestModels(TestCase): def test_lazy(self): tm = TestModel() tm.save() def test_safestr(self): c = Company(cents_paid=12, products_delivered=1) c.name = SafeString('Iñtërnâtiônàlizætiøn1') c.save() class TestLanguageInfo(SimpleTestCase): def test_localized_language_info(self): li = get_language_info('de') self.assertEqual(li['code'], 'de') self.assertEqual(li['name_local'], 'Deutsch') self.assertEqual(li['name'], 'German') self.assertIs(li['bidi'], False) def test_unknown_language_code(self): with self.assertRaisesMessage(KeyError, "Unknown language code xx"): get_language_info('xx') with translation.override('xx'): # A language with no translation catalogs should fallback to the # untranslated string. self.assertEqual(gettext("Title"), "Title") def test_unknown_only_country_code(self): li = get_language_info('de-xx') self.assertEqual(li['code'], 'de') self.assertEqual(li['name_local'], 'Deutsch') self.assertEqual(li['name'], 'German') self.assertIs(li['bidi'], False) def test_unknown_language_code_and_country_code(self): with self.assertRaisesMessage(KeyError, "Unknown language code xx-xx and xx"): get_language_info('xx-xx') def test_fallback_language_code(self): """ get_language_info return the first fallback language info if the lang_info struct does not contain the 'name' key. """ li = get_language_info('zh-my') self.assertEqual(li['code'], 'zh-hans') li = get_language_info('zh-hans') self.assertEqual(li['code'], 'zh-hans') @override_settings( USE_I18N=True, LANGUAGES=[ ('en', 'English'), ('fr', 'French'), ], MIDDLEWARE=[ 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ], ROOT_URLCONF='i18n.urls', ) class LocaleMiddlewareTests(TestCase): def test_streaming_response(self): # Regression test for #5241 response = self.client.get('/fr/streaming/') self.assertContains(response, "Oui/Non") response = self.client.get('/en/streaming/') self.assertContains(response, "Yes/No") @override_settings( MIDDLEWARE=[ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ], ) def test_language_not_saved_to_session(self): """ The Current language isno' automatically saved to the session on every request (#21473). """ self.client.get('/fr/simple/') self.assertNotIn(LANGUAGE_SESSION_KEY, self.client.session) @override_settings( USE_I18N=True, LANGUAGES=[ ('en', 'English'), ('de', 'German'), ('fr', 'French'), ], MIDDLEWARE=[ 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ], ROOT_URLCONF='i18n.urls_default_unprefixed', LANGUAGE_CODE='en', ) class UnprefixedDefaultLanguageTests(SimpleTestCase): def test_default_lang_without_prefix(self): """ With i18n_patterns(..., prefix_default_language=False), the default language (settings.LANGUAGE_CODE) should be accessible without a prefix. """ response = self.client.get('/simple/') self.assertEqual(response.content, b'Yes') def test_other_lang_with_prefix(self): response = self.client.get('/fr/simple/') self.assertEqual(response.content, b'Oui') def test_unprefixed_language_other_than_accept_language(self): response = self.client.get('/simple/', HTTP_ACCEPT_LANGUAGE='fr') self.assertEqual(response.content, b'Yes') def test_page_with_dash(self): # A page starting with /de* shouldn't match the 'de' language code. response = self.client.get('/de-simple-page/') self.assertEqual(response.content, b'Yes') def test_no_redirect_on_404(self): """ A request for a nonexistent URL shouldn't cause a redirect to /<default_language>/<request_url> when prefix_default_language=False and /<default_language>/<request_url> has a URL match (#27402). """ # A match for /group1/group2/ must exist for this to act as a # regression test. response = self.client.get('/group1/group2/') self.assertEqual(response.status_code, 200) response = self.client.get('/nonexistent/') self.assertEqual(response.status_code, 404) @override_settings( USE_I18N=True, LANGUAGES=[ ('bg', 'Bulgarian'), ('en-us', 'English'), ('pt-br', 'Portuguese (Brazil)'), ], MIDDLEWARE=[ 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ], ROOT_URLCONF='i18n.urls' ) class CountrySpecificLanguageTests(SimpleTestCase): rf = RequestFactory() def test_check_for_language(self): self.assertTrue(check_for_language('en')) self.assertTrue(check_for_language('en-us')) self.assertTrue(check_for_language('en-US')) self.assertFalse(check_for_language('en_US')) self.assertTrue(check_for_language('be')) self.assertTrue(check_for_language('be@latin')) self.assertTrue(check_for_language('sr-RS@latin')) self.assertTrue(check_for_language('sr-RS@12345')) self.assertFalse(check_for_language('en-ü')) self.assertFalse(check_for_language('en\x00')) self.assertFalse(check_for_language(None)) self.assertFalse(check_for_language('be@ ')) # Specifying encoding is not supported (Django enforces UTF-8) self.assertFalse(check_for_language('tr-TR.UTF-8')) self.assertFalse(check_for_language('tr-TR.UTF8')) self.assertFalse(check_for_language('de-DE.utf-8')) def test_check_for_language_null(self): self.assertIs(trans_null.check_for_language('en'), True) def test_get_language_from_request(self): # issue 19919 r = self.rf.get('/') r.COOKIES = {} r.META = {'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8,bg;q=0.6,ru;q=0.4'} lang = get_language_from_request(r) self.assertEqual('en-us', lang) r = self.rf.get('/') r.COOKIES = {} r.META = {'HTTP_ACCEPT_LANGUAGE': 'bg-bg,en-US;q=0.8,en;q=0.6,ru;q=0.4'} lang = get_language_from_request(r) self.assertEqual('bg', lang) def test_get_language_from_request_null(self): lang = trans_null.get_language_from_request(None) self.assertEqual(lang, 'en') with override_settings(LANGUAGE_CODE='de'): lang = trans_null.get_language_from_request(None) self.assertEqual(lang, 'de') def test_specific_language_codes(self): # issue 11915 r = self.rf.get('/') r.COOKIES = {} r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt,en-US;q=0.8,en;q=0.6,ru;q=0.4'} lang = get_language_from_request(r) self.assertEqual('pt-br', lang) r = self.rf.get('/') r.COOKIES = {} r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt-pt,en-US;q=0.8,en;q=0.6,ru;q=0.4'} lang = get_language_from_request(r) self.assertEqual('pt-br', lang) class TranslationFilesMissing(SimpleTestCase): def setUp(self): super().setUp() self.gettext_find_builtin = gettext_module.find def tearDown(self): gettext_module.find = self.gettext_find_builtin super().tearDown() def patchGettextFind(self): gettext_module.find = lambda *args, **kw: None def test_failure_finding_default_mo_files(self): """OSError is raised if the default language is unparseable.""" self.patchGettextFind() trans_real._translations = {} with self.assertRaises(OSError): activate('en') class NonDjangoLanguageTests(SimpleTestCase): """ A language non present in default Django languages can still be installed/used by a Django project. """ @override_settings( USE_I18N=True, LANGUAGES=[ ('en-us', 'English'), ('xxx', 'Somelanguage'), ], LANGUAGE_CODE='xxx', LOCALE_PATHS=[os.path.join(here, 'commands', 'locale')], ) def test_non_django_language(self): self.assertEqual(get_language(), 'xxx') self.assertEqual(gettext("year"), "reay") @override_settings(USE_I18N=True) def test_check_for_language(self): with tempfile.TemporaryDirectory() as app_dir: os.makedirs(os.path.join(app_dir, 'locale', 'dummy_Lang', 'LC_MESSAGES')) open(os.path.join(app_dir, 'locale', 'dummy_Lang', 'LC_MESSAGES', 'django.mo'), 'w').close() app_config = AppConfig('dummy_app', AppModuleStub(__path__=[app_dir])) with mock.patch('django.apps.apps.get_app_configs', return_value=[app_config]): self.assertIs(check_for_language('dummy-lang'), True) @override_settings( USE_I18N=True, LANGUAGES=[ ('en-us', 'English'), # xyz language has no locale files ('xyz', 'XYZ'), ], ) @translation.override('xyz') def test_plural_non_django_language(self): self.assertEqual(get_language(), 'xyz') self.assertEqual(ngettext('year', 'years', 2), 'years') @override_settings(USE_I18N=True) class WatchForTranslationChangesTests(SimpleTestCase): @override_settings(USE_I18N=False) def test_i18n_disabled(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_not_called() def test_i18n_enabled(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) self.assertGreater(mocked_sender.watch_dir.call_count, 1) def test_i18n_locale_paths(self): mocked_sender = mock.MagicMock() with tempfile.TemporaryDirectory() as app_dir: with self.settings(LOCALE_PATHS=[app_dir]): watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_any_call(Path(app_dir), '**/*.mo') def test_i18n_app_dirs(self): mocked_sender = mock.MagicMock() with self.settings(INSTALLED_APPS=['tests.i18n.sampleproject']): watch_for_translation_changes(mocked_sender) project_dir = Path(__file__).parent / 'sampleproject' / 'locale' mocked_sender.watch_dir.assert_any_call(project_dir, '**/*.mo') def test_i18n_local_locale(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) locale_dir = Path(__file__).parent / 'locale' mocked_sender.watch_dir.assert_any_call(locale_dir, '**/*.mo') class TranslationFileChangedTests(SimpleTestCase): def setUp(self): self.gettext_translations = gettext_module._translations.copy() self.trans_real_translations = trans_real._translations.copy() def tearDown(self): gettext._translations = self.gettext_translations trans_real._translations = self.trans_real_translations def test_ignores_non_mo_files(self): gettext_module._translations = {'foo': 'bar'} path = Path('test.py') self.assertIsNone(translation_file_changed(None, path)) self.assertEqual(gettext_module._translations, {'foo': 'bar'}) def test_resets_cache_with_mo_files(self): gettext_module._translations = {'foo': 'bar'} trans_real._translations = {'foo': 'bar'} trans_real._default = 1 trans_real._active = False path = Path('test.mo') self.assertIs(translation_file_changed(None, path), True) self.assertEqual(gettext_module._translations, {}) self.assertEqual(trans_real._translations, {}) self.assertIsNone(trans_real._default) self.assertIsInstance(trans_real._active, Local) class UtilsTests(SimpleTestCase): def test_round_away_from_one(self): tests = [ (0, 0), (0., 0), (0.25, 0), (0.5, 0), (0.75, 0), (1, 1), (1., 1), (1.25, 2), (1.5, 2), (1.75, 2), (-0., 0), (-0.25, -1), (-0.5, -1), (-0.75, -1), (-1, -1), (-1., -1), (-1.25, -2), (-1.5, -2), (-1.75, -2), ] for value, expected in tests: with self.subTest(value=value): self.assertEqual(round_away_from_one(value), expected)
2c620a7e768983ffaeb6461f2df6d6c4ad2a673b52d055b71bbe0c69818b482c
import gettext as gettext_module import os import stat import unittest from io import StringIO from pathlib import Path from subprocess import run from unittest import mock from django.core.management import ( CommandError, call_command, execute_from_command_line, ) from django.core.management.commands.makemessages import ( Command as MakeMessagesCommand, ) from django.core.management.utils import find_command from django.test import SimpleTestCase, override_settings from django.test.utils import captured_stderr, captured_stdout from django.utils import translation from django.utils.translation import gettext from .utils import RunInTmpDirMixin, copytree has_msgfmt = find_command('msgfmt') @unittest.skipUnless(has_msgfmt, 'msgfmt is mandatory for compilation tests') class MessageCompilationTests(RunInTmpDirMixin, SimpleTestCase): work_subdir = 'commands' class PoFileTests(MessageCompilationTests): LOCALE = 'es_AR' MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' % LOCALE def test_bom_rejection(self): stderr = StringIO() with self.assertRaisesMessage(CommandError, 'compilemessages generated one or more errors.'): call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO(), stderr=stderr) self.assertIn('file has a BOM (Byte Order Mark)', stderr.getvalue()) self.assertFalse(os.path.exists(self.MO_FILE)) def test_no_write_access(self): mo_file_en = 'locale/en/LC_MESSAGES/django.mo' err_buffer = StringIO() # put file in read-only mode old_mode = os.stat(mo_file_en).st_mode os.chmod(mo_file_en, stat.S_IREAD) try: with self.assertRaisesMessage(CommandError, 'compilemessages generated one or more errors.'): call_command('compilemessages', locale=['en'], stderr=err_buffer, verbosity=0) self.assertIn('not writable location', err_buffer.getvalue()) finally: os.chmod(mo_file_en, old_mode) class PoFileContentsTests(MessageCompilationTests): # Ticket #11240 LOCALE = 'fr' MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' % LOCALE def test_percent_symbol_in_po_file(self): call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO()) self.assertTrue(os.path.exists(self.MO_FILE)) class MultipleLocaleCompilationTests(MessageCompilationTests): MO_FILE_HR = None MO_FILE_FR = None def setUp(self): super().setUp() localedir = os.path.join(self.test_dir, 'locale') self.MO_FILE_HR = os.path.join(localedir, 'hr/LC_MESSAGES/django.mo') self.MO_FILE_FR = os.path.join(localedir, 'fr/LC_MESSAGES/django.mo') def test_one_locale(self): with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]): call_command('compilemessages', locale=['hr'], stdout=StringIO()) self.assertTrue(os.path.exists(self.MO_FILE_HR)) def test_multiple_locales(self): with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]): call_command('compilemessages', locale=['hr', 'fr'], stdout=StringIO()) self.assertTrue(os.path.exists(self.MO_FILE_HR)) self.assertTrue(os.path.exists(self.MO_FILE_FR)) class ExcludedLocaleCompilationTests(MessageCompilationTests): work_subdir = 'exclude' MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' def setUp(self): super().setUp() copytree('canned_locale', 'locale') def test_command_help(self): with captured_stdout(), captured_stderr(): # `call_command` bypasses the parser; by calling # `execute_from_command_line` with the help subcommand we # ensure that there are no issues with the parser itself. execute_from_command_line(['django-admin', 'help', 'compilemessages']) def test_one_locale_excluded(self): call_command('compilemessages', exclude=['it'], stdout=StringIO()) self.assertTrue(os.path.exists(self.MO_FILE % 'en')) self.assertTrue(os.path.exists(self.MO_FILE % 'fr')) self.assertFalse(os.path.exists(self.MO_FILE % 'it')) def test_multiple_locales_excluded(self): call_command('compilemessages', exclude=['it', 'fr'], stdout=StringIO()) self.assertTrue(os.path.exists(self.MO_FILE % 'en')) self.assertFalse(os.path.exists(self.MO_FILE % 'fr')) self.assertFalse(os.path.exists(self.MO_FILE % 'it')) def test_one_locale_excluded_with_locale(self): call_command('compilemessages', locale=['en', 'fr'], exclude=['fr'], stdout=StringIO()) self.assertTrue(os.path.exists(self.MO_FILE % 'en')) self.assertFalse(os.path.exists(self.MO_FILE % 'fr')) self.assertFalse(os.path.exists(self.MO_FILE % 'it')) def test_multiple_locales_excluded_with_locale(self): call_command('compilemessages', locale=['en', 'fr', 'it'], exclude=['fr', 'it'], stdout=StringIO()) self.assertTrue(os.path.exists(self.MO_FILE % 'en')) self.assertFalse(os.path.exists(self.MO_FILE % 'fr')) self.assertFalse(os.path.exists(self.MO_FILE % 'it')) class IgnoreDirectoryCompilationTests(MessageCompilationTests): # Reuse the exclude directory since it contains some locale fixtures. work_subdir = 'exclude' MO_FILE = '%s/%s/LC_MESSAGES/django.mo' CACHE_DIR = Path('cache') / 'locale' NESTED_DIR = Path('outdated') / 'v1' / 'locale' def setUp(self): super().setUp() copytree('canned_locale', 'locale') copytree('canned_locale', self.CACHE_DIR) copytree('canned_locale', self.NESTED_DIR) def assertAllExist(self, dir, langs): self.assertTrue(all(Path(self.MO_FILE % (dir, lang)).exists() for lang in langs)) def assertNoneExist(self, dir, langs): self.assertTrue(all(Path(self.MO_FILE % (dir, lang)).exists() is False for lang in langs)) def test_one_locale_dir_ignored(self): call_command('compilemessages', ignore=['cache'], verbosity=0) self.assertAllExist('locale', ['en', 'fr', 'it']) self.assertNoneExist(self.CACHE_DIR, ['en', 'fr', 'it']) self.assertAllExist(self.NESTED_DIR, ['en', 'fr', 'it']) def test_multiple_locale_dirs_ignored(self): call_command('compilemessages', ignore=['cache/locale', 'outdated'], verbosity=0) self.assertAllExist('locale', ['en', 'fr', 'it']) self.assertNoneExist(self.CACHE_DIR, ['en', 'fr', 'it']) self.assertNoneExist(self.NESTED_DIR, ['en', 'fr', 'it']) def test_ignores_based_on_pattern(self): call_command('compilemessages', ignore=['*/locale'], verbosity=0) self.assertAllExist('locale', ['en', 'fr', 'it']) self.assertNoneExist(self.CACHE_DIR, ['en', 'fr', 'it']) self.assertNoneExist(self.NESTED_DIR, ['en', 'fr', 'it']) class CompilationErrorHandling(MessageCompilationTests): def test_error_reported_by_msgfmt(self): # po file contains wrong po formatting. with self.assertRaises(CommandError): call_command('compilemessages', locale=['ja'], verbosity=0, stderr=StringIO()) def test_msgfmt_error_including_non_ascii(self): # po file contains invalid msgstr content (triggers non-ascii error content). # Make sure the output of msgfmt is unaffected by the current locale. env = os.environ.copy() env.update({'LANG': 'C'}) with mock.patch('django.core.management.utils.run', lambda *args, **kwargs: run(*args, env=env, **kwargs)): cmd = MakeMessagesCommand() if cmd.gettext_version < (0, 18, 3): self.skipTest("python-brace-format is a recent gettext addition.") stderr = StringIO() with self.assertRaisesMessage(CommandError, 'compilemessages generated one or more errors'): call_command('compilemessages', locale=['ko'], stdout=StringIO(), stderr=stderr) self.assertIn("' cannot start a field name", stderr.getvalue()) class ProjectAndAppTests(MessageCompilationTests): LOCALE = 'ru' PROJECT_MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' % LOCALE APP_MO_FILE = 'app_with_locale/locale/%s/LC_MESSAGES/django.mo' % LOCALE class FuzzyTranslationTest(ProjectAndAppTests): def setUp(self): super().setUp() gettext_module._translations = {} # flush cache or test will be useless def test_nofuzzy_compiling(self): with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]): call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO()) with translation.override(self.LOCALE): self.assertEqual(gettext('Lenin'), 'Ленин') self.assertEqual(gettext('Vodka'), 'Vodka') def test_fuzzy_compiling(self): with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]): call_command('compilemessages', locale=[self.LOCALE], fuzzy=True, stdout=StringIO()) with translation.override(self.LOCALE): self.assertEqual(gettext('Lenin'), 'Ленин') self.assertEqual(gettext('Vodka'), 'Водка') class AppCompilationTest(ProjectAndAppTests): def test_app_locale_compiled(self): call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO()) self.assertTrue(os.path.exists(self.PROJECT_MO_FILE)) self.assertTrue(os.path.exists(self.APP_MO_FILE))
bcb70fe5c06b70b949417de4a54b37d318ec38eac7e3f6b4de55dcd1b8e2d6da
import collections.abc from datetime import datetime from math import ceil from operator import attrgetter from django.core.exceptions import FieldError from django.db import connection from django.db.models import Max from django.db.models.expressions import Exists, OuterRef from django.db.models.functions import Substr from django.test import TestCase, skipUnlessDBFeature from .models import ( Article, Author, Game, IsNullWithNoneAsRHS, Player, Season, Tag, ) class LookupTests(TestCase): @classmethod def setUpTestData(cls): # Create a few Authors. cls.au1 = Author.objects.create(name='Author 1', alias='a1') cls.au2 = Author.objects.create(name='Author 2', alias='a2') # Create a few Articles. cls.a1 = Article.objects.create( headline='Article 1', pub_date=datetime(2005, 7, 26), author=cls.au1, slug='a1', ) cls.a2 = Article.objects.create( headline='Article 2', pub_date=datetime(2005, 7, 27), author=cls.au1, slug='a2', ) cls.a3 = Article.objects.create( headline='Article 3', pub_date=datetime(2005, 7, 27), author=cls.au1, slug='a3', ) cls.a4 = Article.objects.create( headline='Article 4', pub_date=datetime(2005, 7, 28), author=cls.au1, slug='a4', ) cls.a5 = Article.objects.create( headline='Article 5', pub_date=datetime(2005, 8, 1, 9, 0), author=cls.au2, slug='a5', ) cls.a6 = Article.objects.create( headline='Article 6', pub_date=datetime(2005, 8, 1, 8, 0), author=cls.au2, slug='a6', ) cls.a7 = Article.objects.create( headline='Article 7', pub_date=datetime(2005, 7, 27), author=cls.au2, slug='a7', ) # Create a few Tags. cls.t1 = Tag.objects.create(name='Tag 1') cls.t1.articles.add(cls.a1, cls.a2, cls.a3) cls.t2 = Tag.objects.create(name='Tag 2') cls.t2.articles.add(cls.a3, cls.a4, cls.a5) cls.t3 = Tag.objects.create(name='Tag 3') cls.t3.articles.add(cls.a5, cls.a6, cls.a7) def test_exists(self): # We can use .exists() to check that there are some self.assertTrue(Article.objects.exists()) for a in Article.objects.all(): a.delete() # There should be none now! self.assertFalse(Article.objects.exists()) def test_lookup_int_as_str(self): # Integer value can be queried using string self.assertQuerysetEqual(Article.objects.filter(id__iexact=str(self.a1.id)), ['<Article: Article 1>']) @skipUnlessDBFeature('supports_date_lookup_using_string') def test_lookup_date_as_str(self): # A date lookup can be performed using a string search self.assertQuerysetEqual( Article.objects.filter(pub_date__startswith='2005'), [ '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ] ) def test_iterator(self): # Each QuerySet gets iterator(), which is a generator that "lazily" # returns results using database-level iteration. self.assertIsInstance(Article.objects.iterator(), collections.abc.Iterator) self.assertQuerysetEqual( Article.objects.iterator(), [ 'Article 5', 'Article 6', 'Article 4', 'Article 2', 'Article 3', 'Article 7', 'Article 1', ], transform=attrgetter('headline') ) # iterator() can be used on any QuerySet. self.assertQuerysetEqual( Article.objects.filter(headline__endswith='4').iterator(), ['Article 4'], transform=attrgetter('headline')) def test_count(self): # count() returns the number of objects matching search criteria. self.assertEqual(Article.objects.count(), 7) self.assertEqual(Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).count(), 3) self.assertEqual(Article.objects.filter(headline__startswith='Blah blah').count(), 0) # count() should respect sliced query sets. articles = Article.objects.all() self.assertEqual(articles.count(), 7) self.assertEqual(articles[:4].count(), 4) self.assertEqual(articles[1:100].count(), 6) self.assertEqual(articles[10:100].count(), 0) # Date and date/time lookups can also be done with strings. self.assertEqual(Article.objects.filter(pub_date__exact='2005-07-27 00:00:00').count(), 3) def test_in_bulk(self): # in_bulk() takes a list of IDs and returns a dictionary mapping IDs to objects. arts = Article.objects.in_bulk([self.a1.id, self.a2.id]) self.assertEqual(arts[self.a1.id], self.a1) self.assertEqual(arts[self.a2.id], self.a2) self.assertEqual( Article.objects.in_bulk(), { self.a1.id: self.a1, self.a2.id: self.a2, self.a3.id: self.a3, self.a4.id: self.a4, self.a5.id: self.a5, self.a6.id: self.a6, self.a7.id: self.a7, } ) self.assertEqual(Article.objects.in_bulk([self.a3.id]), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk({self.a3.id}), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk(frozenset([self.a3.id])), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk((self.a3.id,)), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk([1000]), {}) self.assertEqual(Article.objects.in_bulk([]), {}) self.assertEqual(Article.objects.in_bulk(iter([self.a1.id])), {self.a1.id: self.a1}) self.assertEqual(Article.objects.in_bulk(iter([])), {}) with self.assertRaises(TypeError): Article.objects.in_bulk(headline__startswith='Blah') def test_in_bulk_lots_of_ids(self): test_range = 2000 max_query_params = connection.features.max_query_params expected_num_queries = ceil(test_range / max_query_params) if max_query_params else 1 Author.objects.bulk_create([Author() for i in range(test_range - Author.objects.count())]) authors = {author.pk: author for author in Author.objects.all()} with self.assertNumQueries(expected_num_queries): self.assertEqual(Author.objects.in_bulk(authors), authors) def test_in_bulk_with_field(self): self.assertEqual( Article.objects.in_bulk([self.a1.slug, self.a2.slug, self.a3.slug], field_name='slug'), { self.a1.slug: self.a1, self.a2.slug: self.a2, self.a3.slug: self.a3, } ) def test_in_bulk_non_unique_field(self): msg = "in_bulk()'s field_name must be a unique field but 'author' isn't." with self.assertRaisesMessage(ValueError, msg): Article.objects.in_bulk([self.au1], field_name='author') def test_values(self): # values() returns a list of dictionaries instead of object instances -- # and you can specify which fields you want to retrieve. self.assertSequenceEqual( Article.objects.values('headline'), [ {'headline': 'Article 5'}, {'headline': 'Article 6'}, {'headline': 'Article 4'}, {'headline': 'Article 2'}, {'headline': 'Article 3'}, {'headline': 'Article 7'}, {'headline': 'Article 1'}, ], ) self.assertSequenceEqual( Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).values('id'), [{'id': self.a2.id}, {'id': self.a3.id}, {'id': self.a7.id}], ) self.assertSequenceEqual( Article.objects.values('id', 'headline'), [ {'id': self.a5.id, 'headline': 'Article 5'}, {'id': self.a6.id, 'headline': 'Article 6'}, {'id': self.a4.id, 'headline': 'Article 4'}, {'id': self.a2.id, 'headline': 'Article 2'}, {'id': self.a3.id, 'headline': 'Article 3'}, {'id': self.a7.id, 'headline': 'Article 7'}, {'id': self.a1.id, 'headline': 'Article 1'}, ], ) # You can use values() with iterator() for memory savings, # because iterator() uses database-level iteration. self.assertSequenceEqual( list(Article.objects.values('id', 'headline').iterator()), [ {'headline': 'Article 5', 'id': self.a5.id}, {'headline': 'Article 6', 'id': self.a6.id}, {'headline': 'Article 4', 'id': self.a4.id}, {'headline': 'Article 2', 'id': self.a2.id}, {'headline': 'Article 3', 'id': self.a3.id}, {'headline': 'Article 7', 'id': self.a7.id}, {'headline': 'Article 1', 'id': self.a1.id}, ], ) # The values() method works with "extra" fields specified in extra(select). self.assertSequenceEqual( Article.objects.extra(select={'id_plus_one': 'id + 1'}).values('id', 'id_plus_one'), [ {'id': self.a5.id, 'id_plus_one': self.a5.id + 1}, {'id': self.a6.id, 'id_plus_one': self.a6.id + 1}, {'id': self.a4.id, 'id_plus_one': self.a4.id + 1}, {'id': self.a2.id, 'id_plus_one': self.a2.id + 1}, {'id': self.a3.id, 'id_plus_one': self.a3.id + 1}, {'id': self.a7.id, 'id_plus_one': self.a7.id + 1}, {'id': self.a1.id, 'id_plus_one': self.a1.id + 1}, ], ) data = { 'id_plus_one': 'id+1', 'id_plus_two': 'id+2', 'id_plus_three': 'id+3', 'id_plus_four': 'id+4', 'id_plus_five': 'id+5', 'id_plus_six': 'id+6', 'id_plus_seven': 'id+7', 'id_plus_eight': 'id+8', } self.assertSequenceEqual( Article.objects.filter(id=self.a1.id).extra(select=data).values(*data), [{ 'id_plus_one': self.a1.id + 1, 'id_plus_two': self.a1.id + 2, 'id_plus_three': self.a1.id + 3, 'id_plus_four': self.a1.id + 4, 'id_plus_five': self.a1.id + 5, 'id_plus_six': self.a1.id + 6, 'id_plus_seven': self.a1.id + 7, 'id_plus_eight': self.a1.id + 8, }], ) # You can specify fields from forward and reverse relations, just like filter(). self.assertSequenceEqual( Article.objects.values('headline', 'author__name'), [ {'headline': self.a5.headline, 'author__name': self.au2.name}, {'headline': self.a6.headline, 'author__name': self.au2.name}, {'headline': self.a4.headline, 'author__name': self.au1.name}, {'headline': self.a2.headline, 'author__name': self.au1.name}, {'headline': self.a3.headline, 'author__name': self.au1.name}, {'headline': self.a7.headline, 'author__name': self.au2.name}, {'headline': self.a1.headline, 'author__name': self.au1.name}, ], ) self.assertSequenceEqual( Author.objects.values('name', 'article__headline').order_by('name', 'article__headline'), [ {'name': self.au1.name, 'article__headline': self.a1.headline}, {'name': self.au1.name, 'article__headline': self.a2.headline}, {'name': self.au1.name, 'article__headline': self.a3.headline}, {'name': self.au1.name, 'article__headline': self.a4.headline}, {'name': self.au2.name, 'article__headline': self.a5.headline}, {'name': self.au2.name, 'article__headline': self.a6.headline}, {'name': self.au2.name, 'article__headline': self.a7.headline}, ], ) self.assertSequenceEqual( ( Author.objects .values('name', 'article__headline', 'article__tag__name') .order_by('name', 'article__headline', 'article__tag__name') ), [ {'name': self.au1.name, 'article__headline': self.a1.headline, 'article__tag__name': self.t1.name}, {'name': self.au1.name, 'article__headline': self.a2.headline, 'article__tag__name': self.t1.name}, {'name': self.au1.name, 'article__headline': self.a3.headline, 'article__tag__name': self.t1.name}, {'name': self.au1.name, 'article__headline': self.a3.headline, 'article__tag__name': self.t2.name}, {'name': self.au1.name, 'article__headline': self.a4.headline, 'article__tag__name': self.t2.name}, {'name': self.au2.name, 'article__headline': self.a5.headline, 'article__tag__name': self.t2.name}, {'name': self.au2.name, 'article__headline': self.a5.headline, 'article__tag__name': self.t3.name}, {'name': self.au2.name, 'article__headline': self.a6.headline, 'article__tag__name': self.t3.name}, {'name': self.au2.name, 'article__headline': self.a7.headline, 'article__tag__name': self.t3.name}, ], ) # However, an exception FieldDoesNotExist will be thrown if you specify # a nonexistent field name in values() (a field that is neither in the # model nor in extra(select)). msg = ( "Cannot resolve keyword 'id_plus_two' into field. Choices are: " "author, author_id, headline, id, id_plus_one, pub_date, slug, tag" ) with self.assertRaisesMessage(FieldError, msg): Article.objects.extra(select={'id_plus_one': 'id + 1'}).values('id', 'id_plus_two') # If you don't specify field names to values(), all are returned. self.assertSequenceEqual( Article.objects.filter(id=self.a5.id).values(), [{ 'id': self.a5.id, 'author_id': self.au2.id, 'headline': 'Article 5', 'pub_date': datetime(2005, 8, 1, 9, 0), 'slug': 'a5', }], ) def test_values_list(self): # values_list() is similar to values(), except that the results are # returned as a list of tuples, rather than a list of dictionaries. # Within each tuple, the order of the elements is the same as the order # of fields in the values_list() call. self.assertSequenceEqual( Article.objects.values_list('headline'), [ ('Article 5',), ('Article 6',), ('Article 4',), ('Article 2',), ('Article 3',), ('Article 7',), ('Article 1',), ], ) self.assertSequenceEqual( Article.objects.values_list('id').order_by('id'), [(self.a1.id,), (self.a2.id,), (self.a3.id,), (self.a4.id,), (self.a5.id,), (self.a6.id,), (self.a7.id,)], ) self.assertSequenceEqual( Article.objects.values_list('id', flat=True).order_by('id'), [self.a1.id, self.a2.id, self.a3.id, self.a4.id, self.a5.id, self.a6.id, self.a7.id], ) self.assertSequenceEqual( Article.objects.extra(select={'id_plus_one': 'id+1'}).order_by('id').values_list('id'), [(self.a1.id,), (self.a2.id,), (self.a3.id,), (self.a4.id,), (self.a5.id,), (self.a6.id,), (self.a7.id,)], ) self.assertSequenceEqual( Article.objects.extra(select={'id_plus_one': 'id+1'}).order_by('id').values_list('id_plus_one', 'id'), [ (self.a1.id + 1, self.a1.id), (self.a2.id + 1, self.a2.id), (self.a3.id + 1, self.a3.id), (self.a4.id + 1, self.a4.id), (self.a5.id + 1, self.a5.id), (self.a6.id + 1, self.a6.id), (self.a7.id + 1, self.a7.id) ], ) self.assertSequenceEqual( Article.objects.extra(select={'id_plus_one': 'id+1'}).order_by('id').values_list('id', 'id_plus_one'), [ (self.a1.id, self.a1.id + 1), (self.a2.id, self.a2.id + 1), (self.a3.id, self.a3.id + 1), (self.a4.id, self.a4.id + 1), (self.a5.id, self.a5.id + 1), (self.a6.id, self.a6.id + 1), (self.a7.id, self.a7.id + 1) ], ) args = ('name', 'article__headline', 'article__tag__name') self.assertSequenceEqual( Author.objects.values_list(*args).order_by(*args), [ (self.au1.name, self.a1.headline, self.t1.name), (self.au1.name, self.a2.headline, self.t1.name), (self.au1.name, self.a3.headline, self.t1.name), (self.au1.name, self.a3.headline, self.t2.name), (self.au1.name, self.a4.headline, self.t2.name), (self.au2.name, self.a5.headline, self.t2.name), (self.au2.name, self.a5.headline, self.t3.name), (self.au2.name, self.a6.headline, self.t3.name), (self.au2.name, self.a7.headline, self.t3.name), ], ) with self.assertRaises(TypeError): Article.objects.values_list('id', 'headline', flat=True) def test_get_next_previous_by(self): # Every DateField and DateTimeField creates get_next_by_FOO() and # get_previous_by_FOO() methods. In the case of identical date values, # these methods will use the ID as a fallback check. This guarantees # that no records are skipped or duplicated. self.assertEqual(repr(self.a1.get_next_by_pub_date()), '<Article: Article 2>') self.assertEqual(repr(self.a2.get_next_by_pub_date()), '<Article: Article 3>') self.assertEqual(repr(self.a2.get_next_by_pub_date(headline__endswith='6')), '<Article: Article 6>') self.assertEqual(repr(self.a3.get_next_by_pub_date()), '<Article: Article 7>') self.assertEqual(repr(self.a4.get_next_by_pub_date()), '<Article: Article 6>') with self.assertRaises(Article.DoesNotExist): self.a5.get_next_by_pub_date() self.assertEqual(repr(self.a6.get_next_by_pub_date()), '<Article: Article 5>') self.assertEqual(repr(self.a7.get_next_by_pub_date()), '<Article: Article 4>') self.assertEqual(repr(self.a7.get_previous_by_pub_date()), '<Article: Article 3>') self.assertEqual(repr(self.a6.get_previous_by_pub_date()), '<Article: Article 4>') self.assertEqual(repr(self.a5.get_previous_by_pub_date()), '<Article: Article 6>') self.assertEqual(repr(self.a4.get_previous_by_pub_date()), '<Article: Article 7>') self.assertEqual(repr(self.a3.get_previous_by_pub_date()), '<Article: Article 2>') self.assertEqual(repr(self.a2.get_previous_by_pub_date()), '<Article: Article 1>') def test_escaping(self): # Underscores, percent signs and backslashes have special meaning in the # underlying SQL code, but Django handles the quoting of them automatically. Article.objects.create(headline='Article_ with underscore', pub_date=datetime(2005, 11, 20)) self.assertQuerysetEqual( Article.objects.filter(headline__startswith='Article'), [ '<Article: Article_ with underscore>', '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ] ) self.assertQuerysetEqual( Article.objects.filter(headline__startswith='Article_'), ['<Article: Article_ with underscore>'] ) Article.objects.create(headline='Article% with percent sign', pub_date=datetime(2005, 11, 21)) self.assertQuerysetEqual( Article.objects.filter(headline__startswith='Article'), [ '<Article: Article% with percent sign>', '<Article: Article_ with underscore>', '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ] ) self.assertQuerysetEqual( Article.objects.filter(headline__startswith='Article%'), ['<Article: Article% with percent sign>'] ) Article.objects.create(headline='Article with \\ backslash', pub_date=datetime(2005, 11, 22)) self.assertQuerysetEqual( Article.objects.filter(headline__contains='\\'), [r'<Article: Article with \ backslash>'] ) def test_exclude(self): Article.objects.bulk_create([ Article(headline='Article_ with underscore', pub_date=datetime(2005, 11, 20)), Article(headline='Article% with percent sign', pub_date=datetime(2005, 11, 21)), Article(headline='Article with \\ backslash', pub_date=datetime(2005, 11, 22)), ]) # exclude() is the opposite of filter() when doing lookups: self.assertQuerysetEqual( Article.objects.filter(headline__contains='Article').exclude(headline__contains='with'), [ '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ] ) self.assertQuerysetEqual( Article.objects.exclude(headline__startswith="Article_"), [ '<Article: Article with \\ backslash>', '<Article: Article% with percent sign>', '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ] ) self.assertQuerysetEqual( Article.objects.exclude(headline="Article 7"), [ '<Article: Article with \\ backslash>', '<Article: Article% with percent sign>', '<Article: Article_ with underscore>', '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 1>', ] ) def test_none(self): # none() returns a QuerySet that behaves like any other QuerySet object self.assertQuerysetEqual(Article.objects.none(), []) self.assertQuerysetEqual(Article.objects.none().filter(headline__startswith='Article'), []) self.assertQuerysetEqual(Article.objects.filter(headline__startswith='Article').none(), []) self.assertEqual(Article.objects.none().count(), 0) self.assertEqual(Article.objects.none().update(headline="This should not take effect"), 0) self.assertQuerysetEqual(Article.objects.none().iterator(), []) def test_in(self): # using __in with an empty list should return an empty query set self.assertQuerysetEqual(Article.objects.filter(id__in=[]), []) self.assertQuerysetEqual( Article.objects.exclude(id__in=[]), [ '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ] ) def test_in_different_database(self): with self.assertRaisesMessage( ValueError, "Subqueries aren't allowed across different databases. Force the " "inner query to be evaluated using `list(inner_query)`." ): list(Article.objects.filter(id__in=Article.objects.using('other').all())) def test_in_keeps_value_ordering(self): query = Article.objects.filter(slug__in=['a%d' % i for i in range(1, 8)]).values('pk').query self.assertIn(' IN (a1, a2, a3, a4, a5, a6, a7) ', str(query)) def test_error_messages(self): # Programming errors are pointed out with nice error messages with self.assertRaisesMessage( FieldError, "Cannot resolve keyword 'pub_date_year' into field. Choices are: " "author, author_id, headline, id, pub_date, slug, tag" ): Article.objects.filter(pub_date_year='2005').count() def test_unsupported_lookups(self): with self.assertRaisesMessage( FieldError, "Unsupported lookup 'starts' for CharField or join on the field " "not permitted, perhaps you meant startswith or istartswith?" ): Article.objects.filter(headline__starts='Article') with self.assertRaisesMessage( FieldError, "Unsupported lookup 'is_null' for DateTimeField or join on the field " "not permitted, perhaps you meant isnull?" ): Article.objects.filter(pub_date__is_null=True) with self.assertRaisesMessage( FieldError, "Unsupported lookup 'gobbledygook' for DateTimeField or join on the field " "not permitted." ): Article.objects.filter(pub_date__gobbledygook='blahblah') def test_relation_nested_lookup_error(self): # An invalid nested lookup on a related field raises a useful error. msg = 'Related Field got invalid lookup: editor' with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(author__editor__name='James') msg = 'Related Field got invalid lookup: foo' with self.assertRaisesMessage(FieldError, msg): Tag.objects.filter(articles__foo='bar') def test_regex(self): # Create some articles with a bit more interesting headlines for testing field lookups: for a in Article.objects.all(): a.delete() now = datetime.now() Article.objects.bulk_create([ Article(pub_date=now, headline='f'), Article(pub_date=now, headline='fo'), Article(pub_date=now, headline='foo'), Article(pub_date=now, headline='fooo'), Article(pub_date=now, headline='hey-Foo'), Article(pub_date=now, headline='bar'), Article(pub_date=now, headline='AbBa'), Article(pub_date=now, headline='baz'), Article(pub_date=now, headline='baxZ'), ]) # zero-or-more self.assertQuerysetEqual( Article.objects.filter(headline__regex=r'fo*'), ['<Article: f>', '<Article: fo>', '<Article: foo>', '<Article: fooo>'] ) self.assertQuerysetEqual( Article.objects.filter(headline__iregex=r'fo*'), [ '<Article: f>', '<Article: fo>', '<Article: foo>', '<Article: fooo>', '<Article: hey-Foo>', ] ) # one-or-more self.assertQuerysetEqual( Article.objects.filter(headline__regex=r'fo+'), ['<Article: fo>', '<Article: foo>', '<Article: fooo>'] ) # wildcard self.assertQuerysetEqual( Article.objects.filter(headline__regex=r'fooo?'), ['<Article: foo>', '<Article: fooo>'] ) # leading anchor self.assertQuerysetEqual( Article.objects.filter(headline__regex=r'^b'), ['<Article: bar>', '<Article: baxZ>', '<Article: baz>'] ) self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'^a'), ['<Article: AbBa>']) # trailing anchor self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'z$'), ['<Article: baz>']) self.assertQuerysetEqual( Article.objects.filter(headline__iregex=r'z$'), ['<Article: baxZ>', '<Article: baz>'] ) # character sets self.assertQuerysetEqual( Article.objects.filter(headline__regex=r'ba[rz]'), ['<Article: bar>', '<Article: baz>'] ) self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'ba.[RxZ]'), ['<Article: baxZ>']) self.assertQuerysetEqual( Article.objects.filter(headline__iregex=r'ba[RxZ]'), ['<Article: bar>', '<Article: baxZ>', '<Article: baz>'] ) # and more articles: Article.objects.bulk_create([ Article(pub_date=now, headline='foobar'), Article(pub_date=now, headline='foobaz'), Article(pub_date=now, headline='ooF'), Article(pub_date=now, headline='foobarbaz'), Article(pub_date=now, headline='zoocarfaz'), Article(pub_date=now, headline='barfoobaz'), Article(pub_date=now, headline='bazbaRFOO'), ]) # alternation self.assertQuerysetEqual( Article.objects.filter(headline__regex=r'oo(f|b)'), [ '<Article: barfoobaz>', '<Article: foobar>', '<Article: foobarbaz>', '<Article: foobaz>', ] ) self.assertQuerysetEqual( Article.objects.filter(headline__iregex=r'oo(f|b)'), [ '<Article: barfoobaz>', '<Article: foobar>', '<Article: foobarbaz>', '<Article: foobaz>', '<Article: ooF>', ] ) self.assertQuerysetEqual( Article.objects.filter(headline__regex=r'^foo(f|b)'), ['<Article: foobar>', '<Article: foobarbaz>', '<Article: foobaz>'] ) # greedy matching self.assertQuerysetEqual( Article.objects.filter(headline__regex=r'b.*az'), [ '<Article: barfoobaz>', '<Article: baz>', '<Article: bazbaRFOO>', '<Article: foobarbaz>', '<Article: foobaz>', ] ) self.assertQuerysetEqual( Article.objects.filter(headline__iregex=r'b.*ar'), [ '<Article: bar>', '<Article: barfoobaz>', '<Article: bazbaRFOO>', '<Article: foobar>', '<Article: foobarbaz>', ] ) @skipUnlessDBFeature('supports_regex_backreferencing') def test_regex_backreferencing(self): # grouping and backreferences now = datetime.now() Article.objects.bulk_create([ Article(pub_date=now, headline='foobar'), Article(pub_date=now, headline='foobaz'), Article(pub_date=now, headline='ooF'), Article(pub_date=now, headline='foobarbaz'), Article(pub_date=now, headline='zoocarfaz'), Article(pub_date=now, headline='barfoobaz'), Article(pub_date=now, headline='bazbaRFOO'), ]) self.assertQuerysetEqual( Article.objects.filter(headline__regex=r'b(.).*b\1'), ['<Article: barfoobaz>', '<Article: bazbaRFOO>', '<Article: foobarbaz>'] ) def test_regex_null(self): """ A regex lookup does not fail on null/None values """ Season.objects.create(year=2012, gt=None) self.assertQuerysetEqual(Season.objects.filter(gt__regex=r'^$'), []) def test_regex_non_string(self): """ A regex lookup does not fail on non-string fields """ Season.objects.create(year=2013, gt=444) self.assertQuerysetEqual(Season.objects.filter(gt__regex=r'^444$'), ['<Season: 2013>']) def test_regex_non_ascii(self): """ A regex lookup does not trip on non-ASCII characters. """ Player.objects.create(name='\u2660') Player.objects.get(name__regex='\u2660') def test_nonfield_lookups(self): """ A lookup query containing non-fields raises the proper exception. """ msg = "Unsupported lookup 'blahblah' for CharField or join on the field not permitted." with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(headline__blahblah=99) with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(headline__blahblah__exact=99) msg = ( "Cannot resolve keyword 'blahblah' into field. Choices are: " "author, author_id, headline, id, pub_date, slug, tag" ) with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(blahblah=99) def test_lookup_collision(self): """ Genuine field names don't collide with built-in lookup types ('year', 'gt', 'range', 'in' etc.) (#11670). """ # 'gt' is used as a code number for the year, e.g. 111=>2009. season_2009 = Season.objects.create(year=2009, gt=111) season_2009.games.create(home="Houston Astros", away="St. Louis Cardinals") season_2010 = Season.objects.create(year=2010, gt=222) season_2010.games.create(home="Houston Astros", away="Chicago Cubs") season_2010.games.create(home="Houston Astros", away="Milwaukee Brewers") season_2010.games.create(home="Houston Astros", away="St. Louis Cardinals") season_2011 = Season.objects.create(year=2011, gt=333) season_2011.games.create(home="Houston Astros", away="St. Louis Cardinals") season_2011.games.create(home="Houston Astros", away="Milwaukee Brewers") hunter_pence = Player.objects.create(name="Hunter Pence") hunter_pence.games.set(Game.objects.filter(season__year__in=[2009, 2010])) pudge = Player.objects.create(name="Ivan Rodriquez") pudge.games.set(Game.objects.filter(season__year=2009)) pedro_feliz = Player.objects.create(name="Pedro Feliz") pedro_feliz.games.set(Game.objects.filter(season__year__in=[2011])) johnson = Player.objects.create(name="Johnson") johnson.games.set(Game.objects.filter(season__year__in=[2011])) # Games in 2010 self.assertEqual(Game.objects.filter(season__year=2010).count(), 3) self.assertEqual(Game.objects.filter(season__year__exact=2010).count(), 3) self.assertEqual(Game.objects.filter(season__gt=222).count(), 3) self.assertEqual(Game.objects.filter(season__gt__exact=222).count(), 3) # Games in 2011 self.assertEqual(Game.objects.filter(season__year=2011).count(), 2) self.assertEqual(Game.objects.filter(season__year__exact=2011).count(), 2) self.assertEqual(Game.objects.filter(season__gt=333).count(), 2) self.assertEqual(Game.objects.filter(season__gt__exact=333).count(), 2) self.assertEqual(Game.objects.filter(season__year__gt=2010).count(), 2) self.assertEqual(Game.objects.filter(season__gt__gt=222).count(), 2) # Games played in 2010 and 2011 self.assertEqual(Game.objects.filter(season__year__in=[2010, 2011]).count(), 5) self.assertEqual(Game.objects.filter(season__year__gt=2009).count(), 5) self.assertEqual(Game.objects.filter(season__gt__in=[222, 333]).count(), 5) self.assertEqual(Game.objects.filter(season__gt__gt=111).count(), 5) # Players who played in 2009 self.assertEqual(Player.objects.filter(games__season__year=2009).distinct().count(), 2) self.assertEqual(Player.objects.filter(games__season__year__exact=2009).distinct().count(), 2) self.assertEqual(Player.objects.filter(games__season__gt=111).distinct().count(), 2) self.assertEqual(Player.objects.filter(games__season__gt__exact=111).distinct().count(), 2) # Players who played in 2010 self.assertEqual(Player.objects.filter(games__season__year=2010).distinct().count(), 1) self.assertEqual(Player.objects.filter(games__season__year__exact=2010).distinct().count(), 1) self.assertEqual(Player.objects.filter(games__season__gt=222).distinct().count(), 1) self.assertEqual(Player.objects.filter(games__season__gt__exact=222).distinct().count(), 1) # Players who played in 2011 self.assertEqual(Player.objects.filter(games__season__year=2011).distinct().count(), 2) self.assertEqual(Player.objects.filter(games__season__year__exact=2011).distinct().count(), 2) self.assertEqual(Player.objects.filter(games__season__gt=333).distinct().count(), 2) self.assertEqual(Player.objects.filter(games__season__year__gt=2010).distinct().count(), 2) self.assertEqual(Player.objects.filter(games__season__gt__gt=222).distinct().count(), 2) def test_chain_date_time_lookups(self): self.assertQuerysetEqual( Article.objects.filter(pub_date__month__gt=7), ['<Article: Article 5>', '<Article: Article 6>'], ordered=False ) self.assertQuerysetEqual( Article.objects.filter(pub_date__day__gte=27), ['<Article: Article 2>', '<Article: Article 3>', '<Article: Article 4>', '<Article: Article 7>'], ordered=False ) self.assertQuerysetEqual( Article.objects.filter(pub_date__hour__lt=8), ['<Article: Article 1>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 4>', '<Article: Article 7>'], ordered=False ) self.assertQuerysetEqual( Article.objects.filter(pub_date__minute__lte=0), ['<Article: Article 1>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 4>', '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 7>'], ordered=False ) def test_exact_none_transform(self): """Transforms are used for __exact=None.""" Season.objects.create(year=1, nulled_text_field='not null') self.assertFalse(Season.objects.filter(nulled_text_field__isnull=True)) self.assertTrue(Season.objects.filter(nulled_text_field__nulled__isnull=True)) self.assertTrue(Season.objects.filter(nulled_text_field__nulled__exact=None)) self.assertTrue(Season.objects.filter(nulled_text_field__nulled=None)) def test_exact_sliced_queryset_limit_one(self): self.assertCountEqual( Article.objects.filter(author=Author.objects.all()[:1]), [self.a1, self.a2, self.a3, self.a4] ) def test_exact_sliced_queryset_limit_one_offset(self): self.assertCountEqual( Article.objects.filter(author=Author.objects.all()[1:2]), [self.a5, self.a6, self.a7] ) def test_exact_sliced_queryset_not_limited_to_one(self): msg = ( 'The QuerySet value for an exact lookup must be limited to one ' 'result using slicing.' ) with self.assertRaisesMessage(ValueError, msg): list(Article.objects.filter(author=Author.objects.all()[:2])) with self.assertRaisesMessage(ValueError, msg): list(Article.objects.filter(author=Author.objects.all()[1:])) def test_custom_field_none_rhs(self): """ __exact=value is transformed to __isnull=True if Field.get_prep_value() converts value to None. """ season = Season.objects.create(year=2012, nulled_text_field=None) self.assertTrue(Season.objects.filter(pk=season.pk, nulled_text_field__isnull=True)) self.assertTrue(Season.objects.filter(pk=season.pk, nulled_text_field='')) def test_pattern_lookups_with_substr(self): a = Author.objects.create(name='John Smith', alias='Johx') b = Author.objects.create(name='Rhonda Simpson', alias='sonx') tests = ( ('startswith', [a]), ('istartswith', [a]), ('contains', [a, b]), ('icontains', [a, b]), ('endswith', [b]), ('iendswith', [b]), ) for lookup, result in tests: with self.subTest(lookup=lookup): authors = Author.objects.filter(**{'name__%s' % lookup: Substr('alias', 1, 3)}) self.assertCountEqual(authors, result) def test_custom_lookup_none_rhs(self): """Lookup.can_use_none_as_rhs=True allows None as a lookup value.""" season = Season.objects.create(year=2012, nulled_text_field=None) query = Season.objects.get_queryset().query field = query.model._meta.get_field('nulled_text_field') self.assertIsInstance(query.build_lookup(['isnull_none_rhs'], field, None), IsNullWithNoneAsRHS) self.assertTrue(Season.objects.filter(pk=season.pk, nulled_text_field__isnull_none_rhs=True)) def test_exact_exists(self): qs = Article.objects.filter(pk=OuterRef('pk')) seasons = Season.objects.annotate( pk_exists=Exists(qs), ).filter( pk_exists=Exists(qs), ) self.assertCountEqual(seasons, Season.objects.all()) def test_nested_outerref_lhs(self): tag = Tag.objects.create(name=self.au1.alias) tag.articles.add(self.a1) qs = Tag.objects.annotate( has_author_alias_match=Exists( Article.objects.annotate( author_exists=Exists( Author.objects.filter(alias=OuterRef(OuterRef('name'))) ), ).filter(author_exists=True) ), ) self.assertEqual(qs.get(has_author_alias_match=True), tag) def test_exact_query_rhs_with_selected_columns(self): newest_author = Author.objects.create(name='Author 2') authors_max_ids = Author.objects.filter( name='Author 2', ).values( 'name', ).annotate( max_id=Max('id'), ).values('max_id') authors = Author.objects.filter(id=authors_max_ids[:1]) self.assertEqual(authors.get(), newest_author)
6af51e7542c62ad0426a7fb35a1d7132f10532b6e62c2ea5b0a8dbd2a87ea5b3
from django.db.models.query_utils import InvalidQuery from django.test import TestCase from .models import ( BigChild, Child, ChildProxy, Primary, RefreshPrimaryProxy, Secondary, ) class AssertionMixin: def assert_delayed(self, obj, num): """ Instances with deferred fields look the same as normal instances when we examine attribute values. Therefore, this method returns the number of deferred fields on returned instances. """ count = len(obj.get_deferred_fields()) self.assertEqual(count, num) class DeferTests(AssertionMixin, TestCase): @classmethod def setUpTestData(cls): cls.s1 = Secondary.objects.create(first="x1", second="y1") cls.p1 = Primary.objects.create(name="p1", value="xx", related=cls.s1) def test_defer(self): qs = Primary.objects.all() self.assert_delayed(qs.defer("name")[0], 1) self.assert_delayed(qs.defer("name").get(pk=self.p1.pk), 1) self.assert_delayed(qs.defer("related__first")[0], 0) self.assert_delayed(qs.defer("name").defer("value")[0], 2) def test_only(self): qs = Primary.objects.all() self.assert_delayed(qs.only("name")[0], 2) self.assert_delayed(qs.only("name").get(pk=self.p1.pk), 2) self.assert_delayed(qs.only("name").only("value")[0], 2) self.assert_delayed(qs.only("related__first")[0], 2) # Using 'pk' with only() should result in 3 deferred fields, namely all # of them except the model's primary key see #15494 self.assert_delayed(qs.only("pk")[0], 3) # You can use 'pk' with reverse foreign key lookups. # The related_id is always set even if it's not fetched from the DB, # so pk and related_id are not deferred. self.assert_delayed(self.s1.primary_set.all().only('pk')[0], 2) def test_defer_only_chaining(self): qs = Primary.objects.all() self.assert_delayed(qs.only("name", "value").defer("name")[0], 2) self.assert_delayed(qs.defer("name").only("value", "name")[0], 2) self.assert_delayed(qs.defer("name").only("value")[0], 2) self.assert_delayed(qs.only("name").defer("value")[0], 2) def test_defer_on_an_already_deferred_field(self): qs = Primary.objects.all() self.assert_delayed(qs.defer("name")[0], 1) self.assert_delayed(qs.defer("name").defer("name")[0], 1) def test_defer_none_to_clear_deferred_set(self): qs = Primary.objects.all() self.assert_delayed(qs.defer("name", "value")[0], 2) self.assert_delayed(qs.defer(None)[0], 0) self.assert_delayed(qs.only("name").defer(None)[0], 0) def test_only_none_raises_error(self): msg = 'Cannot pass None as an argument to only().' with self.assertRaisesMessage(TypeError, msg): Primary.objects.only(None) def test_defer_extra(self): qs = Primary.objects.all() self.assert_delayed(qs.defer("name").extra(select={"a": 1})[0], 1) self.assert_delayed(qs.extra(select={"a": 1}).defer("name")[0], 1) def test_defer_values_does_not_defer(self): # User values() won't defer anything (you get the full list of # dictionaries back), but it still works. self.assertEqual(Primary.objects.defer("name").values()[0], { "id": self.p1.id, "name": "p1", "value": "xx", "related_id": self.s1.id, }) def test_only_values_does_not_defer(self): self.assertEqual(Primary.objects.only("name").values()[0], { "id": self.p1.id, "name": "p1", "value": "xx", "related_id": self.s1.id, }) def test_get(self): # Using defer() and only() with get() is also valid. qs = Primary.objects.all() self.assert_delayed(qs.defer("name").get(pk=self.p1.pk), 1) self.assert_delayed(qs.only("name").get(pk=self.p1.pk), 2) def test_defer_with_select_related(self): obj = Primary.objects.select_related().defer("related__first", "related__second")[0] self.assert_delayed(obj.related, 2) self.assert_delayed(obj, 0) def test_only_with_select_related(self): obj = Primary.objects.select_related().only("related__first")[0] self.assert_delayed(obj, 2) self.assert_delayed(obj.related, 1) self.assertEqual(obj.related_id, self.s1.pk) self.assertEqual(obj.name, "p1") def test_defer_select_related_raises_invalid_query(self): msg = ( 'Field Primary.related cannot be both deferred and traversed ' 'using select_related at the same time.' ) with self.assertRaisesMessage(InvalidQuery, msg): Primary.objects.defer("related").select_related("related")[0] def test_only_select_related_raises_invalid_query(self): msg = ( 'Field Primary.related cannot be both deferred and traversed using ' 'select_related at the same time.' ) with self.assertRaisesMessage(InvalidQuery, msg): Primary.objects.only("name").select_related("related")[0] def test_defer_foreign_keys_are_deferred_and_not_traversed(self): # select_related() overrides defer(). with self.assertNumQueries(1): obj = Primary.objects.defer("related").select_related()[0] self.assert_delayed(obj, 1) self.assertEqual(obj.related.id, self.s1.pk) def test_saving_object_with_deferred_field(self): # Saving models with deferred fields is possible (but inefficient, # since every field has to be retrieved first). Primary.objects.create(name="p2", value="xy", related=self.s1) obj = Primary.objects.defer("value").get(name="p2") obj.name = "a new name" obj.save() self.assertQuerysetEqual( Primary.objects.all(), [ "p1", "a new name", ], lambda p: p.name, ordered=False, ) def test_defer_baseclass_when_subclass_has_no_added_fields(self): # Regression for #10572 - A subclass with no extra fields can defer # fields from the base class Child.objects.create(name="c1", value="foo", related=self.s1) # You can defer a field on a baseclass when the subclass has no fields obj = Child.objects.defer("value").get(name="c1") self.assert_delayed(obj, 1) self.assertEqual(obj.name, "c1") self.assertEqual(obj.value, "foo") def test_only_baseclass_when_subclass_has_no_added_fields(self): # You can retrieve a single column on a base class with no fields Child.objects.create(name="c1", value="foo", related=self.s1) obj = Child.objects.only("name").get(name="c1") # on an inherited model, its PK is also fetched, hence '3' deferred fields. self.assert_delayed(obj, 3) self.assertEqual(obj.name, "c1") self.assertEqual(obj.value, "foo") class BigChildDeferTests(AssertionMixin, TestCase): @classmethod def setUpTestData(cls): cls.s1 = Secondary.objects.create(first="x1", second="y1") BigChild.objects.create(name="b1", value="foo", related=cls.s1, other="bar") def test_defer_baseclass_when_subclass_has_added_field(self): # You can defer a field on a baseclass obj = BigChild.objects.defer("value").get(name="b1") self.assert_delayed(obj, 1) self.assertEqual(obj.name, "b1") self.assertEqual(obj.value, "foo") self.assertEqual(obj.other, "bar") def test_defer_subclass(self): # You can defer a field on a subclass obj = BigChild.objects.defer("other").get(name="b1") self.assert_delayed(obj, 1) self.assertEqual(obj.name, "b1") self.assertEqual(obj.value, "foo") self.assertEqual(obj.other, "bar") def test_defer_subclass_both(self): # Deferring fields from both superclass and subclass works. obj = BigChild.objects.defer("other", "value").get(name="b1") self.assert_delayed(obj, 2) def test_only_baseclass_when_subclass_has_added_field(self): # You can retrieve a single field on a baseclass obj = BigChild.objects.only("name").get(name="b1") # when inherited model, its PK is also fetched, hence '4' deferred fields. self.assert_delayed(obj, 4) self.assertEqual(obj.name, "b1") self.assertEqual(obj.value, "foo") self.assertEqual(obj.other, "bar") def test_only_subclass(self): # You can retrieve a single field on a subclass obj = BigChild.objects.only("other").get(name="b1") self.assert_delayed(obj, 4) self.assertEqual(obj.name, "b1") self.assertEqual(obj.value, "foo") self.assertEqual(obj.other, "bar") class TestDefer2(AssertionMixin, TestCase): def test_defer_proxy(self): """ Ensure select_related together with only on a proxy model behaves as expected. See #17876. """ related = Secondary.objects.create(first='x1', second='x2') ChildProxy.objects.create(name='p1', value='xx', related=related) children = ChildProxy.objects.all().select_related().only('id', 'name') self.assertEqual(len(children), 1) child = children[0] self.assert_delayed(child, 2) self.assertEqual(child.name, 'p1') self.assertEqual(child.value, 'xx') def test_defer_inheritance_pk_chaining(self): """ When an inherited model is fetched from the DB, its PK is also fetched. When getting the PK of the parent model it is useful to use the already fetched parent model PK if it happens to be available. """ s1 = Secondary.objects.create(first="x1", second="y1") bc = BigChild.objects.create(name='b1', value='foo', related=s1, other='bar') bc_deferred = BigChild.objects.only('name').get(pk=bc.pk) with self.assertNumQueries(0): bc_deferred.id self.assertEqual(bc_deferred.pk, bc_deferred.id) def test_eq(self): s1 = Secondary.objects.create(first="x1", second="y1") s1_defer = Secondary.objects.only('pk').get(pk=s1.pk) self.assertEqual(s1, s1_defer) self.assertEqual(s1_defer, s1) def test_refresh_not_loading_deferred_fields(self): s = Secondary.objects.create() rf = Primary.objects.create(name='foo', value='bar', related=s) rf2 = Primary.objects.only('related', 'value').get() rf.name = 'new foo' rf.value = 'new bar' rf.save() with self.assertNumQueries(1): rf2.refresh_from_db() self.assertEqual(rf2.value, 'new bar') with self.assertNumQueries(1): self.assertEqual(rf2.name, 'new foo') def test_custom_refresh_on_deferred_loading(self): s = Secondary.objects.create() rf = RefreshPrimaryProxy.objects.create(name='foo', value='bar', related=s) rf2 = RefreshPrimaryProxy.objects.only('related').get() rf.name = 'new foo' rf.value = 'new bar' rf.save() with self.assertNumQueries(1): # Customized refresh_from_db() reloads all deferred fields on # access of any of them. self.assertEqual(rf2.name, 'new foo') self.assertEqual(rf2.value, 'new bar')
051de7cda3f3990304b53db7b212027d43bb943f042ce4eb36bc9640179c3463
from asgiref.sync import async_to_sync from django.core.exceptions import SynchronousOnlyOperation from django.test import SimpleTestCase from django.utils.asyncio import async_unsafe from .models import SimpleModel class DatabaseConnectionTest(SimpleTestCase): """A database connection cannot be used in an async context.""" @async_to_sync async def test_get_async_connection(self): with self.assertRaises(SynchronousOnlyOperation): list(SimpleModel.objects.all()) class AsyncUnsafeTest(SimpleTestCase): """ async_unsafe decorator should work correctly and returns the correct message. """ @async_unsafe def dangerous_method(self): return True @async_to_sync async def test_async_unsafe(self): # async_unsafe decorator catches bad access and returns the right # message. msg = ( 'You cannot call this from an async context - use a thread or ' 'sync_to_async.' ) with self.assertRaisesMessage(SynchronousOnlyOperation, msg): self.dangerous_method()
b8e5942784b9da5d0d533c70a6695c4505426000b04b6168d7b893f54dcd5ca5
from django.db import models class SimpleModel(models.Model): field = models.IntegerField()
6dc59b3816715b39de695ddde82e83623a3f78608496906cd8c5c12d3ecdceae
""" The tests are shared with contenttypes_tests and so shouldn't import or reference any models directly. Subclasses should inherit django.test.TestCase. """ from operator import attrgetter class BaseOrderWithRespectToTests: # Hook to allow subclasses to run these tests with alternate models. Answer = None Post = None Question = None @classmethod def setUpTestData(cls): cls.q1 = cls.Question.objects.create(text="Which Beatle starts with the letter 'R'?") cls.Answer.objects.create(text="John", question=cls.q1) cls.Answer.objects.create(text="Paul", question=cls.q1) cls.Answer.objects.create(text="George", question=cls.q1) cls.Answer.objects.create(text="Ringo", question=cls.q1) def test_default_to_insertion_order(self): # Answers will always be ordered in the order they were inserted. self.assertQuerysetEqual( self.q1.answer_set.all(), [ "John", "Paul", "George", "Ringo", ], attrgetter("text"), ) def test_previous_and_next_in_order(self): # We can retrieve the answers related to a particular object, in the # order they were created, once we have a particular object. a1 = self.q1.answer_set.all()[0] self.assertEqual(a1.text, "John") self.assertEqual(a1.get_next_in_order().text, "Paul") a2 = list(self.q1.answer_set.all())[-1] self.assertEqual(a2.text, "Ringo") self.assertEqual(a2.get_previous_in_order().text, "George") def test_item_ordering(self): # We can retrieve the ordering of the queryset from a particular item. a1 = self.q1.answer_set.all()[1] id_list = [o.pk for o in self.q1.answer_set.all()] self.assertSequenceEqual(a1.question.get_answer_order(), id_list) # It doesn't matter which answer we use to check the order, it will # always be the same. a2 = self.Answer.objects.create(text="Number five", question=self.q1) self.assertEqual(list(a1.question.get_answer_order()), list(a2.question.get_answer_order())) def test_set_order_unrelated_object(self): """An answer that's not related isn't updated.""" q = self.Question.objects.create(text='other') a = self.Answer.objects.create(text='Number five', question=q) self.q1.set_answer_order([o.pk for o in self.q1.answer_set.all()] + [a.pk]) self.assertEqual(self.Answer.objects.get(pk=a.pk)._order, 0) def test_change_ordering(self): # The ordering can be altered a = self.Answer.objects.create(text="Number five", question=self.q1) # Swap the last two items in the order list id_list = [o.pk for o in self.q1.answer_set.all()] x = id_list.pop() id_list.insert(-1, x) # By default, the ordering is different from the swapped version self.assertNotEqual(list(a.question.get_answer_order()), id_list) # Change the ordering to the swapped version - # this changes the ordering of the queryset. a.question.set_answer_order(id_list) self.assertQuerysetEqual( self.q1.answer_set.all(), [ "John", "Paul", "George", "Number five", "Ringo" ], attrgetter("text") ) def test_recursive_ordering(self): p1 = self.Post.objects.create(title="1") p2 = self.Post.objects.create(title="2") p1_1 = self.Post.objects.create(title="1.1", parent=p1) p1_2 = self.Post.objects.create(title="1.2", parent=p1) self.Post.objects.create(title="2.1", parent=p2) p1_3 = self.Post.objects.create(title="1.3", parent=p1) self.assertSequenceEqual(p1.get_post_order(), [p1_1.pk, p1_2.pk, p1_3.pk]) def test_delete_and_insert(self): q1 = self.Question.objects.create(text='What is your favorite color?') q2 = self.Question.objects.create(text='What color is it?') a1 = self.Answer.objects.create(text='Blue', question=q1) a2 = self.Answer.objects.create(text='Red', question=q1) a3 = self.Answer.objects.create(text='Green', question=q1) a4 = self.Answer.objects.create(text='Yellow', question=q1) self.assertSequenceEqual(q1.answer_set.all(), [a1, a2, a3, a4]) a3.question = q2 a3.save() a1.delete() new_answer = self.Answer.objects.create(text='Black', question=q1) self.assertSequenceEqual(q1.answer_set.all(), [a2, a4, new_answer])
4d788c1e6fc8a43f7b0e4873c29ba5419f252dda9e77993a03fc5e66931bf0dd
import datetime from django.contrib import admin from django.contrib.admin.models import LogEntry from django.contrib.admin.options import IncorrectLookupParameters from django.contrib.admin.templatetags.admin_list import pagination from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.admin.views.main import ALL_VAR, SEARCH_VAR from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.messages.storage.cookie import CookieStorage from django.db import connection, models from django.db.models import F from django.db.models.fields import Field, IntegerField from django.db.models.functions import Upper from django.db.models.lookups import Contains, Exact from django.template import Context, Template, TemplateSyntaxError from django.test import TestCase, override_settings from django.test.client import RequestFactory from django.test.utils import ( CaptureQueriesContext, isolate_apps, register_lookup, ) from django.urls import reverse from django.utils import formats from .admin import ( BandAdmin, ChildAdmin, ChordsBandAdmin, ConcertAdmin, CustomPaginationAdmin, CustomPaginator, DynamicListDisplayChildAdmin, DynamicListDisplayLinksChildAdmin, DynamicListFilterChildAdmin, DynamicSearchFieldsChildAdmin, EmptyValueChildAdmin, EventAdmin, FilteredChildAdmin, GroupAdmin, InvitationAdmin, NoListDisplayLinksParentAdmin, ParentAdmin, QuartetAdmin, SwallowAdmin, site as custom_site, ) from .models import ( Band, CharPK, Child, ChordsBand, ChordsMusician, Concert, CustomIdUser, Event, Genre, Group, Invitation, Membership, Musician, OrderedObject, Parent, Quartet, Swallow, SwallowOneToOne, UnorderedObject, ) def build_tbody_html(pk, href, extra_fields): return ( '<tbody><tr class="row1">' '<td class="action-checkbox">' '<input type="checkbox" name="_selected_action" value="{}" ' 'class="action-select"></td>' '<th class="field-name"><a href="{}">name</a></th>' '{}</tr></tbody>' ).format(pk, href, extra_fields) @override_settings(ROOT_URLCONF="admin_changelist.urls") class ChangeListTests(TestCase): factory = RequestFactory() @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser(username='super', email='[email protected]', password='xxx') def _create_superuser(self, username): return User.objects.create_superuser(username=username, email='[email protected]', password='xxx') def _mocked_authenticated_request(self, url, user): request = self.factory.get(url) request.user = user return request def test_specified_ordering_by_f_expression(self): class OrderedByFBandAdmin(admin.ModelAdmin): list_display = ['name', 'genres', 'nr_of_members'] ordering = ( F('nr_of_members').desc(nulls_last=True), Upper(F('name')).asc(), F('genres').asc(), ) m = OrderedByFBandAdmin(Band, custom_site) request = self.factory.get('/band/') request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.get_ordering_field_columns(), {3: 'desc', 2: 'asc'}) def test_specified_ordering_by_f_expression_without_asc_desc(self): class OrderedByFBandAdmin(admin.ModelAdmin): list_display = ['name', 'genres', 'nr_of_members'] ordering = (F('nr_of_members'), Upper('name'), F('genres')) m = OrderedByFBandAdmin(Band, custom_site) request = self.factory.get('/band/') request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.get_ordering_field_columns(), {3: 'asc', 2: 'asc'}) def test_select_related_preserved(self): """ Regression test for #10348: ChangeList.get_queryset() shouldn't overwrite a custom select_related provided by ModelAdmin.get_queryset(). """ m = ChildAdmin(Child, custom_site) request = self.factory.get('/child/') request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.query.select_related, {'parent': {}}) def test_select_related_as_tuple(self): ia = InvitationAdmin(Invitation, custom_site) request = self.factory.get('/invitation/') request.user = self.superuser cl = ia.get_changelist_instance(request) self.assertEqual(cl.queryset.query.select_related, {'player': {}}) def test_select_related_as_empty_tuple(self): ia = InvitationAdmin(Invitation, custom_site) ia.list_select_related = () request = self.factory.get('/invitation/') request.user = self.superuser cl = ia.get_changelist_instance(request) self.assertIs(cl.queryset.query.select_related, False) def test_get_select_related_custom_method(self): class GetListSelectRelatedAdmin(admin.ModelAdmin): list_display = ('band', 'player') def get_list_select_related(self, request): return ('band', 'player') ia = GetListSelectRelatedAdmin(Invitation, custom_site) request = self.factory.get('/invitation/') request.user = self.superuser cl = ia.get_changelist_instance(request) self.assertEqual(cl.queryset.query.select_related, {'player': {}, 'band': {}}) def test_result_list_empty_changelist_value(self): """ Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored for relationship fields """ new_child = Child.objects.create(name='name', parent=None) request = self.factory.get('/child/') request.user = self.superuser m = ChildAdmin(Child, custom_site) cl = m.get_changelist_instance(request) cl.formset = None template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') context = Context({'cl': cl, 'opts': Child._meta}) table_output = template.render(context) link = reverse('admin:admin_changelist_child_change', args=(new_child.id,)) row_html = build_tbody_html(new_child.id, link, '<td class="field-parent nowrap">-</td>') self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output) def test_result_list_set_empty_value_display_on_admin_site(self): """ Empty value display can be set on AdminSite. """ new_child = Child.objects.create(name='name', parent=None) request = self.factory.get('/child/') request.user = self.superuser # Set a new empty display value on AdminSite. admin.site.empty_value_display = '???' m = ChildAdmin(Child, admin.site) cl = m.get_changelist_instance(request) cl.formset = None template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') context = Context({'cl': cl, 'opts': Child._meta}) table_output = template.render(context) link = reverse('admin:admin_changelist_child_change', args=(new_child.id,)) row_html = build_tbody_html(new_child.id, link, '<td class="field-parent nowrap">???</td>') self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output) def test_result_list_set_empty_value_display_in_model_admin(self): """ Empty value display can be set in ModelAdmin or individual fields. """ new_child = Child.objects.create(name='name', parent=None) request = self.factory.get('/child/') request.user = self.superuser m = EmptyValueChildAdmin(Child, admin.site) cl = m.get_changelist_instance(request) cl.formset = None template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') context = Context({'cl': cl, 'opts': Child._meta}) table_output = template.render(context) link = reverse('admin:admin_changelist_child_change', args=(new_child.id,)) row_html = build_tbody_html( new_child.id, link, '<td class="field-age_display">&amp;dagger;</td>' '<td class="field-age">-empty-</td>' ) self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output) def test_result_list_html(self): """ Inclusion tag result_list generates a table when with default ModelAdmin settings. """ new_parent = Parent.objects.create(name='parent') new_child = Child.objects.create(name='name', parent=new_parent) request = self.factory.get('/child/') request.user = self.superuser m = ChildAdmin(Child, custom_site) cl = m.get_changelist_instance(request) cl.formset = None template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') context = Context({'cl': cl, 'opts': Child._meta}) table_output = template.render(context) link = reverse('admin:admin_changelist_child_change', args=(new_child.id,)) row_html = build_tbody_html(new_child.id, link, '<td class="field-parent nowrap">%s</td>' % new_parent) self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output) def test_result_list_editable_html(self): """ Regression tests for #11791: Inclusion tag result_list generates a table and this checks that the items are nested within the table element tags. Also a regression test for #13599, verifies that hidden fields when list_editable is enabled are rendered in a div outside the table. """ new_parent = Parent.objects.create(name='parent') new_child = Child.objects.create(name='name', parent=new_parent) request = self.factory.get('/child/') request.user = self.superuser m = ChildAdmin(Child, custom_site) # Test with list_editable fields m.list_display = ['id', 'name', 'parent'] m.list_display_links = ['id'] m.list_editable = ['name'] cl = m.get_changelist_instance(request) FormSet = m.get_changelist_formset(request) cl.formset = FormSet(queryset=cl.result_list) template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') context = Context({'cl': cl, 'opts': Child._meta}) table_output = template.render(context) # make sure that hidden fields are in the correct place hiddenfields_div = ( '<div class="hiddenfields">' '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id">' '</div>' ) % new_child.id self.assertInHTML(hiddenfields_div, table_output, msg_prefix='Failed to find hidden fields') # make sure that list editable fields are rendered in divs correctly editable_name_field = ( '<input name="form-0-name" value="name" class="vTextField" ' 'maxlength="30" type="text" id="id_form-0-name">' ) self.assertInHTML( '<td class="field-name">%s</td>' % editable_name_field, table_output, msg_prefix='Failed to find "name" list_editable field', ) def test_result_list_editable(self): """ Regression test for #14312: list_editable with pagination """ new_parent = Parent.objects.create(name='parent') for i in range(200): Child.objects.create(name='name %s' % i, parent=new_parent) request = self.factory.get('/child/', data={'p': -1}) # Anything outside range request.user = self.superuser m = ChildAdmin(Child, custom_site) # Test with list_editable fields m.list_display = ['id', 'name', 'parent'] m.list_display_links = ['id'] m.list_editable = ['name'] with self.assertRaises(IncorrectLookupParameters): m.get_changelist_instance(request) def test_custom_paginator(self): new_parent = Parent.objects.create(name='parent') for i in range(200): Child.objects.create(name='name %s' % i, parent=new_parent) request = self.factory.get('/child/') request.user = self.superuser m = CustomPaginationAdmin(Child, custom_site) cl = m.get_changelist_instance(request) cl.get_results(request) self.assertIsInstance(cl.paginator, CustomPaginator) def test_distinct_for_m2m_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't appear more than once. Basic ManyToMany. """ blues = Genre.objects.create(name='Blues') band = Band.objects.create(name='B.B. King Review', nr_of_members=11) band.genres.add(blues) band.genres.add(blues) m = BandAdmin(Band, custom_site) request = self.factory.get('/band/', data={'genres': blues.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) cl.get_results(request) # There's only one Group instance self.assertEqual(cl.result_count, 1) def test_distinct_for_through_m2m_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't appear more than once. With an intermediate model. """ lead = Musician.objects.create(name='Vox') band = Group.objects.create(name='The Hype') Membership.objects.create(group=band, music=lead, role='lead voice') Membership.objects.create(group=band, music=lead, role='bass player') m = GroupAdmin(Group, custom_site) request = self.factory.get('/group/', data={'members': lead.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) cl.get_results(request) # There's only one Group instance self.assertEqual(cl.result_count, 1) def test_distinct_for_through_m2m_at_second_level_in_list_filter(self): """ When using a ManyToMany in list_filter at the second level behind a ForeignKey, distinct() must be called and results shouldn't appear more than once. """ lead = Musician.objects.create(name='Vox') band = Group.objects.create(name='The Hype') Concert.objects.create(name='Woodstock', group=band) Membership.objects.create(group=band, music=lead, role='lead voice') Membership.objects.create(group=band, music=lead, role='bass player') m = ConcertAdmin(Concert, custom_site) request = self.factory.get('/concert/', data={'group__members': lead.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) cl.get_results(request) # There's only one Concert instance self.assertEqual(cl.result_count, 1) def test_distinct_for_inherited_m2m_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't appear more than once. Model managed in the admin inherits from the one that defines the relationship. """ lead = Musician.objects.create(name='John') four = Quartet.objects.create(name='The Beatles') Membership.objects.create(group=four, music=lead, role='lead voice') Membership.objects.create(group=four, music=lead, role='guitar player') m = QuartetAdmin(Quartet, custom_site) request = self.factory.get('/quartet/', data={'members': lead.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) cl.get_results(request) # There's only one Quartet instance self.assertEqual(cl.result_count, 1) def test_distinct_for_m2m_to_inherited_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't appear more than once. Target of the relationship inherits from another. """ lead = ChordsMusician.objects.create(name='Player A') three = ChordsBand.objects.create(name='The Chords Trio') Invitation.objects.create(band=three, player=lead, instrument='guitar') Invitation.objects.create(band=three, player=lead, instrument='bass') m = ChordsBandAdmin(ChordsBand, custom_site) request = self.factory.get('/chordsband/', data={'members': lead.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) cl.get_results(request) # There's only one ChordsBand instance self.assertEqual(cl.result_count, 1) def test_distinct_for_non_unique_related_object_in_list_filter(self): """ Regressions tests for #15819: If a field listed in list_filters is a non-unique related object, distinct() must be called. """ parent = Parent.objects.create(name='Mary') # Two children with the same name Child.objects.create(parent=parent, name='Daniel') Child.objects.create(parent=parent, name='Daniel') m = ParentAdmin(Parent, custom_site) request = self.factory.get('/parent/', data={'child__name': 'Daniel'}) request.user = self.superuser cl = m.get_changelist_instance(request) # Make sure distinct() was called self.assertEqual(cl.queryset.count(), 1) def test_changelist_search_form_validation(self): m = ConcertAdmin(Concert, custom_site) tests = [ ({SEARCH_VAR: '\x00'}, 'Null characters are not allowed.'), ({SEARCH_VAR: 'some\x00thing'}, 'Null characters are not allowed.'), ] for case, error in tests: with self.subTest(case=case): request = self.factory.get('/concert/', case) request.user = self.superuser request._messages = CookieStorage(request) m.get_changelist_instance(request) messages = [m.message for m in request._messages] self.assertEqual(1, len(messages)) self.assertEqual(error, messages[0]) def test_distinct_for_non_unique_related_object_in_search_fields(self): """ Regressions tests for #15819: If a field listed in search_fields is a non-unique related object, distinct() must be called. """ parent = Parent.objects.create(name='Mary') Child.objects.create(parent=parent, name='Danielle') Child.objects.create(parent=parent, name='Daniel') m = ParentAdmin(Parent, custom_site) request = self.factory.get('/parent/', data={SEARCH_VAR: 'daniel'}) request.user = self.superuser cl = m.get_changelist_instance(request) # Make sure distinct() was called self.assertEqual(cl.queryset.count(), 1) def test_distinct_for_many_to_many_at_second_level_in_search_fields(self): """ When using a ManyToMany in search_fields at the second level behind a ForeignKey, distinct() must be called and results shouldn't appear more than once. """ lead = Musician.objects.create(name='Vox') band = Group.objects.create(name='The Hype') Concert.objects.create(name='Woodstock', group=band) Membership.objects.create(group=band, music=lead, role='lead voice') Membership.objects.create(group=band, music=lead, role='bass player') m = ConcertAdmin(Concert, custom_site) request = self.factory.get('/concert/', data={SEARCH_VAR: 'vox'}) request.user = self.superuser cl = m.get_changelist_instance(request) # There's only one Concert instance self.assertEqual(cl.queryset.count(), 1) def test_pk_in_search_fields(self): band = Group.objects.create(name='The Hype') Concert.objects.create(name='Woodstock', group=band) m = ConcertAdmin(Concert, custom_site) m.search_fields = ['group__pk'] request = self.factory.get('/concert/', data={SEARCH_VAR: band.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 1) request = self.factory.get('/concert/', data={SEARCH_VAR: band.pk + 5}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 0) def test_builtin_lookup_in_search_fields(self): band = Group.objects.create(name='The Hype') concert = Concert.objects.create(name='Woodstock', group=band) m = ConcertAdmin(Concert, custom_site) m.search_fields = ['name__iexact'] request = self.factory.get('/', data={SEARCH_VAR: 'woodstock'}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [concert]) request = self.factory.get('/', data={SEARCH_VAR: 'wood'}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, []) def test_custom_lookup_in_search_fields(self): band = Group.objects.create(name='The Hype') concert = Concert.objects.create(name='Woodstock', group=band) m = ConcertAdmin(Concert, custom_site) m.search_fields = ['group__name__cc'] with register_lookup(Field, Contains, lookup_name='cc'): request = self.factory.get('/', data={SEARCH_VAR: 'Hype'}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [concert]) request = self.factory.get('/', data={SEARCH_VAR: 'Woodstock'}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, []) def test_spanning_relations_with_custom_lookup_in_search_fields(self): hype = Group.objects.create(name='The Hype') concert = Concert.objects.create(name='Woodstock', group=hype) vox = Musician.objects.create(name='Vox', age=20) Membership.objects.create(music=vox, group=hype) # Register a custom lookup on IntegerField to ensure that field # traversing logic in ModelAdmin.get_search_results() works. with register_lookup(IntegerField, Exact, lookup_name='exactly'): m = ConcertAdmin(Concert, custom_site) m.search_fields = ['group__members__age__exactly'] request = self.factory.get('/', data={SEARCH_VAR: '20'}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [concert]) request = self.factory.get('/', data={SEARCH_VAR: '21'}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, []) def test_custom_lookup_with_pk_shortcut(self): self.assertEqual(CharPK._meta.pk.name, 'char_pk') # Not equal to 'pk'. m = admin.ModelAdmin(CustomIdUser, custom_site) abc = CharPK.objects.create(char_pk='abc') abcd = CharPK.objects.create(char_pk='abcd') m = admin.ModelAdmin(CharPK, custom_site) m.search_fields = ['pk__exact'] request = self.factory.get('/', data={SEARCH_VAR: 'abc'}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [abc]) request = self.factory.get('/', data={SEARCH_VAR: 'abcd'}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [abcd]) def test_no_distinct_for_m2m_in_list_filter_without_params(self): """ If a ManyToManyField is in list_filter but isn't in any lookup params, the changelist's query shouldn't have distinct. """ m = BandAdmin(Band, custom_site) for lookup_params in ({}, {'name': 'test'}): request = self.factory.get('/band/', lookup_params) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertFalse(cl.queryset.query.distinct) # A ManyToManyField in params does have distinct applied. request = self.factory.get('/band/', {'genres': '0'}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertTrue(cl.queryset.query.distinct) def test_pagination(self): """ Regression tests for #12893: Pagination in admins changelist doesn't use queryset set by modeladmin. """ parent = Parent.objects.create(name='anything') for i in range(30): Child.objects.create(name='name %s' % i, parent=parent) Child.objects.create(name='filtered %s' % i, parent=parent) request = self.factory.get('/child/') request.user = self.superuser # Test default queryset m = ChildAdmin(Child, custom_site) cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 60) self.assertEqual(cl.paginator.count, 60) self.assertEqual(list(cl.paginator.page_range), [1, 2, 3, 4, 5, 6]) # Test custom queryset m = FilteredChildAdmin(Child, custom_site) cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 30) self.assertEqual(cl.paginator.count, 30) self.assertEqual(list(cl.paginator.page_range), [1, 2, 3]) def test_computed_list_display_localization(self): """ Regression test for #13196: output of functions should be localized in the changelist. """ self.client.force_login(self.superuser) event = Event.objects.create(date=datetime.date.today()) response = self.client.get(reverse('admin:admin_changelist_event_changelist')) self.assertContains(response, formats.localize(event.date)) self.assertNotContains(response, str(event.date)) def test_dynamic_list_display(self): """ Regression tests for #14206: dynamic list_display support. """ parent = Parent.objects.create(name='parent') for i in range(10): Child.objects.create(name='child %s' % i, parent=parent) user_noparents = self._create_superuser('noparents') user_parents = self._create_superuser('parents') # Test with user 'noparents' m = custom_site._registry[Child] request = self._mocked_authenticated_request('/child/', user_noparents) response = m.changelist_view(request) self.assertNotContains(response, 'Parent object') list_display = m.get_list_display(request) list_display_links = m.get_list_display_links(request, list_display) self.assertEqual(list_display, ['name', 'age']) self.assertEqual(list_display_links, ['name']) # Test with user 'parents' m = DynamicListDisplayChildAdmin(Child, custom_site) request = self._mocked_authenticated_request('/child/', user_parents) response = m.changelist_view(request) self.assertContains(response, 'Parent object') custom_site.unregister(Child) list_display = m.get_list_display(request) list_display_links = m.get_list_display_links(request, list_display) self.assertEqual(list_display, ('parent', 'name', 'age')) self.assertEqual(list_display_links, ['parent']) # Test default implementation custom_site.register(Child, ChildAdmin) m = custom_site._registry[Child] request = self._mocked_authenticated_request('/child/', user_noparents) response = m.changelist_view(request) self.assertContains(response, 'Parent object') def test_show_all(self): parent = Parent.objects.create(name='anything') for i in range(30): Child.objects.create(name='name %s' % i, parent=parent) Child.objects.create(name='filtered %s' % i, parent=parent) # Add "show all" parameter to request request = self.factory.get('/child/', data={ALL_VAR: ''}) request.user = self.superuser # Test valid "show all" request (number of total objects is under max) m = ChildAdmin(Child, custom_site) m.list_max_show_all = 200 # 200 is the max we'll pass to ChangeList cl = m.get_changelist_instance(request) cl.get_results(request) self.assertEqual(len(cl.result_list), 60) # Test invalid "show all" request (number of total objects over max) # falls back to paginated pages m = ChildAdmin(Child, custom_site) m.list_max_show_all = 30 # 30 is the max we'll pass to ChangeList for this test cl = m.get_changelist_instance(request) cl.get_results(request) self.assertEqual(len(cl.result_list), 10) def test_dynamic_list_display_links(self): """ Regression tests for #16257: dynamic list_display_links support. """ parent = Parent.objects.create(name='parent') for i in range(1, 10): Child.objects.create(id=i, name='child %s' % i, parent=parent, age=i) m = DynamicListDisplayLinksChildAdmin(Child, custom_site) superuser = self._create_superuser('superuser') request = self._mocked_authenticated_request('/child/', superuser) response = m.changelist_view(request) for i in range(1, 10): link = reverse('admin:admin_changelist_child_change', args=(i,)) self.assertContains(response, '<a href="%s">%s</a>' % (link, i)) list_display = m.get_list_display(request) list_display_links = m.get_list_display_links(request, list_display) self.assertEqual(list_display, ('parent', 'name', 'age')) self.assertEqual(list_display_links, ['age']) def test_no_list_display_links(self): """#15185 -- Allow no links from the 'change list' view grid.""" p = Parent.objects.create(name='parent') m = NoListDisplayLinksParentAdmin(Parent, custom_site) superuser = self._create_superuser('superuser') request = self._mocked_authenticated_request('/parent/', superuser) response = m.changelist_view(request) link = reverse('admin:admin_changelist_parent_change', args=(p.pk,)) self.assertNotContains(response, '<a href="%s">' % link) def test_tuple_list_display(self): swallow = Swallow.objects.create(origin='Africa', load='12.34', speed='22.2') swallow2 = Swallow.objects.create(origin='Africa', load='12.34', speed='22.2') swallow_o2o = SwallowOneToOne.objects.create(swallow=swallow2) model_admin = SwallowAdmin(Swallow, custom_site) superuser = self._create_superuser('superuser') request = self._mocked_authenticated_request('/swallow/', superuser) response = model_admin.changelist_view(request) # just want to ensure it doesn't blow up during rendering self.assertContains(response, str(swallow.origin)) self.assertContains(response, str(swallow.load)) self.assertContains(response, str(swallow.speed)) # Reverse one-to-one relations should work. self.assertContains(response, '<td class="field-swallowonetoone">-</td>') self.assertContains(response, '<td class="field-swallowonetoone">%s</td>' % swallow_o2o) def test_multiuser_edit(self): """ Simultaneous edits of list_editable fields on the changelist by different users must not result in one user's edits creating a new object instead of modifying the correct existing object (#11313). """ # To replicate this issue, simulate the following steps: # 1. User1 opens an admin changelist with list_editable fields. # 2. User2 edits object "Foo" such that it moves to another page in # the pagination order and saves. # 3. User1 edits object "Foo" and saves. # 4. The edit made by User1 does not get applied to object "Foo" but # instead is used to create a new object (bug). # For this test, order the changelist by the 'speed' attribute and # display 3 objects per page (SwallowAdmin.list_per_page = 3). # Setup the test to reflect the DB state after step 2 where User2 has # edited the first swallow object's speed from '4' to '1'. a = Swallow.objects.create(origin='Swallow A', load=4, speed=1) b = Swallow.objects.create(origin='Swallow B', load=2, speed=2) c = Swallow.objects.create(origin='Swallow C', load=5, speed=5) d = Swallow.objects.create(origin='Swallow D', load=9, speed=9) superuser = self._create_superuser('superuser') self.client.force_login(superuser) changelist_url = reverse('admin:admin_changelist_swallow_changelist') # Send the POST from User1 for step 3. It's still using the changelist # ordering from before User2's edits in step 2. data = { 'form-TOTAL_FORMS': '3', 'form-INITIAL_FORMS': '3', 'form-MIN_NUM_FORMS': '0', 'form-MAX_NUM_FORMS': '1000', 'form-0-uuid': str(d.pk), 'form-1-uuid': str(c.pk), 'form-2-uuid': str(a.pk), 'form-0-load': '9.0', 'form-0-speed': '9.0', 'form-1-load': '5.0', 'form-1-speed': '5.0', 'form-2-load': '5.0', 'form-2-speed': '4.0', '_save': 'Save', } response = self.client.post(changelist_url, data, follow=True, extra={'o': '-2'}) # The object User1 edited in step 3 is displayed on the changelist and # has the correct edits applied. self.assertContains(response, '1 swallow was changed successfully.') self.assertContains(response, a.origin) a.refresh_from_db() self.assertEqual(a.load, float(data['form-2-load'])) self.assertEqual(a.speed, float(data['form-2-speed'])) b.refresh_from_db() self.assertEqual(b.load, 2) self.assertEqual(b.speed, 2) c.refresh_from_db() self.assertEqual(c.load, float(data['form-1-load'])) self.assertEqual(c.speed, float(data['form-1-speed'])) d.refresh_from_db() self.assertEqual(d.load, float(data['form-0-load'])) self.assertEqual(d.speed, float(data['form-0-speed'])) # No new swallows were created. self.assertEqual(len(Swallow.objects.all()), 4) def test_get_edited_object_ids(self): a = Swallow.objects.create(origin='Swallow A', load=4, speed=1) b = Swallow.objects.create(origin='Swallow B', load=2, speed=2) c = Swallow.objects.create(origin='Swallow C', load=5, speed=5) superuser = self._create_superuser('superuser') self.client.force_login(superuser) changelist_url = reverse('admin:admin_changelist_swallow_changelist') m = SwallowAdmin(Swallow, custom_site) data = { 'form-TOTAL_FORMS': '3', 'form-INITIAL_FORMS': '3', 'form-MIN_NUM_FORMS': '0', 'form-MAX_NUM_FORMS': '1000', 'form-0-uuid': str(a.pk), 'form-1-uuid': str(b.pk), 'form-2-uuid': str(c.pk), 'form-0-load': '9.0', 'form-0-speed': '9.0', 'form-1-load': '5.0', 'form-1-speed': '5.0', 'form-2-load': '5.0', 'form-2-speed': '4.0', '_save': 'Save', } request = self.factory.post(changelist_url, data=data) pks = m._get_edited_object_pks(request, prefix='form') self.assertEqual(sorted(pks), sorted([str(a.pk), str(b.pk), str(c.pk)])) def test_get_list_editable_queryset(self): a = Swallow.objects.create(origin='Swallow A', load=4, speed=1) Swallow.objects.create(origin='Swallow B', load=2, speed=2) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '2', 'form-MIN_NUM_FORMS': '0', 'form-MAX_NUM_FORMS': '1000', 'form-0-uuid': str(a.pk), 'form-0-load': '10', '_save': 'Save', } superuser = self._create_superuser('superuser') self.client.force_login(superuser) changelist_url = reverse('admin:admin_changelist_swallow_changelist') m = SwallowAdmin(Swallow, custom_site) request = self.factory.post(changelist_url, data=data) queryset = m._get_list_editable_queryset(request, prefix='form') self.assertEqual(queryset.count(), 1) data['form-0-uuid'] = 'INVALD_PRIMARY_KEY' # The unfiltered queryset is returned if there's invalid data. request = self.factory.post(changelist_url, data=data) queryset = m._get_list_editable_queryset(request, prefix='form') self.assertEqual(queryset.count(), 2) def test_changelist_view_list_editable_changed_objects_uses_filter(self): """list_editable edits use a filtered queryset to limit memory usage.""" a = Swallow.objects.create(origin='Swallow A', load=4, speed=1) Swallow.objects.create(origin='Swallow B', load=2, speed=2) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '2', 'form-MIN_NUM_FORMS': '0', 'form-MAX_NUM_FORMS': '1000', 'form-0-uuid': str(a.pk), 'form-0-load': '10', '_save': 'Save', } superuser = self._create_superuser('superuser') self.client.force_login(superuser) changelist_url = reverse('admin:admin_changelist_swallow_changelist') with CaptureQueriesContext(connection) as context: response = self.client.post(changelist_url, data=data) self.assertEqual(response.status_code, 200) self.assertIn('WHERE', context.captured_queries[4]['sql']) self.assertIn('IN', context.captured_queries[4]['sql']) # Check only the first few characters since the UUID may have dashes. self.assertIn(str(a.pk)[:8], context.captured_queries[4]['sql']) def test_deterministic_order_for_unordered_model(self): """ The primary key is used in the ordering of the changelist's results to guarantee a deterministic order, even when the model doesn't have any default ordering defined (#17198). """ superuser = self._create_superuser('superuser') for counter in range(1, 51): UnorderedObject.objects.create(id=counter, bool=True) class UnorderedObjectAdmin(admin.ModelAdmin): list_per_page = 10 def check_results_order(ascending=False): custom_site.register(UnorderedObject, UnorderedObjectAdmin) model_admin = UnorderedObjectAdmin(UnorderedObject, custom_site) counter = 0 if ascending else 51 for page in range(0, 5): request = self._mocked_authenticated_request('/unorderedobject/?p=%s' % page, superuser) response = model_admin.changelist_view(request) for result in response.context_data['cl'].result_list: counter += 1 if ascending else -1 self.assertEqual(result.id, counter) custom_site.unregister(UnorderedObject) # When no order is defined at all, everything is ordered by '-pk'. check_results_order() # When an order field is defined but multiple records have the same # value for that field, make sure everything gets ordered by -pk as well. UnorderedObjectAdmin.ordering = ['bool'] check_results_order() # When order fields are defined, including the pk itself, use them. UnorderedObjectAdmin.ordering = ['bool', '-pk'] check_results_order() UnorderedObjectAdmin.ordering = ['bool', 'pk'] check_results_order(ascending=True) UnorderedObjectAdmin.ordering = ['-id', 'bool'] check_results_order() UnorderedObjectAdmin.ordering = ['id', 'bool'] check_results_order(ascending=True) def test_deterministic_order_for_model_ordered_by_its_manager(self): """ The primary key is used in the ordering of the changelist's results to guarantee a deterministic order, even when the model has a manager that defines a default ordering (#17198). """ superuser = self._create_superuser('superuser') for counter in range(1, 51): OrderedObject.objects.create(id=counter, bool=True, number=counter) class OrderedObjectAdmin(admin.ModelAdmin): list_per_page = 10 def check_results_order(ascending=False): custom_site.register(OrderedObject, OrderedObjectAdmin) model_admin = OrderedObjectAdmin(OrderedObject, custom_site) counter = 0 if ascending else 51 for page in range(0, 5): request = self._mocked_authenticated_request('/orderedobject/?p=%s' % page, superuser) response = model_admin.changelist_view(request) for result in response.context_data['cl'].result_list: counter += 1 if ascending else -1 self.assertEqual(result.id, counter) custom_site.unregister(OrderedObject) # When no order is defined at all, use the model's default ordering (i.e. 'number') check_results_order(ascending=True) # When an order field is defined but multiple records have the same # value for that field, make sure everything gets ordered by -pk as well. OrderedObjectAdmin.ordering = ['bool'] check_results_order() # When order fields are defined, including the pk itself, use them. OrderedObjectAdmin.ordering = ['bool', '-pk'] check_results_order() OrderedObjectAdmin.ordering = ['bool', 'pk'] check_results_order(ascending=True) OrderedObjectAdmin.ordering = ['-id', 'bool'] check_results_order() OrderedObjectAdmin.ordering = ['id', 'bool'] check_results_order(ascending=True) @isolate_apps('admin_changelist') def test_total_ordering_optimization(self): class Related(models.Model): unique_field = models.BooleanField(unique=True) class Meta: ordering = ('unique_field',) class Model(models.Model): unique_field = models.BooleanField(unique=True) unique_nullable_field = models.BooleanField(unique=True, null=True) related = models.ForeignKey(Related, models.CASCADE) other_related = models.ForeignKey(Related, models.CASCADE) related_unique = models.OneToOneField(Related, models.CASCADE) field = models.BooleanField() other_field = models.BooleanField() null_field = models.BooleanField(null=True) class Meta: unique_together = { ('field', 'other_field'), ('field', 'null_field'), ('related', 'other_related_id'), } class ModelAdmin(admin.ModelAdmin): def get_queryset(self, request): return Model.objects.none() request = self._mocked_authenticated_request('/', self.superuser) site = admin.AdminSite(name='admin') model_admin = ModelAdmin(Model, site) change_list = model_admin.get_changelist_instance(request) tests = ( ([], ['-pk']), # Unique non-nullable field. (['unique_field'], ['unique_field']), (['-unique_field'], ['-unique_field']), # Unique nullable field. (['unique_nullable_field'], ['unique_nullable_field', '-pk']), # Field. (['field'], ['field', '-pk']), # Related field introspection is not implemented. (['related__unique_field'], ['related__unique_field', '-pk']), # Related attname unique. (['related_unique_id'], ['related_unique_id']), # Related ordering introspection is not implemented. (['related_unique'], ['related_unique', '-pk']), # Composite unique. (['field', '-other_field'], ['field', '-other_field']), # Composite unique nullable. (['-field', 'null_field'], ['-field', 'null_field', '-pk']), # Composite unique nullable. (['-field', 'null_field'], ['-field', 'null_field', '-pk']), # Composite unique nullable. (['-field', 'null_field'], ['-field', 'null_field', '-pk']), # Composite unique and nullable. (['-field', 'null_field', 'other_field'], ['-field', 'null_field', 'other_field']), # Composite unique attnames. (['related_id', '-other_related_id'], ['related_id', '-other_related_id']), # Composite unique names. (['related', '-other_related_id'], ['related', '-other_related_id', '-pk']), ) # F() objects composite unique. total_ordering = [F('field'), F('other_field').desc(nulls_last=True)] # F() objects composite unique nullable. non_total_ordering = [F('field'), F('null_field').desc(nulls_last=True)] tests += ( (total_ordering, total_ordering), (non_total_ordering, non_total_ordering + ['-pk']), ) for ordering, expected in tests: with self.subTest(ordering=ordering): self.assertEqual(change_list._get_deterministic_ordering(ordering), expected) def test_dynamic_list_filter(self): """ Regression tests for ticket #17646: dynamic list_filter support. """ parent = Parent.objects.create(name='parent') for i in range(10): Child.objects.create(name='child %s' % i, parent=parent) user_noparents = self._create_superuser('noparents') user_parents = self._create_superuser('parents') # Test with user 'noparents' m = DynamicListFilterChildAdmin(Child, custom_site) request = self._mocked_authenticated_request('/child/', user_noparents) response = m.changelist_view(request) self.assertEqual(response.context_data['cl'].list_filter, ['name', 'age']) # Test with user 'parents' m = DynamicListFilterChildAdmin(Child, custom_site) request = self._mocked_authenticated_request('/child/', user_parents) response = m.changelist_view(request) self.assertEqual(response.context_data['cl'].list_filter, ('parent', 'name', 'age')) def test_dynamic_search_fields(self): child = self._create_superuser('child') m = DynamicSearchFieldsChildAdmin(Child, custom_site) request = self._mocked_authenticated_request('/child/', child) response = m.changelist_view(request) self.assertEqual(response.context_data['cl'].search_fields, ('name', 'age')) def test_pagination_page_range(self): """ Regression tests for ticket #15653: ensure the number of pages generated for changelist views are correct. """ # instantiating and setting up ChangeList object m = GroupAdmin(Group, custom_site) request = self.factory.get('/group/') request.user = self.superuser cl = m.get_changelist_instance(request) per_page = cl.list_per_page = 10 for page_num, objects_count, expected_page_range in [ (0, per_page, []), (0, per_page * 2, list(range(2))), (5, per_page * 11, list(range(11))), (5, per_page * 12, [0, 1, 2, 3, 4, 5, 6, 7, 8, '.', 10, 11]), (6, per_page * 12, [0, 1, '.', 3, 4, 5, 6, 7, 8, 9, 10, 11]), (6, per_page * 13, [0, 1, '.', 3, 4, 5, 6, 7, 8, 9, '.', 11, 12]), ]: # assuming we have exactly `objects_count` objects Group.objects.all().delete() for i in range(objects_count): Group.objects.create(name='test band') # setting page number and calculating page range cl.page_num = page_num cl.get_results(request) real_page_range = pagination(cl)['page_range'] self.assertEqual(expected_page_range, list(real_page_range)) def test_object_tools_displayed_no_add_permission(self): """ When ModelAdmin.has_add_permission() returns False, the object-tools block is still shown. """ superuser = self._create_superuser('superuser') m = EventAdmin(Event, custom_site) request = self._mocked_authenticated_request('/event/', superuser) self.assertFalse(m.has_add_permission(request)) response = m.changelist_view(request) self.assertIn('<ul class="object-tools">', response.rendered_content) # The "Add" button inside the object-tools shouldn't appear. self.assertNotIn('Add ', response.rendered_content) class GetAdminLogTests(TestCase): def test_custom_user_pk_not_named_id(self): """ {% get_admin_log %} works if the user model's primary key isn't named 'id'. """ context = Context({'user': CustomIdUser()}) template = Template('{% load log %}{% get_admin_log 10 as admin_log for_user user %}') # This template tag just logs. self.assertEqual(template.render(context), '') def test_no_user(self): """{% get_admin_log %} works without specifying a user.""" user = User(username='jondoe', password='secret', email='[email protected]') user.save() ct = ContentType.objects.get_for_model(User) LogEntry.objects.log_action(user.pk, ct.pk, user.pk, repr(user), 1) t = Template( '{% load log %}' '{% get_admin_log 100 as admin_log %}' '{% for entry in admin_log %}' '{{ entry|safe }}' '{% endfor %}' ) self.assertEqual(t.render(Context({})), 'Added “<User: jondoe>”.') def test_missing_args(self): msg = "'get_admin_log' statements require two arguments" with self.assertRaisesMessage(TemplateSyntaxError, msg): Template('{% load log %}{% get_admin_log 10 as %}') def test_non_integer_limit(self): msg = "First argument to 'get_admin_log' must be an integer" with self.assertRaisesMessage(TemplateSyntaxError, msg): Template('{% load log %}{% get_admin_log "10" as admin_log for_user user %}') def test_without_as(self): msg = "Second argument to 'get_admin_log' must be 'as'" with self.assertRaisesMessage(TemplateSyntaxError, msg): Template('{% load log %}{% get_admin_log 10 ad admin_log for_user user %}') def test_without_for_user(self): msg = "Fourth argument to 'get_admin_log' must be 'for_user'" with self.assertRaisesMessage(TemplateSyntaxError, msg): Template('{% load log %}{% get_admin_log 10 as admin_log foruser user %}') @override_settings(ROOT_URLCONF='admin_changelist.urls') class SeleniumTests(AdminSeleniumTestCase): available_apps = ['admin_changelist'] + AdminSeleniumTestCase.available_apps def setUp(self): User.objects.create_superuser(username='super', password='secret', email=None) def test_add_row_selection(self): """ The status line for selected rows gets updated correctly (#22038). """ self.admin_login(username='super', password='secret') self.selenium.get(self.live_server_url + reverse('admin:auth_user_changelist')) form_id = '#changelist-form' # Test amount of rows in the Changelist rows = self.selenium.find_elements_by_css_selector( '%s #result_list tbody tr' % form_id) self.assertEqual(len(rows), 1) # Test current selection selection_indicator = self.selenium.find_element_by_css_selector( '%s .action-counter' % form_id) self.assertEqual(selection_indicator.text, "0 of 1 selected") # Select a row and check again row_selector = self.selenium.find_element_by_css_selector( '%s #result_list tbody tr:first-child .action-select' % form_id) row_selector.click() self.assertEqual(selection_indicator.text, "1 of 1 selected")
e166ae067d9b5d8b5fa4afbc65e989f129ac71f5ff2db013b2df7cb671f39190
from subprocess import CompletedProcess from unittest import mock, skipUnless from django.db import connection from django.db.backends.oracle.client import DatabaseClient from django.test import SimpleTestCase @skipUnless(connection.vendor == 'oracle', 'Oracle tests') class OracleDbshellTests(SimpleTestCase): def _run_dbshell(self, rlwrap=False): """Run runshell command and capture its arguments.""" def _mock_subprocess_run(*args, **kwargs): self.subprocess_args = list(*args) return CompletedProcess(self.subprocess_args, 0) client = DatabaseClient(connection) self.subprocess_args = None with mock.patch('subprocess.run', new=_mock_subprocess_run): with mock.patch('shutil.which', return_value='/usr/bin/rlwrap' if rlwrap else None): client.runshell() return self.subprocess_args def test_without_rlwrap(self): self.assertEqual( self._run_dbshell(rlwrap=False), ['sqlplus', '-L', connection._connect_string()], ) def test_with_rlwrap(self): self.assertEqual( self._run_dbshell(rlwrap=True), ['/usr/bin/rlwrap', 'sqlplus', '-L', connection._connect_string()], )
2bf0c0617e2a8a74350c1e924d5d090940d4eee4a0f27bed3f9a5113a0bffe2b
import os import signal import subprocess from unittest import mock from django.db.backends.postgresql.client import DatabaseClient from django.test import SimpleTestCase class PostgreSqlDbshellCommandTestCase(SimpleTestCase): def _run_it(self, dbinfo): """ That function invokes the runshell command, while mocking subprocess.run(). It returns a 2-tuple with: - The command line list - The dictionary of PG* environment variables, or {}. """ def _mock_subprocess_run(*args, env=os.environ, **kwargs): self.subprocess_args = list(*args) # PostgreSQL environment variables. self.pg_env = {key: env[key] for key in env if key.startswith('PG')} return subprocess.CompletedProcess(self.subprocess_args, 0) with mock.patch('subprocess.run', new=_mock_subprocess_run): DatabaseClient.runshell_db(dbinfo) return self.subprocess_args, self.pg_env def test_basic(self): self.assertEqual( self._run_it({ 'database': 'dbname', 'user': 'someuser', 'password': 'somepassword', 'host': 'somehost', 'port': '444', }), ( ['psql', '-U', 'someuser', '-h', 'somehost', '-p', '444', 'dbname'], {'PGPASSWORD': 'somepassword'}, ) ) def test_nopass(self): self.assertEqual( self._run_it({ 'database': 'dbname', 'user': 'someuser', 'host': 'somehost', 'port': '444', }), ( ['psql', '-U', 'someuser', '-h', 'somehost', '-p', '444', 'dbname'], {}, ) ) def test_ssl_certificate(self): self.assertEqual( self._run_it({ 'database': 'dbname', 'user': 'someuser', 'host': 'somehost', 'port': '444', 'sslmode': 'verify-ca', 'sslrootcert': 'root.crt', 'sslcert': 'client.crt', 'sslkey': 'client.key', }), ( ['psql', '-U', 'someuser', '-h', 'somehost', '-p', '444', 'dbname'], { 'PGSSLCERT': 'client.crt', 'PGSSLKEY': 'client.key', 'PGSSLMODE': 'verify-ca', 'PGSSLROOTCERT': 'root.crt', }, ) ) def test_column(self): self.assertEqual( self._run_it({ 'database': 'dbname', 'user': 'some:user', 'password': 'some:password', 'host': '::1', 'port': '444', }), ( ['psql', '-U', 'some:user', '-h', '::1', '-p', '444', 'dbname'], {'PGPASSWORD': 'some:password'}, ) ) def test_accent(self): username = 'rôle' password = 'sésame' self.assertEqual( self._run_it({ 'database': 'dbname', 'user': username, 'password': password, 'host': 'somehost', 'port': '444', }), ( ['psql', '-U', username, '-h', 'somehost', '-p', '444', 'dbname'], {'PGPASSWORD': password}, ) ) def test_sigint_handler(self): """SIGINT is ignored in Python and passed to psql to abort queries.""" def _mock_subprocess_run(*args, **kwargs): handler = signal.getsignal(signal.SIGINT) self.assertEqual(handler, signal.SIG_IGN) sigint_handler = signal.getsignal(signal.SIGINT) # The default handler isn't SIG_IGN. self.assertNotEqual(sigint_handler, signal.SIG_IGN) with mock.patch('subprocess.run', new=_mock_subprocess_run): DatabaseClient.runshell_db({}) # dbshell restores the original handler. self.assertEqual(sigint_handler, signal.getsignal(signal.SIGINT))
81eca42cadbb905c37691583d84b92b777bfc20cb1c396417976e3709066f084
from unittest import mock from django.db import connection, transaction from django.db.models import Case, Count, F, FilteredRelation, Q, When from django.test import TestCase from django.test.testcases import skipUnlessDBFeature from .models import Author, Book, Borrower, Editor, RentalSession, Reservation class FilteredRelationTests(TestCase): @classmethod def setUpTestData(cls): cls.author1 = Author.objects.create(name='Alice') cls.author2 = Author.objects.create(name='Jane') cls.editor_a = Editor.objects.create(name='a') cls.editor_b = Editor.objects.create(name='b') cls.book1 = Book.objects.create( title='Poem by Alice', editor=cls.editor_a, author=cls.author1, ) cls.book1.generic_author.set([cls.author2]) cls.book2 = Book.objects.create( title='The book by Jane A', editor=cls.editor_b, author=cls.author2, ) cls.book3 = Book.objects.create( title='The book by Jane B', editor=cls.editor_b, author=cls.author2, ) cls.book4 = Book.objects.create( title='The book by Alice', editor=cls.editor_a, author=cls.author1, ) cls.author1.favorite_books.add(cls.book2) cls.author1.favorite_books.add(cls.book3) def test_select_related(self): qs = Author.objects.annotate( book_join=FilteredRelation('book'), ).select_related('book_join__editor').order_by('pk', 'book_join__pk') with self.assertNumQueries(1): self.assertQuerysetEqual(qs, [ (self.author1, self.book1, self.editor_a, self.author1), (self.author1, self.book4, self.editor_a, self.author1), (self.author2, self.book2, self.editor_b, self.author2), (self.author2, self.book3, self.editor_b, self.author2), ], lambda x: (x, x.book_join, x.book_join.editor, x.book_join.author)) def test_select_related_with_empty_relation(self): qs = Author.objects.annotate( book_join=FilteredRelation('book', condition=Q(pk=-1)), ).select_related('book_join').order_by('pk') self.assertSequenceEqual(qs, [self.author1, self.author2]) def test_select_related_foreign_key(self): qs = Book.objects.annotate( author_join=FilteredRelation('author'), ).select_related('author_join').order_by('pk') with self.assertNumQueries(1): self.assertQuerysetEqual(qs, [ (self.book1, self.author1), (self.book2, self.author2), (self.book3, self.author2), (self.book4, self.author1), ], lambda x: (x, x.author_join)) @skipUnlessDBFeature('has_select_for_update', 'has_select_for_update_of') def test_select_related_foreign_key_for_update_of(self): with transaction.atomic(): qs = Book.objects.annotate( author_join=FilteredRelation('author'), ).select_related('author_join').select_for_update(of=('self',)).order_by('pk') with self.assertNumQueries(1): self.assertQuerysetEqual(qs, [ (self.book1, self.author1), (self.book2, self.author2), (self.book3, self.author2), (self.book4, self.author1), ], lambda x: (x, x.author_join)) def test_without_join(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')), ), [self.author1, self.author2] ) def test_with_join(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')), ).filter(book_alice__isnull=False), [self.author1] ) def test_with_exclude(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')), ).exclude(book_alice__isnull=False), [self.author2], ) def test_with_join_and_complex_condition(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation( 'book', condition=Q( Q(book__title__iexact='poem by alice') | Q(book__state=Book.RENTED) ), ), ).filter(book_alice__isnull=False), [self.author1] ) def test_internal_queryset_alias_mapping(self): queryset = Author.objects.annotate( book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')), ).filter(book_alice__isnull=False) self.assertIn( 'INNER JOIN {} book_alice ON'.format(connection.ops.quote_name('filtered_relation_book')), str(queryset.query) ) def test_with_multiple_filter(self): self.assertSequenceEqual( Author.objects.annotate( book_editor_a=FilteredRelation( 'book', condition=Q(book__title__icontains='book', book__editor_id=self.editor_a.pk), ), ).filter(book_editor_a__isnull=False), [self.author1] ) def test_multiple_times(self): self.assertSequenceEqual( Author.objects.annotate( book_title_alice=FilteredRelation('book', condition=Q(book__title__icontains='alice')), ).filter(book_title_alice__isnull=False).filter(book_title_alice__isnull=False).distinct(), [self.author1] ) def test_exclude_relation_with_join(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation('book', condition=~Q(book__title__icontains='alice')), ).filter(book_alice__isnull=False).distinct(), [self.author2] ) def test_with_m2m(self): qs = Author.objects.annotate( favorite_books_written_by_jane=FilteredRelation( 'favorite_books', condition=Q(favorite_books__in=[self.book2]), ), ).filter(favorite_books_written_by_jane__isnull=False) self.assertSequenceEqual(qs, [self.author1]) def test_with_m2m_deep(self): qs = Author.objects.annotate( favorite_books_written_by_jane=FilteredRelation( 'favorite_books', condition=Q(favorite_books__author=self.author2), ), ).filter(favorite_books_written_by_jane__title='The book by Jane B') self.assertSequenceEqual(qs, [self.author1]) def test_with_m2m_multijoin(self): qs = Author.objects.annotate( favorite_books_written_by_jane=FilteredRelation( 'favorite_books', condition=Q(favorite_books__author=self.author2), ) ).filter(favorite_books_written_by_jane__editor__name='b').distinct() self.assertSequenceEqual(qs, [self.author1]) def test_values_list(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')), ).filter(book_alice__isnull=False).values_list('book_alice__title', flat=True), ['Poem by Alice'] ) def test_values(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')), ).filter(book_alice__isnull=False).values(), [{'id': self.author1.pk, 'name': 'Alice', 'content_type_id': None, 'object_id': None}] ) def test_extra(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')), ).filter(book_alice__isnull=False).extra(where=['1 = 1']), [self.author1] ) @skipUnlessDBFeature('supports_select_union') def test_union(self): qs1 = Author.objects.annotate( book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')), ).filter(book_alice__isnull=False) qs2 = Author.objects.annotate( book_jane=FilteredRelation('book', condition=Q(book__title__iexact='the book by jane a')), ).filter(book_jane__isnull=False) self.assertSequenceEqual(qs1.union(qs2), [self.author1, self.author2]) @skipUnlessDBFeature('supports_select_intersection') def test_intersection(self): qs1 = Author.objects.annotate( book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')), ).filter(book_alice__isnull=False) qs2 = Author.objects.annotate( book_jane=FilteredRelation('book', condition=Q(book__title__iexact='the book by jane a')), ).filter(book_jane__isnull=False) self.assertSequenceEqual(qs1.intersection(qs2), []) @skipUnlessDBFeature('supports_select_difference') def test_difference(self): qs1 = Author.objects.annotate( book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')), ).filter(book_alice__isnull=False) qs2 = Author.objects.annotate( book_jane=FilteredRelation('book', condition=Q(book__title__iexact='the book by jane a')), ).filter(book_jane__isnull=False) self.assertSequenceEqual(qs1.difference(qs2), [self.author1]) def test_select_for_update(self): self.assertSequenceEqual( Author.objects.annotate( book_jane=FilteredRelation('book', condition=Q(book__title__iexact='the book by jane a')), ).filter(book_jane__isnull=False).select_for_update(), [self.author2] ) def test_defer(self): # One query for the list and one query for the deferred title. with self.assertNumQueries(2): self.assertQuerysetEqual( Author.objects.annotate( book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')), ).filter(book_alice__isnull=False).select_related('book_alice').defer('book_alice__title'), ['Poem by Alice'], lambda author: author.book_alice.title ) def test_only_not_supported(self): msg = 'only() is not supported with FilteredRelation.' with self.assertRaisesMessage(ValueError, msg): Author.objects.annotate( book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')), ).filter(book_alice__isnull=False).select_related('book_alice').only('book_alice__state') def test_as_subquery(self): inner_qs = Author.objects.annotate( book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')), ).filter(book_alice__isnull=False) qs = Author.objects.filter(id__in=inner_qs) self.assertSequenceEqual(qs, [self.author1]) def test_with_foreign_key_error(self): msg = ( "FilteredRelation's condition doesn't support nested relations " "(got 'author__favorite_books__author')." ) with self.assertRaisesMessage(ValueError, msg): list(Book.objects.annotate( alice_favorite_books=FilteredRelation( 'author__favorite_books', condition=Q(author__favorite_books__author=self.author1), ) )) def test_with_foreign_key_on_condition_error(self): msg = ( "FilteredRelation's condition doesn't support nested relations " "(got 'book__editor__name__icontains')." ) with self.assertRaisesMessage(ValueError, msg): list(Author.objects.annotate( book_edited_by_b=FilteredRelation('book', condition=Q(book__editor__name__icontains='b')), )) def test_with_empty_relation_name_error(self): with self.assertRaisesMessage(ValueError, 'relation_name cannot be empty.'): FilteredRelation('', condition=Q(blank='')) def test_with_condition_as_expression_error(self): msg = 'condition argument must be a Q() instance.' expression = Case( When(book__title__iexact='poem by alice', then=True), default=False, ) with self.assertRaisesMessage(ValueError, msg): FilteredRelation('book', condition=expression) def test_with_prefetch_related(self): msg = 'prefetch_related() is not supported with FilteredRelation.' qs = Author.objects.annotate( book_title_contains_b=FilteredRelation('book', condition=Q(book__title__icontains='b')), ).filter( book_title_contains_b__isnull=False, ) with self.assertRaisesMessage(ValueError, msg): qs.prefetch_related('book_title_contains_b') with self.assertRaisesMessage(ValueError, msg): qs.prefetch_related('book_title_contains_b__editor') def test_with_generic_foreign_key(self): self.assertSequenceEqual( Book.objects.annotate( generic_authored_book=FilteredRelation( 'generic_author', condition=Q(generic_author__isnull=False) ), ).filter(generic_authored_book__isnull=False), [self.book1] ) def test_eq(self): self.assertEqual(FilteredRelation('book', condition=Q(book__title='b')), mock.ANY) class FilteredRelationAggregationTests(TestCase): @classmethod def setUpTestData(cls): cls.author1 = Author.objects.create(name='Alice') cls.editor_a = Editor.objects.create(name='a') cls.book1 = Book.objects.create( title='Poem by Alice', editor=cls.editor_a, author=cls.author1, ) cls.borrower1 = Borrower.objects.create(name='Jenny') cls.borrower2 = Borrower.objects.create(name='Kevin') # borrower 1 reserves, rents, and returns book1. Reservation.objects.create( borrower=cls.borrower1, book=cls.book1, state=Reservation.STOPPED, ) RentalSession.objects.create( borrower=cls.borrower1, book=cls.book1, state=RentalSession.STOPPED, ) # borrower2 reserves, rents, and returns book1. Reservation.objects.create( borrower=cls.borrower2, book=cls.book1, state=Reservation.STOPPED, ) RentalSession.objects.create( borrower=cls.borrower2, book=cls.book1, state=RentalSession.STOPPED, ) def test_aggregate(self): """ filtered_relation() not only improves performance but also creates correct results when aggregating with multiple LEFT JOINs. Books can be reserved then rented by a borrower. Each reservation and rental session are recorded with Reservation and RentalSession models. Every time a reservation or a rental session is over, their state is changed to 'stopped'. Goal: Count number of books that are either currently reserved or rented by borrower1 or available. """ qs = Book.objects.annotate( is_reserved_or_rented_by=Case( When(reservation__state=Reservation.NEW, then=F('reservation__borrower__pk')), When(rental_session__state=RentalSession.NEW, then=F('rental_session__borrower__pk')), default=None, ) ).filter( Q(is_reserved_or_rented_by=self.borrower1.pk) | Q(state=Book.AVAILABLE) ).distinct() self.assertEqual(qs.count(), 1) # If count is equal to 1, the same aggregation should return in the # same result but it returns 4. self.assertSequenceEqual(qs.annotate(total=Count('pk')).values('total'), [{'total': 4}]) # With FilteredRelation, the result is as expected (1). qs = Book.objects.annotate( active_reservations=FilteredRelation( 'reservation', condition=Q( reservation__state=Reservation.NEW, reservation__borrower=self.borrower1, ) ), ).annotate( active_rental_sessions=FilteredRelation( 'rental_session', condition=Q( rental_session__state=RentalSession.NEW, rental_session__borrower=self.borrower1, ) ), ).filter( (Q(active_reservations__isnull=False) | Q(active_rental_sessions__isnull=False)) | Q(state=Book.AVAILABLE) ).distinct() self.assertEqual(qs.count(), 1) self.assertSequenceEqual(qs.annotate(total=Count('pk')).values('total'), [{'total': 1}])
43829fd823fd8c0daecf135a518a52dd310f784bd2ee944aa7de7710384e29f0
import gettext import os import re from datetime import datetime, timedelta from importlib import import_module import pytz from django import forms from django.conf import settings from django.contrib import admin from django.contrib.admin import widgets from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.auth.models import User from django.core.files.storage import default_storage from django.core.files.uploadedfile import SimpleUploadedFile from django.db.models import CharField, DateField, DateTimeField, UUIDField from django.test import SimpleTestCase, TestCase, override_settings from django.urls import reverse from django.utils import translation from .models import ( Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Individual, Inventory, Member, MyFileField, Profile, School, Student, ) from .widgetadmin import site as widget_admin_site class TestDataMixin: @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser(username='super', password='secret', email=None) cls.u2 = User.objects.create_user(username='testser', password='secret') Car.objects.create(owner=cls.superuser, make='Volkswagen', model='Passat') Car.objects.create(owner=cls.u2, make='BMW', model='M3') class AdminFormfieldForDBFieldTests(SimpleTestCase): """ Tests for correct behavior of ModelAdmin.formfield_for_dbfield """ def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides): """ Helper to call formfield_for_dbfield for a given model and field name and verify that the returned formfield is appropriate. """ # Override any settings on the model admin class MyModelAdmin(admin.ModelAdmin): pass for k in admin_overrides: setattr(MyModelAdmin, k, admin_overrides[k]) # Construct the admin, and ask it for a formfield ma = MyModelAdmin(model, admin.site) ff = ma.formfield_for_dbfield(model._meta.get_field(fieldname), request=None) # "unwrap" the widget wrapper, if needed if isinstance(ff.widget, widgets.RelatedFieldWidgetWrapper): widget = ff.widget.widget else: widget = ff.widget self.assertIsInstance(widget, widgetclass) # Return the formfield so that other tests can continue return ff def test_DateField(self): self.assertFormfield(Event, 'start_date', widgets.AdminDateWidget) def test_DateTimeField(self): self.assertFormfield(Member, 'birthdate', widgets.AdminSplitDateTime) def test_TimeField(self): self.assertFormfield(Event, 'start_time', widgets.AdminTimeWidget) def test_TextField(self): self.assertFormfield(Event, 'description', widgets.AdminTextareaWidget) def test_URLField(self): self.assertFormfield(Event, 'link', widgets.AdminURLFieldWidget) def test_IntegerField(self): self.assertFormfield(Event, 'min_age', widgets.AdminIntegerFieldWidget) def test_CharField(self): self.assertFormfield(Member, 'name', widgets.AdminTextInputWidget) def test_EmailField(self): self.assertFormfield(Member, 'email', widgets.AdminEmailInputWidget) def test_FileField(self): self.assertFormfield(Album, 'cover_art', widgets.AdminFileWidget) def test_ForeignKey(self): self.assertFormfield(Event, 'main_band', forms.Select) def test_raw_id_ForeignKey(self): self.assertFormfield(Event, 'main_band', widgets.ForeignKeyRawIdWidget, raw_id_fields=['main_band']) def test_radio_fields_ForeignKey(self): ff = self.assertFormfield(Event, 'main_band', widgets.AdminRadioSelect, radio_fields={'main_band': admin.VERTICAL}) self.assertIsNone(ff.empty_label) def test_many_to_many(self): self.assertFormfield(Band, 'members', forms.SelectMultiple) def test_raw_id_many_to_many(self): self.assertFormfield(Band, 'members', widgets.ManyToManyRawIdWidget, raw_id_fields=['members']) def test_filtered_many_to_many(self): self.assertFormfield(Band, 'members', widgets.FilteredSelectMultiple, filter_vertical=['members']) def test_formfield_overrides(self): self.assertFormfield(Event, 'start_date', forms.TextInput, formfield_overrides={DateField: {'widget': forms.TextInput}}) def test_formfield_overrides_widget_instances(self): """ Widget instances in formfield_overrides are not shared between different fields. (#19423) """ class BandAdmin(admin.ModelAdmin): formfield_overrides = { CharField: {'widget': forms.TextInput(attrs={'size': '10'})} } ma = BandAdmin(Band, admin.site) f1 = ma.formfield_for_dbfield(Band._meta.get_field('name'), request=None) f2 = ma.formfield_for_dbfield(Band._meta.get_field('style'), request=None) self.assertNotEqual(f1.widget, f2.widget) self.assertEqual(f1.widget.attrs['maxlength'], '100') self.assertEqual(f2.widget.attrs['maxlength'], '20') self.assertEqual(f2.widget.attrs['size'], '10') def test_formfield_overrides_for_datetime_field(self): """ Overriding the widget for DateTimeField doesn't overrides the default form_class for that field (#26449). """ class MemberAdmin(admin.ModelAdmin): formfield_overrides = {DateTimeField: {'widget': widgets.AdminSplitDateTime}} ma = MemberAdmin(Member, admin.site) f1 = ma.formfield_for_dbfield(Member._meta.get_field('birthdate'), request=None) self.assertIsInstance(f1.widget, widgets.AdminSplitDateTime) self.assertIsInstance(f1, forms.SplitDateTimeField) def test_formfield_overrides_for_custom_field(self): """ formfield_overrides works for a custom field class. """ class AlbumAdmin(admin.ModelAdmin): formfield_overrides = {MyFileField: {'widget': forms.TextInput()}} ma = AlbumAdmin(Member, admin.site) f1 = ma.formfield_for_dbfield(Album._meta.get_field('backside_art'), request=None) self.assertIsInstance(f1.widget, forms.TextInput) def test_field_with_choices(self): self.assertFormfield(Member, 'gender', forms.Select) def test_choices_with_radio_fields(self): self.assertFormfield(Member, 'gender', widgets.AdminRadioSelect, radio_fields={'gender': admin.VERTICAL}) def test_inheritance(self): self.assertFormfield(Album, 'backside_art', widgets.AdminFileWidget) def test_m2m_widgets(self): """m2m fields help text as it applies to admin app (#9321).""" class AdvisorAdmin(admin.ModelAdmin): filter_vertical = ['companies'] self.assertFormfield(Advisor, 'companies', widgets.FilteredSelectMultiple, filter_vertical=['companies']) ma = AdvisorAdmin(Advisor, admin.site) f = ma.formfield_for_dbfield(Advisor._meta.get_field('companies'), request=None) self.assertEqual( f.help_text, 'Hold down “Control”, or “Command” on a Mac, to select more than one.' ) @override_settings(ROOT_URLCONF='admin_widgets.urls') class AdminFormfieldForDBFieldWithRequestTests(TestDataMixin, TestCase): def test_filter_choices_by_request_user(self): """ Ensure the user can only see their own cars in the foreign key dropdown. """ self.client.force_login(self.superuser) response = self.client.get(reverse('admin:admin_widgets_cartire_add')) self.assertNotContains(response, "BMW M3") self.assertContains(response, "Volkswagen Passat") @override_settings(ROOT_URLCONF='admin_widgets.urls') class AdminForeignKeyWidgetChangeList(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_changelist_ForeignKey(self): response = self.client.get(reverse('admin:admin_widgets_car_changelist')) self.assertContains(response, '/auth/user/add/') @override_settings(ROOT_URLCONF='admin_widgets.urls') class AdminForeignKeyRawIdWidget(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_nonexistent_target_id(self): band = Band.objects.create(name='Bogey Blues') pk = band.pk band.delete() post_data = { "main_band": '%s' % pk, } # Try posting with a nonexistent pk in a raw id field: this # should result in an error message, not a server exception. response = self.client.post(reverse('admin:admin_widgets_event_add'), post_data) self.assertContains(response, 'Select a valid choice. That choice is not one of the available choices.') def test_invalid_target_id(self): for test_str in ('Iñtërnâtiônàlizætiøn', "1234'", -1234): # This should result in an error message, not a server exception. response = self.client.post(reverse('admin:admin_widgets_event_add'), {"main_band": test_str}) self.assertContains(response, 'Select a valid choice. That choice is not one of the available choices.') def test_url_params_from_lookup_dict_any_iterable(self): lookup1 = widgets.url_params_from_lookup_dict({'color__in': ('red', 'blue')}) lookup2 = widgets.url_params_from_lookup_dict({'color__in': ['red', 'blue']}) self.assertEqual(lookup1, {'color__in': 'red,blue'}) self.assertEqual(lookup1, lookup2) def test_url_params_from_lookup_dict_callable(self): def my_callable(): return 'works' lookup1 = widgets.url_params_from_lookup_dict({'myfield': my_callable}) lookup2 = widgets.url_params_from_lookup_dict({'myfield': my_callable()}) self.assertEqual(lookup1, lookup2) def test_label_and_url_for_value_invalid_uuid(self): field = Bee._meta.get_field('honeycomb') self.assertIsInstance(field.target_field, UUIDField) widget = widgets.ForeignKeyRawIdWidget(field.remote_field, admin.site) self.assertEqual(widget.label_and_url_for_value('invalid-uuid'), ('', '')) class FilteredSelectMultipleWidgetTest(SimpleTestCase): def test_render(self): # Backslash in verbose_name to ensure it is JavaScript escaped. w = widgets.FilteredSelectMultiple('test\\', False) self.assertHTMLEqual( w.render('test', 'test'), '<select multiple name="test" class="selectfilter" ' 'data-field-name="test\\" data-is-stacked="0">\n</select>' ) def test_stacked_render(self): # Backslash in verbose_name to ensure it is JavaScript escaped. w = widgets.FilteredSelectMultiple('test\\', True) self.assertHTMLEqual( w.render('test', 'test'), '<select multiple name="test" class="selectfilterstacked" ' 'data-field-name="test\\" data-is-stacked="1">\n</select>' ) class AdminDateWidgetTest(SimpleTestCase): def test_attrs(self): w = widgets.AdminDateWidget() self.assertHTMLEqual( w.render('test', datetime(2007, 12, 1, 9, 30)), '<input value="2007-12-01" type="text" class="vDateField" name="test" size="10">', ) # pass attrs to widget w = widgets.AdminDateWidget(attrs={'size': 20, 'class': 'myDateField'}) self.assertHTMLEqual( w.render('test', datetime(2007, 12, 1, 9, 30)), '<input value="2007-12-01" type="text" class="myDateField" name="test" size="20">', ) class AdminTimeWidgetTest(SimpleTestCase): def test_attrs(self): w = widgets.AdminTimeWidget() self.assertHTMLEqual( w.render('test', datetime(2007, 12, 1, 9, 30)), '<input value="09:30:00" type="text" class="vTimeField" name="test" size="8">', ) # pass attrs to widget w = widgets.AdminTimeWidget(attrs={'size': 20, 'class': 'myTimeField'}) self.assertHTMLEqual( w.render('test', datetime(2007, 12, 1, 9, 30)), '<input value="09:30:00" type="text" class="myTimeField" name="test" size="20">', ) class AdminSplitDateTimeWidgetTest(SimpleTestCase): def test_render(self): w = widgets.AdminSplitDateTime() self.assertHTMLEqual( w.render('test', datetime(2007, 12, 1, 9, 30)), '<p class="datetime">' 'Date: <input value="2007-12-01" type="text" class="vDateField" ' 'name="test_0" size="10"><br>' 'Time: <input value="09:30:00" type="text" class="vTimeField" ' 'name="test_1" size="8"></p>' ) def test_localization(self): w = widgets.AdminSplitDateTime() with self.settings(USE_L10N=True), translation.override('de-at'): w.is_localized = True self.assertHTMLEqual( w.render('test', datetime(2007, 12, 1, 9, 30)), '<p class="datetime">' 'Datum: <input value="01.12.2007" type="text" ' 'class="vDateField" name="test_0"size="10"><br>' 'Zeit: <input value="09:30:00" type="text" class="vTimeField" ' 'name="test_1" size="8"></p>' ) class AdminURLWidgetTest(SimpleTestCase): def test_get_context_validates_url(self): w = widgets.AdminURLFieldWidget() for invalid in ['', '/not/a/full/url/', 'javascript:alert("Danger XSS!")']: with self.subTest(url=invalid): self.assertFalse(w.get_context('name', invalid, {})['url_valid']) self.assertTrue(w.get_context('name', 'http://example.com', {})['url_valid']) def test_render(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( w.render('test', ''), '<input class="vURLField" name="test" type="url">' ) self.assertHTMLEqual( w.render('test', 'http://example.com'), '<p class="url">Currently:<a href="http://example.com">' 'http://example.com</a><br>' 'Change:<input class="vURLField" name="test" type="url" ' 'value="http://example.com"></p>' ) def test_render_idn(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( w.render('test', 'http://example-äüö.com'), '<p class="url">Currently: <a href="http://xn--example--7za4pnc.com">' 'http://example-äüö.com</a><br>' 'Change:<input class="vURLField" name="test" type="url" ' 'value="http://example-äüö.com"></p>' ) def test_render_quoting(self): """ WARNING: This test doesn't use assertHTMLEqual since it will get rid of some escapes which are tested here! """ HREF_RE = re.compile('href="([^"]+)"') VALUE_RE = re.compile('value="([^"]+)"') TEXT_RE = re.compile('<a[^>]+>([^>]+)</a>') w = widgets.AdminURLFieldWidget() output = w.render('test', 'http://example.com/<sometag>some-text</sometag>') self.assertEqual( HREF_RE.search(output).groups()[0], 'http://example.com/%3Csometag%3Esome-text%3C/sometag%3E', ) self.assertEqual( TEXT_RE.search(output).groups()[0], 'http://example.com/&lt;sometag&gt;some-text&lt;/sometag&gt;', ) self.assertEqual( VALUE_RE.search(output).groups()[0], 'http://example.com/&lt;sometag&gt;some-text&lt;/sometag&gt;', ) output = w.render('test', 'http://example-äüö.com/<sometag>some-text</sometag>') self.assertEqual( HREF_RE.search(output).groups()[0], 'http://xn--example--7za4pnc.com/%3Csometag%3Esome-text%3C/sometag%3E', ) self.assertEqual( TEXT_RE.search(output).groups()[0], 'http://example-äüö.com/&lt;sometag&gt;some-text&lt;/sometag&gt;', ) self.assertEqual( VALUE_RE.search(output).groups()[0], 'http://example-äüö.com/&lt;sometag&gt;some-text&lt;/sometag&gt;', ) output = w.render('test', 'http://www.example.com/%C3%A4"><script>alert("XSS!")</script>"') self.assertEqual( HREF_RE.search(output).groups()[0], 'http://www.example.com/%C3%A4%22%3E%3Cscript%3Ealert(%22XSS!%22)%3C/script%3E%22', ) self.assertEqual( TEXT_RE.search(output).groups()[0], 'http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;' 'alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;' ) self.assertEqual( VALUE_RE.search(output).groups()[0], 'http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;', ) class AdminUUIDWidgetTests(SimpleTestCase): def test_attrs(self): w = widgets.AdminUUIDInputWidget() self.assertHTMLEqual( w.render('test', '550e8400-e29b-41d4-a716-446655440000'), '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" class="vUUIDField" name="test">', ) w = widgets.AdminUUIDInputWidget(attrs={'class': 'myUUIDInput'}) self.assertHTMLEqual( w.render('test', '550e8400-e29b-41d4-a716-446655440000'), '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" class="myUUIDInput" name="test">', ) @override_settings(ROOT_URLCONF='admin_widgets.urls') class AdminFileWidgetTests(TestDataMixin, TestCase): @classmethod def setUpTestData(cls): super().setUpTestData() band = Band.objects.create(name='Linkin Park') cls.album = band.album_set.create( name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg' ) def test_render(self): w = widgets.AdminFileWidget() self.assertHTMLEqual( w.render('test', self.album.cover_art), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a> ' '<span class="clearable-file-input">' '<input type="checkbox" name="test-clear" id="test-clear_id"> ' '<label for="test-clear_id">Clear</label></span><br>' 'Change: <input type="file" name="test"></p>' % { 'STORAGE_URL': default_storage.url(''), }, ) self.assertHTMLEqual( w.render('test', SimpleUploadedFile('test', b'content')), '<input type="file" name="test">', ) def test_render_required(self): widget = widgets.AdminFileWidget() widget.is_required = True self.assertHTMLEqual( widget.render('test', self.album.cover_art), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a><br>' 'Change: <input type="file" name="test"></p>' % { 'STORAGE_URL': default_storage.url(''), }, ) def test_readonly_fields(self): """ File widgets should render as a link when they're marked "read only." """ self.client.force_login(self.superuser) response = self.client.get(reverse('admin:admin_widgets_album_change', args=(self.album.id,))) self.assertContains( response, '<div class="readonly"><a href="%(STORAGE_URL)salbums/hybrid_theory.jpg">' r'albums\hybrid_theory.jpg</a></div>' % {'STORAGE_URL': default_storage.url('')}, html=True, ) self.assertNotContains( response, '<input type="file" name="cover_art" id="id_cover_art">', html=True, ) response = self.client.get(reverse('admin:admin_widgets_album_add')) self.assertContains( response, '<div class="readonly"></div>', html=True, ) @override_settings(ROOT_URLCONF='admin_widgets.urls') class ForeignKeyRawIdWidgetTest(TestCase): def test_render(self): band = Band.objects.create(name='Linkin Park') band.album_set.create( name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg' ) rel = Album._meta.get_field('band').remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render('test', band.pk, attrs={}), '<input type="text" name="test" value="%(bandpk)s" ' 'class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/band/?_to_field=id" class="related-lookup" ' 'id="lookup_id_test" title="Lookup"></a>&nbsp;<strong>' '<a href="/admin_widgets/band/%(bandpk)s/change/">Linkin Park</a>' '</strong>' % {'bandpk': band.pk} ) def test_relations_to_non_primary_key(self): # ForeignKeyRawIdWidget works with fields which aren't related to # the model's primary key. apple = Inventory.objects.create(barcode=86, name='Apple') Inventory.objects.create(barcode=22, name='Pear') core = Inventory.objects.create( barcode=87, name='Core', parent=apple ) rel = Inventory._meta.get_field('parent').remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render('test', core.parent_id, attrs={}), '<input type="text" name="test" value="86" ' 'class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/inventory/?_to_field=barcode" ' 'class="related-lookup" id="lookup_id_test" title="Lookup"></a>' '&nbsp;<strong><a href="/admin_widgets/inventory/%(pk)s/change/">' 'Apple</a></strong>' % {'pk': apple.pk} ) def test_fk_related_model_not_in_admin(self): # FK to a model not registered with admin site. Raw ID widget should # have no magnifying glass link. See #16542 big_honeycomb = Honeycomb.objects.create(location='Old tree') big_honeycomb.bee_set.create() rel = Bee._meta.get_field('honeycomb').remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render('honeycomb_widget', big_honeycomb.pk, attrs={}), '<input type="text" name="honeycomb_widget" value="%(hcombpk)s">' '&nbsp;<strong>%(hcomb)s</strong>' % {'hcombpk': big_honeycomb.pk, 'hcomb': big_honeycomb} ) def test_fk_to_self_model_not_in_admin(self): # FK to self, not registered with admin site. Raw ID widget should have # no magnifying glass link. See #16542 subject1 = Individual.objects.create(name='Subject #1') Individual.objects.create(name='Child', parent=subject1) rel = Individual._meta.get_field('parent').remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render('individual_widget', subject1.pk, attrs={}), '<input type="text" name="individual_widget" value="%(subj1pk)s">' '&nbsp;<strong>%(subj1)s</strong>' % {'subj1pk': subject1.pk, 'subj1': subject1} ) def test_proper_manager_for_label_lookup(self): # see #9258 rel = Inventory._meta.get_field('parent').remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) hidden = Inventory.objects.create( barcode=93, name='Hidden', hidden=True ) child_of_hidden = Inventory.objects.create( barcode=94, name='Child of hidden', parent=hidden ) self.assertHTMLEqual( w.render('test', child_of_hidden.parent_id, attrs={}), '<input type="text" name="test" value="93" class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/inventory/?_to_field=barcode" ' 'class="related-lookup" id="lookup_id_test" title="Lookup"></a>' '&nbsp;<strong><a href="/admin_widgets/inventory/%(pk)s/change/">' 'Hidden</a></strong>' % {'pk': hidden.pk} ) @override_settings(ROOT_URLCONF='admin_widgets.urls') class ManyToManyRawIdWidgetTest(TestCase): def test_render(self): band = Band.objects.create(name='Linkin Park') m1 = Member.objects.create(name='Chester') m2 = Member.objects.create(name='Mike') band.members.add(m1, m2) rel = Band._meta.get_field('members').remote_field w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render('test', [m1.pk, m2.pk], attrs={}), ( '<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField">' '<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>' ) % {'m1pk': m1.pk, 'm2pk': m2.pk} ) self.assertHTMLEqual( w.render('test', [m1.pk]), ( '<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField">' '<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>' ) % {'m1pk': m1.pk} ) def test_m2m_related_model_not_in_admin(self): # M2M relationship with model not registered with admin site. Raw ID # widget should have no magnifying glass link. See #16542 consultor1 = Advisor.objects.create(name='Rockstar Techie') c1 = Company.objects.create(name='Doodle') c2 = Company.objects.create(name='Pear') consultor1.companies.add(c1, c2) rel = Advisor._meta.get_field('companies').remote_field w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render('company_widget1', [c1.pk, c2.pk], attrs={}), '<input type="text" name="company_widget1" value="%(c1pk)s,%(c2pk)s">' % {'c1pk': c1.pk, 'c2pk': c2.pk} ) self.assertHTMLEqual( w.render('company_widget2', [c1.pk]), '<input type="text" name="company_widget2" value="%(c1pk)s">' % {'c1pk': c1.pk} ) @override_settings(ROOT_URLCONF='admin_widgets.urls') class RelatedFieldWidgetWrapperTests(SimpleTestCase): def test_no_can_add_related(self): rel = Individual._meta.get_field('parent').remote_field w = widgets.AdminRadioSelect() # Used to fail with a name error. w = widgets.RelatedFieldWidgetWrapper(w, rel, widget_admin_site) self.assertFalse(w.can_add_related) def test_select_multiple_widget_cant_change_delete_related(self): rel = Individual._meta.get_field('parent').remote_field widget = forms.SelectMultiple() wrapper = widgets.RelatedFieldWidgetWrapper( widget, rel, widget_admin_site, can_add_related=True, can_change_related=True, can_delete_related=True, ) self.assertTrue(wrapper.can_add_related) self.assertFalse(wrapper.can_change_related) self.assertFalse(wrapper.can_delete_related) def test_on_delete_cascade_rel_cant_delete_related(self): rel = Individual._meta.get_field('soulmate').remote_field widget = forms.Select() wrapper = widgets.RelatedFieldWidgetWrapper( widget, rel, widget_admin_site, can_add_related=True, can_change_related=True, can_delete_related=True, ) self.assertTrue(wrapper.can_add_related) self.assertTrue(wrapper.can_change_related) self.assertFalse(wrapper.can_delete_related) def test_custom_widget_render(self): class CustomWidget(forms.Select): def render(self, *args, **kwargs): return 'custom render output' rel = Album._meta.get_field('band').remote_field widget = CustomWidget() wrapper = widgets.RelatedFieldWidgetWrapper( widget, rel, widget_admin_site, can_add_related=True, can_change_related=True, can_delete_related=True, ) output = wrapper.render('name', 'value') self.assertIn('custom render output', output) def test_widget_delegates_value_omitted_from_data(self): class CustomWidget(forms.Select): def value_omitted_from_data(self, data, files, name): return False rel = Album._meta.get_field('band').remote_field widget = CustomWidget() wrapper = widgets.RelatedFieldWidgetWrapper(widget, rel, widget_admin_site) self.assertIs(wrapper.value_omitted_from_data({}, {}, 'band'), False) def test_widget_is_hidden(self): rel = Album._meta.get_field('band').remote_field widget = forms.HiddenInput() widget.choices = () wrapper = widgets.RelatedFieldWidgetWrapper(widget, rel, widget_admin_site) self.assertIs(wrapper.is_hidden, True) context = wrapper.get_context('band', None, {}) self.assertIs(context['is_hidden'], True) output = wrapper.render('name', 'value') # Related item links are hidden. self.assertNotIn('<a ', output) def test_widget_is_not_hidden(self): rel = Album._meta.get_field('band').remote_field widget = forms.Select() wrapper = widgets.RelatedFieldWidgetWrapper(widget, rel, widget_admin_site) self.assertIs(wrapper.is_hidden, False) context = wrapper.get_context('band', None, {}) self.assertIs(context['is_hidden'], False) output = wrapper.render('name', 'value') # Related item links are present. self.assertIn('<a ', output) @override_settings(ROOT_URLCONF='admin_widgets.urls') class AdminWidgetSeleniumTestCase(AdminSeleniumTestCase): available_apps = ['admin_widgets'] + AdminSeleniumTestCase.available_apps def setUp(self): self.u1 = User.objects.create_superuser(username='super', password='secret', email='[email protected]') class DateTimePickerSeleniumTests(AdminWidgetSeleniumTestCase): def test_show_hide_date_time_picker_widgets(self): """ Pressing the ESC key or clicking on a widget value closes the date and time picker widgets. """ from selenium.webdriver.common.keys import Keys self.admin_login(username='super', password='secret', login_url='/') # Open a page that has a date and time picker widgets self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_member_add')) # First, with the date picker widget --------------------------------- cal_icon = self.selenium.find_element_by_id('calendarlink0') # The date picker is hidden self.assertEqual(self.get_css_value('#calendarbox0', 'display'), 'none') # Click the calendar icon cal_icon.click() # The date picker is visible self.assertEqual(self.get_css_value('#calendarbox0', 'display'), 'block') # Press the ESC key self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE]) # The date picker is hidden again self.assertEqual(self.get_css_value('#calendarbox0', 'display'), 'none') # Click the calendar icon, then on the 15th of current month cal_icon.click() self.selenium.find_element_by_xpath("//a[contains(text(), '15')]").click() self.assertEqual(self.get_css_value('#calendarbox0', 'display'), 'none') self.assertEqual( self.selenium.find_element_by_id('id_birthdate_0').get_attribute('value'), datetime.today().strftime('%Y-%m-') + '15', ) # Then, with the time picker widget ---------------------------------- time_icon = self.selenium.find_element_by_id('clocklink0') # The time picker is hidden self.assertEqual(self.get_css_value('#clockbox0', 'display'), 'none') # Click the time icon time_icon.click() # The time picker is visible self.assertEqual(self.get_css_value('#clockbox0', 'display'), 'block') self.assertEqual( [ x.text for x in self.selenium.find_elements_by_xpath("//ul[@class='timelist']/li/a") ], ['Now', 'Midnight', '6 a.m.', 'Noon', '6 p.m.'] ) # Press the ESC key self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE]) # The time picker is hidden again self.assertEqual(self.get_css_value('#clockbox0', 'display'), 'none') # Click the time icon, then select the 'Noon' value time_icon.click() self.selenium.find_element_by_xpath("//a[contains(text(), 'Noon')]").click() self.assertEqual(self.get_css_value('#clockbox0', 'display'), 'none') self.assertEqual( self.selenium.find_element_by_id('id_birthdate_1').get_attribute('value'), '12:00:00', ) def test_calendar_nonday_class(self): """ Ensure cells that are not days of the month have the `nonday` CSS class. Refs #4574. """ self.admin_login(username='super', password='secret', login_url='/') # Open a page that has a date and time picker widgets self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_member_add')) # fill in the birth date. self.selenium.find_element_by_id('id_birthdate_0').send_keys('2013-06-01') # Click the calendar icon self.selenium.find_element_by_id('calendarlink0').click() # get all the tds within the calendar calendar0 = self.selenium.find_element_by_id('calendarin0') tds = calendar0.find_elements_by_tag_name('td') # make sure the first and last 6 cells have class nonday for td in tds[:6] + tds[-6:]: self.assertEqual(td.get_attribute('class'), 'nonday') def test_calendar_selected_class(self): """ Ensure cell for the day in the input has the `selected` CSS class. Refs #4574. """ self.admin_login(username='super', password='secret', login_url='/') # Open a page that has a date and time picker widgets self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_member_add')) # fill in the birth date. self.selenium.find_element_by_id('id_birthdate_0').send_keys('2013-06-01') # Click the calendar icon self.selenium.find_element_by_id('calendarlink0').click() # get all the tds within the calendar calendar0 = self.selenium.find_element_by_id('calendarin0') tds = calendar0.find_elements_by_tag_name('td') # verify the selected cell selected = tds[6] self.assertEqual(selected.get_attribute('class'), 'selected') self.assertEqual(selected.text, '1') def test_calendar_no_selected_class(self): """ Ensure no cells are given the selected class when the field is empty. Refs #4574. """ self.admin_login(username='super', password='secret', login_url='/') # Open a page that has a date and time picker widgets self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_member_add')) # Click the calendar icon self.selenium.find_element_by_id('calendarlink0').click() # get all the tds within the calendar calendar0 = self.selenium.find_element_by_id('calendarin0') tds = calendar0.find_elements_by_tag_name('td') # verify there are no cells with the selected class selected = [td for td in tds if td.get_attribute('class') == 'selected'] self.assertEqual(len(selected), 0) def test_calendar_show_date_from_input(self): """ The calendar shows the date from the input field for every locale supported by Django. """ self.admin_login(username='super', password='secret', login_url='/') # Enter test data member = Member.objects.create(name='Bob', birthdate=datetime(1984, 5, 15), gender='M') # Get month name translations for every locale month_string = 'May' path = os.path.join(os.path.dirname(import_module('django.contrib.admin').__file__), 'locale') for language_code, language_name in settings.LANGUAGES: try: catalog = gettext.translation('djangojs', path, [language_code]) except OSError: continue if month_string in catalog._catalog: month_name = catalog._catalog[month_string] else: month_name = month_string # Get the expected caption may_translation = month_name expected_caption = '{0:s} {1:d}'.format(may_translation.upper(), 1984) # Test with every locale with override_settings(LANGUAGE_CODE=language_code, USE_L10N=True): # Open a page that has a date picker widget url = reverse('admin:admin_widgets_member_change', args=(member.pk,)) self.selenium.get(self.live_server_url + url) # Click on the calendar icon self.selenium.find_element_by_id('calendarlink0').click() # Make sure that the right month and year are displayed self.wait_for_text('#calendarin0 caption', expected_caption) @override_settings(TIME_ZONE='Asia/Singapore') class DateTimePickerShortcutsSeleniumTests(AdminWidgetSeleniumTestCase): def test_date_time_picker_shortcuts(self): """ date/time/datetime picker shortcuts work in the current time zone. Refs #20663. This test case is fairly tricky, it relies on selenium still running the browser in the default time zone "America/Chicago" despite `override_settings` changing the time zone to "Asia/Singapore". """ self.admin_login(username='super', password='secret', login_url='/') error_margin = timedelta(seconds=10) # If we are neighbouring a DST, we add an hour of error margin. tz = pytz.timezone('America/Chicago') utc_now = datetime.now(pytz.utc) tz_yesterday = (utc_now - timedelta(days=1)).astimezone(tz).tzname() tz_tomorrow = (utc_now + timedelta(days=1)).astimezone(tz).tzname() if tz_yesterday != tz_tomorrow: error_margin += timedelta(hours=1) now = datetime.now() self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_member_add')) self.selenium.find_element_by_id('id_name').send_keys('test') # Click on the "today" and "now" shortcuts. shortcuts = self.selenium.find_elements_by_css_selector('.field-birthdate .datetimeshortcuts') for shortcut in shortcuts: shortcut.find_element_by_tag_name('a').click() # There is a time zone mismatch warning. # Warning: This would effectively fail if the TIME_ZONE defined in the # settings has the same UTC offset as "Asia/Singapore" because the # mismatch warning would be rightfully missing from the page. self.selenium.find_elements_by_css_selector('.field-birthdate .timezonewarning') # Submit the form. self.selenium.find_element_by_tag_name('form').submit() self.wait_page_loaded() # Make sure that "now" in javascript is within 10 seconds # from "now" on the server side. member = Member.objects.get(name='test') self.assertGreater(member.birthdate, now - error_margin) self.assertLess(member.birthdate, now + error_margin) # The above tests run with Asia/Singapore which are on the positive side of # UTC. Here we test with a timezone on the negative side. @override_settings(TIME_ZONE='US/Eastern') class DateTimePickerAltTimezoneSeleniumTests(DateTimePickerShortcutsSeleniumTests): pass class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): def setUp(self): super().setUp() self.lisa = Student.objects.create(name='Lisa') self.john = Student.objects.create(name='John') self.bob = Student.objects.create(name='Bob') self.peter = Student.objects.create(name='Peter') self.jenny = Student.objects.create(name='Jenny') self.jason = Student.objects.create(name='Jason') self.cliff = Student.objects.create(name='Cliff') self.arthur = Student.objects.create(name='Arthur') self.school = School.objects.create(name='School of Awesome') def assertActiveButtons(self, mode, field_name, choose, remove, choose_all=None, remove_all=None): choose_link = '#id_%s_add_link' % field_name choose_all_link = '#id_%s_add_all_link' % field_name remove_link = '#id_%s_remove_link' % field_name remove_all_link = '#id_%s_remove_all_link' % field_name self.assertEqual(self.has_css_class(choose_link, 'active'), choose) self.assertEqual(self.has_css_class(remove_link, 'active'), remove) if mode == 'horizontal': self.assertEqual(self.has_css_class(choose_all_link, 'active'), choose_all) self.assertEqual(self.has_css_class(remove_all_link, 'active'), remove_all) def execute_basic_operations(self, mode, field_name): original_url = self.selenium.current_url from_box = '#id_%s_from' % field_name to_box = '#id_%s_to' % field_name choose_link = 'id_%s_add_link' % field_name choose_all_link = 'id_%s_add_all_link' % field_name remove_link = 'id_%s_remove_link' % field_name remove_all_link = 'id_%s_remove_all_link' % field_name # Initial positions --------------------------------------------------- self.assertSelectOptions(from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ]) self.assertSelectOptions(to_box, [str(self.lisa.id), str(self.peter.id)]) self.assertActiveButtons(mode, field_name, False, False, True, True) # Click 'Choose all' -------------------------------------------------- if mode == 'horizontal': self.selenium.find_element_by_id(choose_all_link).click() elif mode == 'vertical': # There 's no 'Choose all' button in vertical mode, so individually # select all options and click 'Choose'. for option in self.selenium.find_elements_by_css_selector(from_box + ' > option'): option.click() self.selenium.find_element_by_id(choose_link).click() self.assertSelectOptions(from_box, []) self.assertSelectOptions(to_box, [ str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ]) self.assertActiveButtons(mode, field_name, False, False, False, True) # Click 'Remove all' -------------------------------------------------- if mode == 'horizontal': self.selenium.find_element_by_id(remove_all_link).click() elif mode == 'vertical': # There 's no 'Remove all' button in vertical mode, so individually # select all options and click 'Remove'. for option in self.selenium.find_elements_by_css_selector(to_box + ' > option'): option.click() self.selenium.find_element_by_id(remove_link).click() self.assertSelectOptions(from_box, [ str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ]) self.assertSelectOptions(to_box, []) self.assertActiveButtons(mode, field_name, False, False, True, False) # Choose some options ------------------------------------------------ from_lisa_select_option = self.get_select_option(from_box, str(self.lisa.id)) # Check the title attribute is there for tool tips: ticket #20821 self.assertEqual(from_lisa_select_option.get_attribute('title'), from_lisa_select_option.get_attribute('text')) from_lisa_select_option.click() self.get_select_option(from_box, str(self.jason.id)).click() self.get_select_option(from_box, str(self.bob.id)).click() self.get_select_option(from_box, str(self.john.id)).click() self.assertActiveButtons(mode, field_name, True, False, True, False) self.selenium.find_element_by_id(choose_link).click() self.assertActiveButtons(mode, field_name, False, False, True, True) self.assertSelectOptions(from_box, [ str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id), ]) self.assertSelectOptions(to_box, [ str(self.lisa.id), str(self.bob.id), str(self.jason.id), str(self.john.id), ]) # Check the tooltip is still there after moving: ticket #20821 to_lisa_select_option = self.get_select_option(to_box, str(self.lisa.id)) self.assertEqual(to_lisa_select_option.get_attribute('title'), to_lisa_select_option.get_attribute('text')) # Remove some options ------------------------------------------------- self.get_select_option(to_box, str(self.lisa.id)).click() self.get_select_option(to_box, str(self.bob.id)).click() self.assertActiveButtons(mode, field_name, False, True, True, True) self.selenium.find_element_by_id(remove_link).click() self.assertActiveButtons(mode, field_name, False, False, True, True) self.assertSelectOptions(from_box, [ str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id) ]) self.assertSelectOptions(to_box, [str(self.jason.id), str(self.john.id)]) # Choose some more options -------------------------------------------- self.get_select_option(from_box, str(self.arthur.id)).click() self.get_select_option(from_box, str(self.cliff.id)).click() self.selenium.find_element_by_id(choose_link).click() self.assertSelectOptions(from_box, [ str(self.peter.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id), ]) self.assertSelectOptions(to_box, [ str(self.jason.id), str(self.john.id), str(self.arthur.id), str(self.cliff.id), ]) # Choose some more options -------------------------------------------- self.get_select_option(from_box, str(self.peter.id)).click() self.get_select_option(from_box, str(self.lisa.id)).click() # Confirm they're selected after clicking inactive buttons: ticket #26575 self.assertSelectedOptions(from_box, [str(self.peter.id), str(self.lisa.id)]) self.selenium.find_element_by_id(remove_link).click() self.assertSelectedOptions(from_box, [str(self.peter.id), str(self.lisa.id)]) # Unselect the options ------------------------------------------------ self.get_select_option(from_box, str(self.peter.id)).click() self.get_select_option(from_box, str(self.lisa.id)).click() # Choose some more options -------------------------------------------- self.get_select_option(to_box, str(self.jason.id)).click() self.get_select_option(to_box, str(self.john.id)).click() # Confirm they're selected after clicking inactive buttons: ticket #26575 self.assertSelectedOptions(to_box, [str(self.jason.id), str(self.john.id)]) self.selenium.find_element_by_id(choose_link).click() self.assertSelectedOptions(to_box, [str(self.jason.id), str(self.john.id)]) # Unselect the options ------------------------------------------------ self.get_select_option(to_box, str(self.jason.id)).click() self.get_select_option(to_box, str(self.john.id)).click() # Pressing buttons shouldn't change the URL. self.assertEqual(self.selenium.current_url, original_url) def test_basic(self): self.school.students.set([self.lisa, self.peter]) self.school.alumni.set([self.lisa, self.peter]) self.admin_login(username='super', password='secret', login_url='/') self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_school_change', args=(self.school.id,))) self.wait_page_loaded() self.execute_basic_operations('vertical', 'students') self.execute_basic_operations('horizontal', 'alumni') # Save and check that everything is properly stored in the database --- self.selenium.find_element_by_xpath('//input[@value="Save"]').click() self.wait_page_loaded() self.school = School.objects.get(id=self.school.id) # Reload from database self.assertEqual(list(self.school.students.all()), [self.arthur, self.cliff, self.jason, self.john]) self.assertEqual(list(self.school.alumni.all()), [self.arthur, self.cliff, self.jason, self.john]) def test_filter(self): """ Typing in the search box filters out options displayed in the 'from' box. """ from selenium.webdriver.common.keys import Keys self.school.students.set([self.lisa, self.peter]) self.school.alumni.set([self.lisa, self.peter]) self.admin_login(username='super', password='secret', login_url='/') self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_school_change', args=(self.school.id,))) for field_name in ['students', 'alumni']: from_box = '#id_%s_from' % field_name to_box = '#id_%s_to' % field_name choose_link = 'id_%s_add_link' % field_name remove_link = 'id_%s_remove_link' % field_name input = self.selenium.find_element_by_id('id_%s_input' % field_name) # Initial values self.assertSelectOptions(from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ]) # Typing in some characters filters out non-matching options input.send_keys('a') self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)]) input.send_keys('R') self.assertSelectOptions(from_box, [str(self.arthur.id)]) # Clearing the text box makes the other options reappear input.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)]) input.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions(from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ]) # ----------------------------------------------------------------- # Choosing a filtered option sends it properly to the 'to' box. input.send_keys('a') self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)]) self.get_select_option(from_box, str(self.jason.id)).click() self.selenium.find_element_by_id(choose_link).click() self.assertSelectOptions(from_box, [str(self.arthur.id)]) self.assertSelectOptions(to_box, [ str(self.lisa.id), str(self.peter.id), str(self.jason.id), ]) self.get_select_option(to_box, str(self.lisa.id)).click() self.selenium.find_element_by_id(remove_link).click() self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.lisa.id)]) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) input.send_keys([Keys.BACK_SPACE]) # Clear text box self.assertSelectOptions(from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jenny.id), str(self.john.id), str(self.lisa.id), ]) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) # ----------------------------------------------------------------- # Pressing enter on a filtered option sends it properly to # the 'to' box. self.get_select_option(to_box, str(self.jason.id)).click() self.selenium.find_element_by_id(remove_link).click() input.send_keys('ja') self.assertSelectOptions(from_box, [str(self.jason.id)]) input.send_keys([Keys.ENTER]) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) input.send_keys([Keys.BACK_SPACE, Keys.BACK_SPACE]) # Save and check that everything is properly stored in the database --- self.selenium.find_element_by_xpath('//input[@value="Save"]').click() self.wait_page_loaded() self.school = School.objects.get(id=self.school.id) # Reload from database self.assertEqual(list(self.school.students.all()), [self.jason, self.peter]) self.assertEqual(list(self.school.alumni.all()), [self.jason, self.peter]) def test_back_button_bug(self): """ Some browsers had a bug where navigating away from the change page and then clicking the browser's back button would clear the filter_horizontal/filter_vertical widgets (#13614). """ self.school.students.set([self.lisa, self.peter]) self.school.alumni.set([self.lisa, self.peter]) self.admin_login(username='super', password='secret', login_url='/') change_url = reverse('admin:admin_widgets_school_change', args=(self.school.id,)) self.selenium.get(self.live_server_url + change_url) # Navigate away and go back to the change form page. self.selenium.find_element_by_link_text('Home').click() self.selenium.back() expected_unselected_values = [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ] expected_selected_values = [str(self.lisa.id), str(self.peter.id)] # Everything is still in place self.assertSelectOptions('#id_students_from', expected_unselected_values) self.assertSelectOptions('#id_students_to', expected_selected_values) self.assertSelectOptions('#id_alumni_from', expected_unselected_values) self.assertSelectOptions('#id_alumni_to', expected_selected_values) def test_refresh_page(self): """ Horizontal and vertical filter widgets keep selected options on page reload (#22955). """ self.school.students.add(self.arthur, self.jason) self.school.alumni.add(self.arthur, self.jason) self.admin_login(username='super', password='secret', login_url='/') change_url = reverse('admin:admin_widgets_school_change', args=(self.school.id,)) self.selenium.get(self.live_server_url + change_url) options_len = len(self.selenium.find_elements_by_css_selector('#id_students_to > option')) self.assertEqual(options_len, 2) # self.selenium.refresh() or send_keys(Keys.F5) does hard reload and # doesn't replicate what happens when a user clicks the browser's # 'Refresh' button. self.selenium.execute_script("location.reload()") self.wait_page_loaded() options_len = len(self.selenium.find_elements_by_css_selector('#id_students_to > option')) self.assertEqual(options_len, 2) class AdminRawIdWidgetSeleniumTests(AdminWidgetSeleniumTestCase): def setUp(self): super().setUp() Band.objects.create(id=42, name='Bogey Blues') Band.objects.create(id=98, name='Green Potatoes') def test_ForeignKey(self): self.admin_login(username='super', password='secret', login_url='/') self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_event_add')) main_window = self.selenium.current_window_handle # No value has been selected yet self.assertEqual(self.selenium.find_element_by_id('id_main_band').get_attribute('value'), '') # Open the popup window and click on a band self.selenium.find_element_by_id('lookup_id_main_band').click() self.wait_for_popup() self.selenium.switch_to.window('id_main_band') link = self.selenium.find_element_by_link_text('Bogey Blues') self.assertIn('/band/42/', link.get_attribute('href')) link.click() # The field now contains the selected band's id self.selenium.switch_to.window(main_window) self.wait_for_value('#id_main_band', '42') # Reopen the popup window and click on another band self.selenium.find_element_by_id('lookup_id_main_band').click() self.wait_for_popup() self.selenium.switch_to.window('id_main_band') link = self.selenium.find_element_by_link_text('Green Potatoes') self.assertIn('/band/98/', link.get_attribute('href')) link.click() # The field now contains the other selected band's id self.selenium.switch_to.window(main_window) self.wait_for_value('#id_main_band', '98') def test_many_to_many(self): self.admin_login(username='super', password='secret', login_url='/') self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_event_add')) main_window = self.selenium.current_window_handle # No value has been selected yet self.assertEqual(self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '') # Help text for the field is displayed self.assertEqual( self.selenium.find_element_by_css_selector('.field-supporting_bands div.help').text, 'Supporting Bands.' ) # Open the popup window and click on a band self.selenium.find_element_by_id('lookup_id_supporting_bands').click() self.wait_for_popup() self.selenium.switch_to.window('id_supporting_bands') link = self.selenium.find_element_by_link_text('Bogey Blues') self.assertIn('/band/42/', link.get_attribute('href')) link.click() # The field now contains the selected band's id self.selenium.switch_to.window(main_window) self.wait_for_value('#id_supporting_bands', '42') # Reopen the popup window and click on another band self.selenium.find_element_by_id('lookup_id_supporting_bands').click() self.wait_for_popup() self.selenium.switch_to.window('id_supporting_bands') link = self.selenium.find_element_by_link_text('Green Potatoes') self.assertIn('/band/98/', link.get_attribute('href')) link.click() # The field now contains the two selected bands' ids self.selenium.switch_to.window(main_window) self.wait_for_value('#id_supporting_bands', '42,98') class RelatedFieldWidgetSeleniumTests(AdminWidgetSeleniumTestCase): def test_ForeignKey_using_to_field(self): self.admin_login(username='super', password='secret', login_url='/') self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_profile_add')) main_window = self.selenium.current_window_handle # Click the Add User button to add new self.selenium.find_element_by_id('add_id_user').click() self.wait_for_popup() self.selenium.switch_to.window('id_user') password_field = self.selenium.find_element_by_id('id_password') password_field.send_keys('password') username_field = self.selenium.find_element_by_id('id_username') username_value = 'newuser' username_field.send_keys(username_value) save_button_css_selector = '.submit-row > input[type=submit]' self.selenium.find_element_by_css_selector(save_button_css_selector).click() self.selenium.switch_to.window(main_window) # The field now contains the new user self.selenium.find_element_by_css_selector('#id_user option[value=newuser]') # Click the Change User button to change it self.selenium.find_element_by_id('change_id_user').click() self.wait_for_popup() self.selenium.switch_to.window('id_user') username_field = self.selenium.find_element_by_id('id_username') username_value = 'changednewuser' username_field.clear() username_field.send_keys(username_value) save_button_css_selector = '.submit-row > input[type=submit]' self.selenium.find_element_by_css_selector(save_button_css_selector).click() self.selenium.switch_to.window(main_window) self.selenium.find_element_by_css_selector('#id_user option[value=changednewuser]') # Go ahead and submit the form to make sure it works self.selenium.find_element_by_css_selector(save_button_css_selector).click() self.wait_for_text('li.success', 'The profile “changednewuser” was added successfully.') profiles = Profile.objects.all() self.assertEqual(len(profiles), 1) self.assertEqual(profiles[0].user.username, username_value)
b90e3d271eeae5d1ddaf3f53021804f3819768adad6b66a05378c7af13ab1627
from django import forms from django.contrib import admin from django.contrib.admin.widgets import AutocompleteSelect from django.forms import ModelChoiceField from django.test import TestCase, override_settings from django.utils import translation from .models import Album, Band class AlbumForm(forms.ModelForm): class Meta: model = Album fields = ['band', 'featuring'] widgets = { 'band': AutocompleteSelect( Album._meta.get_field('band').remote_field, admin.site, attrs={'class': 'my-class'}, ), 'featuring': AutocompleteSelect( Album._meta.get_field('featuring').remote_field, admin.site, ) } class NotRequiredBandForm(forms.Form): band = ModelChoiceField( queryset=Album.objects.all(), widget=AutocompleteSelect(Album._meta.get_field('band').remote_field, admin.site), required=False, ) class RequiredBandForm(forms.Form): band = ModelChoiceField( queryset=Album.objects.all(), widget=AutocompleteSelect(Album._meta.get_field('band').remote_field, admin.site), required=True, ) @override_settings(ROOT_URLCONF='admin_widgets.urls') class AutocompleteMixinTests(TestCase): empty_option = '<option value=""></option>' maxDiff = 1000 def test_build_attrs(self): form = AlbumForm() attrs = form['band'].field.widget.get_context(name='my_field', value=None, attrs={})['widget']['attrs'] self.assertEqual(attrs, { 'class': 'my-class admin-autocomplete', 'data-ajax--cache': 'true', 'data-ajax--delay': 250, 'data-ajax--type': 'GET', 'data-ajax--url': '/admin_widgets/band/autocomplete/', 'data-theme': 'admin-autocomplete', 'data-allow-clear': 'false', 'data-placeholder': '' }) def test_build_attrs_no_custom_class(self): form = AlbumForm() attrs = form['featuring'].field.widget.get_context(name='name', value=None, attrs={})['widget']['attrs'] self.assertEqual(attrs['class'], 'admin-autocomplete') def test_build_attrs_not_required_field(self): form = NotRequiredBandForm() attrs = form['band'].field.widget.build_attrs({}) self.assertJSONEqual(attrs['data-allow-clear'], True) def test_build_attrs_required_field(self): form = RequiredBandForm() attrs = form['band'].field.widget.build_attrs({}) self.assertJSONEqual(attrs['data-allow-clear'], False) def test_get_url(self): rel = Album._meta.get_field('band').remote_field w = AutocompleteSelect(rel, admin.site) url = w.get_url() self.assertEqual(url, '/admin_widgets/band/autocomplete/') def test_render_options(self): beatles = Band.objects.create(name='The Beatles', style='rock') who = Band.objects.create(name='The Who', style='rock') # With 'band', a ForeignKey. form = AlbumForm(initial={'band': beatles.pk}) output = form.as_table() selected_option = '<option value="%s" selected>The Beatles</option>' % beatles.pk option = '<option value="%s">The Who</option>' % who.pk self.assertIn(selected_option, output) self.assertNotIn(option, output) # With 'featuring', a ManyToManyField. form = AlbumForm(initial={'featuring': [beatles.pk, who.pk]}) output = form.as_table() selected_option = '<option value="%s" selected>The Beatles</option>' % beatles.pk option = '<option value="%s" selected>The Who</option>' % who.pk self.assertIn(selected_option, output) self.assertIn(option, output) def test_render_options_required_field(self): """Empty option is present if the field isn't required.""" form = NotRequiredBandForm() output = form.as_table() self.assertIn(self.empty_option, output) def test_render_options_not_required_field(self): """Empty option isn't present if the field isn't required.""" form = RequiredBandForm() output = form.as_table() self.assertNotIn(self.empty_option, output) def test_media(self): rel = Album._meta.get_field('band').remote_field base_files = ( 'admin/js/vendor/jquery/jquery.min.js', 'admin/js/vendor/select2/select2.full.min.js', # Language file is inserted here. 'admin/js/jquery.init.js', 'admin/js/autocomplete.js', ) languages = ( ('de', 'de'), # Language with code 00 does not exist. ('00', None), # Language files are case sensitive. ('sr-cyrl', 'sr-Cyrl'), ('zh-hans', 'zh-CN'), ('zh-hant', 'zh-TW'), ) for lang, select_lang in languages: with self.subTest(lang=lang): if select_lang: expected_files = ( base_files[:2] + (('admin/js/vendor/select2/i18n/%s.js' % select_lang),) + base_files[2:] ) else: expected_files = base_files with translation.override(lang): self.assertEqual(AutocompleteSelect(rel, admin.site).media._js, list(expected_files))
c5f533b63d7aefca3ae8a02badec5605c5b37bb10f3d69605a090a31cb010ee5
from django.db import migrations class Migration(migrations.Migration): dependencies = [] operations = []
2ed198a3ab3765742dbf6f9fb2eb283b3561e4208b1d998b2cb22c8f7211517b
from .custom_permissions import CustomPermissionsUser from .custom_user import ( CustomUser, CustomUserWithoutIsActiveField, ExtensionUser, ) from .invalid_models import CustomUserNonUniqueUsername from .is_active import IsActiveTestUser1 from .minimal import MinimalUser from .no_password import NoPasswordUser from .proxy import Proxy, UserProxy from .uuid_pk import UUIDUser from .with_foreign_key import CustomUserWithFK, Email from .with_integer_username import IntegerUsernameUser from .with_last_login_attr import UserWithDisabledLastLoginField from .with_many_to_many import ( CustomUserWithM2M, CustomUserWithM2MThrough, Organization, ) __all__ = ( 'CustomPermissionsUser', 'CustomUser', 'CustomUserNonUniqueUsername', 'CustomUserWithFK', 'CustomUserWithM2M', 'CustomUserWithM2MThrough', 'CustomUserWithoutIsActiveField', 'Email', 'ExtensionUser', 'IntegerUsernameUser', 'IsActiveTestUser1', 'MinimalUser', 'NoPasswordUser', 'Organization', 'Proxy', 'UUIDUser', 'UserProxy', 'UserWithDisabledLastLoginField', )
c7cd95dded86b9154757de870534ce7f3556278761f6a688889d4348adf8f9c5
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class Organization(models.Model): name = models.CharField(max_length=255) class CustomUserWithM2MManager(BaseUserManager): def create_superuser(self, username, orgs, password): user = self.model(username=username) user.set_password(password) user.save(using=self._db) user.orgs.add(*orgs) return user class CustomUserWithM2M(AbstractBaseUser): username = models.CharField(max_length=30, unique=True) orgs = models.ManyToManyField(Organization) custom_objects = CustomUserWithM2MManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['orgs'] class CustomUserWithM2MThrough(AbstractBaseUser): username = models.CharField(max_length=30, unique=True) orgs = models.ManyToManyField(Organization, through='Membership') custom_objects = CustomUserWithM2MManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['orgs'] class Membership(models.Model): user = models.ForeignKey(CustomUserWithM2MThrough, on_delete=models.CASCADE) organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
d2dbb2307ecc48a1165b0807ad924599048246ba1610fba82ccf39091009e6a4
from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): subparsers_1 = parser.add_subparsers(dest='subcommand_1') parser_foo_1 = subparsers_1.add_parser('foo_1') subparsers_2 = parser_foo_1.add_subparsers(dest='subcommand_2') parser_foo_2 = subparsers_2.add_parser('foo_2') parser_foo_2.add_argument('--bar', required=True) def handle(self, *args, **options): self.stdout.write(','.join(options))
eaf8e457af096dd8ee9e54fa4544d93a0cfc4eba06c1ec355c219090f88e1e52
from django.core.management.base import BaseCommand from django.utils.version import PY37 class Command(BaseCommand): def add_arguments(self, parser): kwargs = {'required': True} if PY37 else {} subparsers = parser.add_subparsers(dest='subcommand', **kwargs) parser_foo = subparsers.add_parser('foo') parser_foo.add_argument('--bar') def handle(self, *args, **options): self.stdout.write(','.join(options))
aa9f0c3d6f61f59fc3f7febed0f42558475fac58398cf3c43f406ace7d67b31f
from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--foo-id', type=int, nargs='?', default=None) group.add_argument('--foo-name', type=str, nargs='?', default=None) def handle(self, *args, **options): self.stdout.write(','.join(options))
ef5866b1b7d907ab3037300dee0b683b019a08affca4fef78c423400f0001c2a
from django.core.serializers.json import DjangoJSONEncoder from django.db import migrations, models from ..fields import ( ArrayField, BigIntegerRangeField, CICharField, CIEmailField, CITextField, DateRangeField, DateTimeRangeField, DecimalRangeField, EnumField, HStoreField, IntegerRangeField, JSONField, SearchVectorField, ) from ..models import TagField class Migration(migrations.Migration): dependencies = [ ('postgres_tests', '0001_setup_extensions'), ] operations = [ migrations.CreateModel( name='CharArrayModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', ArrayField(models.CharField(max_length=10), size=None)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='DateTimeArrayModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('datetimes', ArrayField(models.DateTimeField(), size=None)), ('dates', ArrayField(models.DateField(), size=None)), ('times', ArrayField(models.TimeField(), size=None)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='HStoreModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', HStoreField(blank=True, null=True)), ('array_field', ArrayField(HStoreField(), null=True)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='OtherTypesArrayModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('ips', ArrayField(models.GenericIPAddressField(), size=None, default=list)), ('uuids', ArrayField(models.UUIDField(), size=None, default=list)), ('decimals', ArrayField(models.DecimalField(max_digits=5, decimal_places=2), size=None, default=list)), ('tags', ArrayField(TagField(), blank=True, null=True, size=None)), ('json', ArrayField(JSONField(default={}), default=[])), ('int_ranges', ArrayField(IntegerRangeField(), null=True, blank=True)), ('bigint_ranges', ArrayField(BigIntegerRangeField(), null=True, blank=True)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='IntegerArrayModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', ArrayField(models.IntegerField(), size=None)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='NestedIntegerArrayModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', ArrayField(ArrayField(models.IntegerField(), size=None), size=None)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='NullableIntegerArrayModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', ArrayField(models.IntegerField(), size=None, null=True, blank=True)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='CharFieldModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', models.CharField(max_length=16)), ], options=None, bases=None, ), migrations.CreateModel( name='TextFieldModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', models.TextField()), ], options=None, bases=None, ), migrations.CreateModel( name='Scene', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('scene', models.CharField(max_length=255)), ('setting', models.CharField(max_length=255)), ], options=None, bases=None, ), migrations.CreateModel( name='Character', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=255)), ], options=None, bases=None, ), migrations.CreateModel( name='CITestModel', fields=[ ('name', CICharField(primary_key=True, max_length=255)), ('email', CIEmailField()), ('description', CITextField()), ('array_field', ArrayField(CITextField(), null=True)), ], options={ 'required_db_vendor': 'postgresql', }, bases=None, ), migrations.CreateModel( name='Line', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('scene', models.ForeignKey('postgres_tests.Scene', on_delete=models.SET_NULL)), ('character', models.ForeignKey('postgres_tests.Character', on_delete=models.SET_NULL)), ('dialogue', models.TextField(blank=True, null=True)), ('dialogue_search_vector', SearchVectorField(blank=True, null=True)), ('dialogue_config', models.CharField(max_length=100, blank=True, null=True)), ], options={ 'required_db_vendor': 'postgresql', }, bases=None, ), migrations.CreateModel( name='AggregateTestModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('boolean_field', models.BooleanField(null=True)), ('char_field', models.CharField(max_length=30, blank=True)), ('integer_field', models.IntegerField(null=True)), ] ), migrations.CreateModel( name='StatTestModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('int1', models.IntegerField()), ('int2', models.IntegerField()), ('related_field', models.ForeignKey( 'postgres_tests.AggregateTestModel', models.SET_NULL, null=True, )), ] ), migrations.CreateModel( name='NowTestModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('when', models.DateTimeField(null=True, default=None)), ] ), migrations.CreateModel( name='UUIDTestModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('uuid', models.UUIDField(default=None, null=True)), ] ), migrations.CreateModel( name='RangesModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('ints', IntegerRangeField(null=True, blank=True)), ('bigints', BigIntegerRangeField(null=True, blank=True)), ('decimals', DecimalRangeField(null=True, blank=True)), ('timestamps', DateTimeRangeField(null=True, blank=True)), ('timestamps_inner', DateTimeRangeField(null=True, blank=True)), ('dates', DateRangeField(null=True, blank=True)), ('dates_inner', DateRangeField(null=True, blank=True)), ], options={ 'required_db_vendor': 'postgresql' }, bases=(models.Model,) ), migrations.CreateModel( name='RangeLookupsModel', fields=[ ('parent', models.ForeignKey( 'postgres_tests.RangesModel', models.SET_NULL, blank=True, null=True, )), ('integer', models.IntegerField(blank=True, null=True)), ('big_integer', models.BigIntegerField(blank=True, null=True)), ('float', models.FloatField(blank=True, null=True)), ('timestamp', models.DateTimeField(blank=True, null=True)), ('date', models.DateField(blank=True, null=True)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='JSONModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('field', JSONField(null=True, blank=True)), ('field_custom', JSONField(null=True, blank=True, encoder=DjangoJSONEncoder)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='ArrayEnumModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('array_of_enums', ArrayField(EnumField(max_length=20), null=True, blank=True)), ], options={ 'required_db_vendor': 'postgresql', }, bases=(models.Model,), ), migrations.CreateModel( name='Room', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('number', models.IntegerField(unique=True)), ], ), migrations.CreateModel( name='HotelReservation', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('room', models.ForeignKey('postgres_tests.Room', models.CASCADE)), ('datespan', DateRangeField()), ('start', models.DateTimeField()), ('end', models.DateTimeField()), ('cancelled', models.BooleanField(default=False)), ], options={ 'required_db_vendor': 'postgresql', }, ), ]
d2e59d4cdbc33d02ed2b54c1259b1b541a431fb16b22aca2cafa3d4289fde55b
from datetime import date from django.forms import DateField, Form, SelectDateWidget from django.test import override_settings from django.utils import translation from django.utils.dates import MONTHS_AP from .base import WidgetTest class SelectDateWidgetTest(WidgetTest): maxDiff = None widget = SelectDateWidget( years=('2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016'), ) def test_render_empty(self): self.check_html(self.widget, 'mydate', '', html=( """ <select name="mydate_month" id="id_mydate_month"> <option selected value="">---</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option selected value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option selected value="">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010">2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """ )) def test_render_none(self): """ Rendering the None or '' values should yield the same output. """ self.assertHTMLEqual( self.widget.render('mydate', None), self.widget.render('mydate', ''), ) def test_render_string(self): self.check_html(self.widget, 'mydate', '2010-04-15', html=( """ <select name="mydate_month" id="id_mydate_month"> <option value="">---</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4" selected>April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15" selected>15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected>2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """ )) def test_render_datetime(self): self.assertHTMLEqual( self.widget.render('mydate', date(2010, 4, 15)), self.widget.render('mydate', '2010-04-15'), ) def test_render_invalid_date(self): """ Invalid dates should still render the failed date. """ self.check_html(self.widget, 'mydate', '2010-02-31', html=( """ <select name="mydate_month" id="id_mydate_month"> <option value="">---</option> <option value="1">January</option> <option value="2" selected>February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31" selected>31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected>2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """ )) def test_custom_months(self): widget = SelectDateWidget(months=MONTHS_AP, years=('2013',)) self.check_html(widget, 'mydate', '', html=( """ <select name="mydate_month" id="id_mydate_month"> <option selected value="">---</option> <option value="1">Jan.</option> <option value="2">Feb.</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">Aug.</option> <option value="9">Sept.</option> <option value="10">Oct.</option> <option value="11">Nov.</option> <option value="12">Dec.</option> </select> <select name="mydate_day" id="id_mydate_day"> <option selected value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option selected value="">---</option> <option value="2013">2013</option> </select> """ )) def test_selectdate_required(self): class GetNotRequiredDate(Form): mydate = DateField(widget=SelectDateWidget, required=False) class GetRequiredDate(Form): mydate = DateField(widget=SelectDateWidget, required=True) self.assertFalse(GetNotRequiredDate().fields['mydate'].widget.is_required) self.assertTrue(GetRequiredDate().fields['mydate'].widget.is_required) def test_selectdate_required_placeholder(self): for required in (True, False): field = DateField(widget=SelectDateWidget(years=('2018', '2019')), required=required) self.check_html(field.widget, 'my_date', '', html=( """ <select name="my_date_month" id="id_my_date_month" %(m_placeholder)s> %(empty)s <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="my_date_day" id="id_my_date_day" %(d_placeholder)s> %(empty)s %(days_options)s </select> <select name="my_date_year" id="id_my_date_year" %(y_placeholder)s> %(empty)s <option value="2018">2018</option> <option value="2019">2019</option> </select> """ % { 'days_options': '\n'.join( '<option value="%s">%s</option>' % (i, i) for i in range(1, 32) ), 'm_placeholder': 'placeholder="Month"' if required else '', 'd_placeholder': 'placeholder="Day"' if required else '', 'y_placeholder': 'placeholder="Year"' if required else '', 'empty': '' if required else '<option selected value="">---</option>', } )) def test_selectdate_empty_label(self): w = SelectDateWidget(years=('2014',), empty_label='empty_label') # Rendering the default state with empty_label set as string. self.assertInHTML('<option selected value="">empty_label</option>', w.render('mydate', ''), count=3) w = SelectDateWidget(years=('2014',), empty_label=('empty_year', 'empty_month', 'empty_day')) # Rendering the default state with empty_label tuple. self.assertHTMLEqual( w.render('mydate', ''), """ <select name="mydate_month" id="id_mydate_month"> <option selected value="">empty_month</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option selected value="">empty_day</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option selected value="">empty_year</option> <option value="2014">2014</option> </select> """, ) with self.assertRaisesMessage(ValueError, 'empty_label list/tuple must have 3 elements.'): SelectDateWidget(years=('2014',), empty_label=('not enough', 'values')) @override_settings(USE_L10N=True) @translation.override('nl') def test_l10n(self): w = SelectDateWidget( years=('2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016') ) self.assertEqual( w.value_from_datadict({'date_year': '2010', 'date_month': '8', 'date_day': '13'}, {}, 'date'), '13-08-2010', ) self.assertHTMLEqual( w.render('date', '13-08-2010'), """ <select name="date_day" id="id_date_day"> <option value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13" selected>13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="date_month" id="id_date_month"> <option value="">---</option> <option value="1">januari</option> <option value="2">februari</option> <option value="3">maart</option> <option value="4">april</option> <option value="5">mei</option> <option value="6">juni</option> <option value="7">juli</option> <option value="8" selected>augustus</option> <option value="9">september</option> <option value="10">oktober</option> <option value="11">november</option> <option value="12">december</option> </select> <select name="date_year" id="id_date_year"> <option value="">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected>2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """, ) # Even with an invalid date, the widget should reflect the entered value (#17401). self.assertEqual(w.render('mydate', '2010-02-30').count('selected'), 3) # Years before 1900 should work. w = SelectDateWidget(years=('1899',)) self.assertEqual( w.value_from_datadict({'date_year': '1899', 'date_month': '8', 'date_day': '13'}, {}, 'date'), '13-08-1899', ) # And years before 1000 (demonstrating the need for datetime_safe). w = SelectDateWidget(years=('0001',)) self.assertEqual( w.value_from_datadict({'date_year': '0001', 'date_month': '8', 'date_day': '13'}, {}, 'date'), '13-08-0001', ) @override_settings(USE_L10N=False, DATE_INPUT_FORMATS=['%d.%m.%Y']) def test_custom_input_format(self): w = SelectDateWidget(years=('0001', '1899', '2009', '2010')) for values, expected in ( (('0001', '8', '13'), '13.08.0001'), (('1899', '7', '11'), '11.07.1899'), (('2009', '3', '7'), '07.03.2009'), ): with self.subTest(values=values): data = { 'field_%s' % field: value for field, value in zip(('year', 'month', 'day'), values) } self.assertEqual(w.value_from_datadict(data, {}, 'field'), expected) def test_format_value(self): valid_formats = [ '2000-1-1', '2000-10-15', '2000-01-01', '2000-01-0', '2000-0-01', '2000-0-0', '0-01-01', '0-01-0', '0-0-01', '0-0-0', ] for value in valid_formats: year, month, day = (int(x) or '' for x in value.split('-')) with self.subTest(value=value): self.assertEqual(self.widget.format_value(value), {'day': day, 'month': month, 'year': year}) invalid_formats = [ '2000-01-001', '2000-001-01', '2-01-01', '20-01-01', '200-01-01', '20000-01-01', ] for value in invalid_formats: with self.subTest(value=value): self.assertEqual(self.widget.format_value(value), {'day': None, 'month': None, 'year': None}) def test_value_from_datadict(self): tests = [ (('2000', '12', '1'), '2000-12-01'), (('', '12', '1'), '0-12-1'), (('2000', '', '1'), '2000-0-1'), (('2000', '12', ''), '2000-12-0'), (('', '', '', ''), None), ((None, '12', '1'), None), (('2000', None, '1'), None), (('2000', '12', None), None), ] for values, expected in tests: with self.subTest(values=values): data = {} for field_name, value in zip(('year', 'month', 'day'), values): if value is not None: data['field_%s' % field_name] = value self.assertEqual(self.widget.value_from_datadict(data, {}, 'field'), expected) def test_value_omitted_from_data(self): self.assertIs(self.widget.value_omitted_from_data({}, {}, 'field'), True) self.assertIs(self.widget.value_omitted_from_data({'field_month': '12'}, {}, 'field'), False) self.assertIs(self.widget.value_omitted_from_data({'field_year': '2000'}, {}, 'field'), False) self.assertIs(self.widget.value_omitted_from_data({'field_day': '1'}, {}, 'field'), False) data = {'field_day': '1', 'field_month': '12', 'field_year': '2000'} self.assertIs(self.widget.value_omitted_from_data(data, {}, 'field'), False) @override_settings(USE_THOUSAND_SEPARATOR=True, USE_L10N=True) def test_years_rendered_without_separator(self): widget = SelectDateWidget(years=(2007,)) self.check_html(widget, 'mydate', '', html=( """ <select name="mydate_month" id="id_mydate_month"> <option selected value="">---</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option selected value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option selected value="">---</option> <option value="2007">2007</option> </select> """ ))
e703de634c4f5e07e20f2950fe56c621bb75a904e624127061e5298ecd87e7d6
import copy import datetime from django.forms import Select from django.test import override_settings from django.utils.safestring import mark_safe from .base import WidgetTest class SelectTest(WidgetTest): widget = Select nested_widget = Select(choices=( ('outer1', 'Outer 1'), ('Group "1"', (('inner1', 'Inner 1'), ('inner2', 'Inner 2'))), )) def test_render(self): self.check_html(self.widget(choices=self.beatles), 'beatle', 'J', html=( """<select name="beatle"> <option value="J" selected>John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""" )) def test_render_none(self): """ If the value is None, none of the options are selected. """ self.check_html(self.widget(choices=self.beatles), 'beatle', None, html=( """<select name="beatle"> <option value="J">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""" )) def test_render_label_value(self): """ If the value corresponds to a label (but not to an option value), none of the options are selected. """ self.check_html(self.widget(choices=self.beatles), 'beatle', 'John', html=( """<select name="beatle"> <option value="J">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""" )) def test_render_selected(self): """ Only one option can be selected (#8103). """ choices = [('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('0', 'extra')] self.check_html(self.widget(choices=choices), 'choices', '0', html=( """<select name="choices"> <option value="0" selected>0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="0">extra</option> </select>""" )) def test_constructor_attrs(self): """ Select options shouldn't inherit the parent widget attrs. """ widget = Select( attrs={'class': 'super', 'id': 'super'}, choices=[(1, 1), (2, 2), (3, 3)], ) self.check_html(widget, 'num', 2, html=( """<select name="num" class="super" id="super"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>""" )) def test_compare_to_str(self): """ The value is compared to its str(). """ self.check_html( self.widget(choices=[('1', '1'), ('2', '2'), ('3', '3')]), 'num', 2, html=( """<select name="num"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>""" ), ) self.check_html( self.widget(choices=[(1, 1), (2, 2), (3, 3)]), 'num', '2', html=( """<select name="num"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>""" ), ) self.check_html( self.widget(choices=[(1, 1), (2, 2), (3, 3)]), 'num', 2, html=( """<select name="num"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>""" ), ) def test_choices_constructor(self): widget = Select(choices=[(1, 1), (2, 2), (3, 3)]) self.check_html(widget, 'num', 2, html=( """<select name="num"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>""" )) def test_choices_constructor_generator(self): """ If choices is passed to the constructor and is a generator, it can be iterated over multiple times without getting consumed. """ def get_choices(): for i in range(5): yield (i, i) widget = Select(choices=get_choices()) self.check_html(widget, 'num', 2, html=( """<select name="num"> <option value="0">0</option> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> <option value="4">4</option> </select>""" )) self.check_html(widget, 'num', 3, html=( """<select name="num"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3" selected>3</option> <option value="4">4</option> </select>""" )) def test_choices_escaping(self): choices = (('bad', 'you & me'), ('good', mark_safe('you &gt; me'))) self.check_html(self.widget(choices=choices), 'escape', None, html=( """<select name="escape"> <option value="bad">you &amp; me</option> <option value="good">you &gt; me</option> </select>""" )) def test_choices_unicode(self): self.check_html( self.widget(choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), 'email', 'ŠĐĆŽćžšđ', html=( """<select name="email"> <option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111 </option> <option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option> </select>""" ), ) def test_choices_optgroup(self): """ Choices can be nested one level in order to create HTML optgroups. """ self.check_html(self.nested_widget, 'nestchoice', None, html=( """<select name="nestchoice"> <option value="outer1">Outer 1</option> <optgroup label="Group &quot;1&quot;"> <option value="inner1">Inner 1</option> <option value="inner2">Inner 2</option> </optgroup> </select>""" )) def test_choices_select_outer(self): self.check_html(self.nested_widget, 'nestchoice', 'outer1', html=( """<select name="nestchoice"> <option value="outer1" selected>Outer 1</option> <optgroup label="Group &quot;1&quot;"> <option value="inner1">Inner 1</option> <option value="inner2">Inner 2</option> </optgroup> </select>""" )) def test_choices_select_inner(self): self.check_html(self.nested_widget, 'nestchoice', 'inner1', html=( """<select name="nestchoice"> <option value="outer1">Outer 1</option> <optgroup label="Group &quot;1&quot;"> <option value="inner1" selected>Inner 1</option> <option value="inner2">Inner 2</option> </optgroup> </select>""" )) @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True) def test_doesnt_localize_option_value(self): choices = [ (1, 'One'), (1000, 'One thousand'), (1000000, 'One million'), ] html = """ <select name="number"> <option value="1">One</option> <option value="1000">One thousand</option> <option value="1000000">One million</option> </select> """ self.check_html(self.widget(choices=choices), 'number', None, html=html) choices = [ (datetime.time(0, 0), 'midnight'), (datetime.time(12, 0), 'noon'), ] html = """ <select name="time"> <option value="00:00:00">midnight</option> <option value="12:00:00">noon</option> </select> """ self.check_html(self.widget(choices=choices), 'time', None, html=html) def test_options(self): options = list(self.widget(choices=self.beatles).options( 'name', ['J'], attrs={'class': 'super'}, )) self.assertEqual(len(options), 4) self.assertEqual(options[0]['name'], 'name') self.assertEqual(options[0]['value'], 'J') self.assertEqual(options[0]['label'], 'John') self.assertEqual(options[0]['index'], '0') self.assertEqual(options[0]['selected'], True) # Template-related attributes self.assertEqual(options[1]['name'], 'name') self.assertEqual(options[1]['value'], 'P') self.assertEqual(options[1]['label'], 'Paul') self.assertEqual(options[1]['index'], '1') self.assertEqual(options[1]['selected'], False) def test_optgroups(self): choices = [ ('Audio', [ ('vinyl', 'Vinyl'), ('cd', 'CD'), ]), ('Video', [ ('vhs', 'VHS Tape'), ('dvd', 'DVD'), ]), ('unknown', 'Unknown'), ] groups = list(self.widget(choices=choices).optgroups( 'name', ['vhs'], attrs={'class': 'super'}, )) audio, video, unknown = groups label, options, index = audio self.assertEqual(label, 'Audio') self.assertEqual( options, [{ 'value': 'vinyl', 'type': 'select', 'attrs': {}, 'index': '0_0', 'label': 'Vinyl', 'template_name': 'django/forms/widgets/select_option.html', 'name': 'name', 'selected': False, 'wrap_label': True, }, { 'value': 'cd', 'type': 'select', 'attrs': {}, 'index': '0_1', 'label': 'CD', 'template_name': 'django/forms/widgets/select_option.html', 'name': 'name', 'selected': False, 'wrap_label': True, }] ) self.assertEqual(index, 0) label, options, index = video self.assertEqual(label, 'Video') self.assertEqual( options, [{ 'value': 'vhs', 'template_name': 'django/forms/widgets/select_option.html', 'label': 'VHS Tape', 'attrs': {'selected': True}, 'index': '1_0', 'name': 'name', 'selected': True, 'type': 'select', 'wrap_label': True, }, { 'value': 'dvd', 'template_name': 'django/forms/widgets/select_option.html', 'label': 'DVD', 'attrs': {}, 'index': '1_1', 'name': 'name', 'selected': False, 'type': 'select', 'wrap_label': True, }] ) self.assertEqual(index, 1) label, options, index = unknown self.assertEqual(label, None) self.assertEqual( options, [{ 'value': 'unknown', 'selected': False, 'template_name': 'django/forms/widgets/select_option.html', 'label': 'Unknown', 'attrs': {}, 'index': '2', 'name': 'name', 'type': 'select', 'wrap_label': True, }] ) self.assertEqual(index, 2) def test_optgroups_integer_choices(self): """The option 'value' is the same type as what's in `choices`.""" groups = list(self.widget(choices=[[0, 'choice text']]).optgroups('name', ['vhs'])) label, options, index = groups[0] self.assertEqual(options[0]['value'], 0) def test_deepcopy(self): """ __deepcopy__() should copy all attributes properly (#25085). """ widget = Select() obj = copy.deepcopy(widget) self.assertIsNot(widget, obj) self.assertEqual(widget.choices, obj.choices) self.assertIsNot(widget.choices, obj.choices) self.assertEqual(widget.attrs, obj.attrs) self.assertIsNot(widget.attrs, obj.attrs) def test_doesnt_render_required_when_impossible_to_select_empty_field(self): widget = self.widget(choices=[('J', 'John'), ('P', 'Paul')]) self.assertIs(widget.use_required_attribute(initial=None), False) def test_renders_required_when_possible_to_select_empty_field_str(self): widget = self.widget(choices=[('', 'select please'), ('P', 'Paul')]) self.assertIs(widget.use_required_attribute(initial=None), True) def test_renders_required_when_possible_to_select_empty_field_list(self): widget = self.widget(choices=[['', 'select please'], ['P', 'Paul']]) self.assertIs(widget.use_required_attribute(initial=None), True) def test_renders_required_when_possible_to_select_empty_field_none(self): widget = self.widget(choices=[(None, 'select please'), ('P', 'Paul')]) self.assertIs(widget.use_required_attribute(initial=None), True) def test_doesnt_render_required_when_no_choices_are_available(self): widget = self.widget(choices=[]) self.assertIs(widget.use_required_attribute(initial=None), False)
8f7f80a4af4b6f628b3468208cc4d6ee630782f0b678442eb3ad7e5cee698a7d
from datetime import date, datetime from django.forms import ( DateField, Form, HiddenInput, SelectDateWidget, ValidationError, ) from django.test import SimpleTestCase, override_settings from django.utils import translation class GetDate(Form): mydate = DateField(widget=SelectDateWidget) class DateFieldTest(SimpleTestCase): def test_form_field(self): a = GetDate({'mydate_month': '4', 'mydate_day': '1', 'mydate_year': '2008'}) self.assertTrue(a.is_valid()) self.assertEqual(a.cleaned_data['mydate'], date(2008, 4, 1)) # As with any widget that implements get_value_from_datadict(), we must # accept the input from the "as_hidden" rendering as well. self.assertHTMLEqual( a['mydate'].as_hidden(), '<input type="hidden" name="mydate" value="2008-04-01" id="id_mydate">', ) b = GetDate({'mydate': '2008-4-1'}) self.assertTrue(b.is_valid()) self.assertEqual(b.cleaned_data['mydate'], date(2008, 4, 1)) # Invalid dates shouldn't be allowed c = GetDate({'mydate_month': '2', 'mydate_day': '31', 'mydate_year': '2010'}) self.assertFalse(c.is_valid()) self.assertEqual(c.errors, {'mydate': ['Enter a valid date.']}) # label tag is correctly associated with month dropdown d = GetDate({'mydate_month': '1', 'mydate_day': '1', 'mydate_year': '2010'}) self.assertIn('<label for="id_mydate_month">', d.as_p()) @override_settings(USE_L10N=True) @translation.override('nl') def test_l10n_date_changed(self): """ DateField.has_changed() with SelectDateWidget works with a localized date format (#17165). """ # With Field.show_hidden_initial=False b = GetDate({ 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '1', }, initial={'mydate': date(2008, 4, 1)}) self.assertFalse(b.has_changed()) b = GetDate({ 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '2', }, initial={'mydate': date(2008, 4, 1)}) self.assertTrue(b.has_changed()) # With Field.show_hidden_initial=True class GetDateShowHiddenInitial(Form): mydate = DateField(widget=SelectDateWidget, show_hidden_initial=True) b = GetDateShowHiddenInitial({ 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '1', 'initial-mydate': HiddenInput().format_value(date(2008, 4, 1)), }, initial={'mydate': date(2008, 4, 1)}) self.assertFalse(b.has_changed()) b = GetDateShowHiddenInitial({ 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '22', 'initial-mydate': HiddenInput().format_value(date(2008, 4, 1)), }, initial={'mydate': date(2008, 4, 1)}) self.assertTrue(b.has_changed()) b = GetDateShowHiddenInitial({ 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '22', 'initial-mydate': HiddenInput().format_value(date(2008, 4, 1)), }, initial={'mydate': date(2008, 4, 22)}) self.assertTrue(b.has_changed()) b = GetDateShowHiddenInitial({ 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '22', 'initial-mydate': HiddenInput().format_value(date(2008, 4, 22)), }, initial={'mydate': date(2008, 4, 1)}) self.assertFalse(b.has_changed()) @override_settings(USE_L10N=True) @translation.override('nl') def test_l10n_invalid_date_in(self): # Invalid dates shouldn't be allowed a = GetDate({'mydate_month': '2', 'mydate_day': '31', 'mydate_year': '2010'}) self.assertFalse(a.is_valid()) # 'Geef een geldige datum op.' = 'Enter a valid date.' self.assertEqual(a.errors, {'mydate': ['Voer een geldige datum in.']}) @override_settings(USE_L10N=True) @translation.override('nl') def test_form_label_association(self): # label tag is correctly associated with first rendered dropdown a = GetDate({'mydate_month': '1', 'mydate_day': '1', 'mydate_year': '2010'}) self.assertIn('<label for="id_mydate_day">', a.as_p()) def test_datefield_1(self): f = DateField() self.assertEqual(date(2006, 10, 25), f.clean(date(2006, 10, 25))) self.assertEqual(date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30))) self.assertEqual(date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30, 59))) self.assertEqual(date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30, 59, 200))) self.assertEqual(date(2006, 10, 25), f.clean('2006-10-25')) self.assertEqual(date(2006, 10, 25), f.clean('10/25/2006')) self.assertEqual(date(2006, 10, 25), f.clean('10/25/06')) self.assertEqual(date(2006, 10, 25), f.clean('Oct 25 2006')) self.assertEqual(date(2006, 10, 25), f.clean('October 25 2006')) self.assertEqual(date(2006, 10, 25), f.clean('October 25, 2006')) self.assertEqual(date(2006, 10, 25), f.clean('25 October 2006')) self.assertEqual(date(2006, 10, 25), f.clean('25 October, 2006')) with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean('2006-4-31') with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean('200a-10-25') with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean('25/10/06') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) def test_datefield_2(self): f = DateField(required=False) self.assertIsNone(f.clean(None)) self.assertEqual('None', repr(f.clean(None))) self.assertIsNone(f.clean('')) self.assertEqual('None', repr(f.clean(''))) def test_datefield_3(self): f = DateField(input_formats=['%Y %m %d']) self.assertEqual(date(2006, 10, 25), f.clean(date(2006, 10, 25))) self.assertEqual(date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30))) self.assertEqual(date(2006, 10, 25), f.clean('2006 10 25')) with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean('2006-10-25') with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean('10/25/2006') with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean('10/25/06') def test_datefield_4(self): # Test whitespace stripping behavior (#5714) f = DateField() self.assertEqual(date(2006, 10, 25), f.clean(' 10/25/2006 ')) self.assertEqual(date(2006, 10, 25), f.clean(' 10/25/06 ')) self.assertEqual(date(2006, 10, 25), f.clean(' Oct 25 2006 ')) self.assertEqual(date(2006, 10, 25), f.clean(' October 25 2006 ')) self.assertEqual(date(2006, 10, 25), f.clean(' October 25, 2006 ')) self.assertEqual(date(2006, 10, 25), f.clean(' 25 October 2006 ')) with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean(' ') def test_datefield_5(self): # Test null bytes (#18982) f = DateField() with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean('a\x00b') def test_datefield_changed(self): format = '%d/%m/%Y' f = DateField(input_formats=[format]) d = date(2007, 9, 17) self.assertFalse(f.has_changed(d, '17/09/2007')) def test_datefield_strptime(self): """field.strptime() doesn't raise a UnicodeEncodeError (#16123)""" f = DateField() try: f.strptime('31 мая 2011', '%d-%b-%y') except Exception as e: # assertIsInstance or assertRaises cannot be used because UnicodeEncodeError # is a subclass of ValueError self.assertEqual(e.__class__, ValueError)
726f532b4363c2c8aebc2ab4d0d084d319b9af13e96d16d538706d929802e746
import os import unittest from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import ( ClearableFileInput, FileInput, ImageField, ValidationError, Widget, ) from django.test import SimpleTestCase from . import FormFieldAssertionsMixin try: from PIL import Image except ImportError: Image = None def get_img_path(path): return os.path.join(os.path.abspath(os.path.join(__file__, '..', '..')), 'tests', path) @unittest.skipUnless(Image, "Pillow is required to test ImageField") class ImageFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_imagefield_annotate_with_image_after_clean(self): f = ImageField() img_path = get_img_path('filepath_test_files/1x1.png') with open(img_path, 'rb') as img_file: img_data = img_file.read() img_file = SimpleUploadedFile('1x1.png', img_data) img_file.content_type = 'text/plain' uploaded_file = f.clean(img_file) self.assertEqual('PNG', uploaded_file.image.format) self.assertEqual('image/png', uploaded_file.content_type) def test_imagefield_annotate_with_bitmap_image_after_clean(self): """ This also tests the situation when Pillow doesn't detect the MIME type of the image (#24948). """ from PIL.BmpImagePlugin import BmpImageFile try: Image.register_mime(BmpImageFile.format, None) f = ImageField() img_path = get_img_path('filepath_test_files/1x1.bmp') with open(img_path, 'rb') as img_file: img_data = img_file.read() img_file = SimpleUploadedFile('1x1.bmp', img_data) img_file.content_type = 'text/plain' uploaded_file = f.clean(img_file) self.assertEqual('BMP', uploaded_file.image.format) self.assertIsNone(uploaded_file.content_type) finally: Image.register_mime(BmpImageFile.format, 'image/bmp') def test_file_extension_validation(self): f = ImageField() img_path = get_img_path('filepath_test_files/1x1.png') with open(img_path, 'rb') as img_file: img_data = img_file.read() img_file = SimpleUploadedFile('1x1.txt', img_data) with self.assertRaisesMessage(ValidationError, 'File extension “txt” is not allowed.'): f.clean(img_file) def test_widget_attrs_default_accept(self): f = ImageField() # Nothing added for non-FileInput widgets. self.assertEqual(f.widget_attrs(Widget()), {}) self.assertEqual(f.widget_attrs(FileInput()), {'accept': 'image/*'}) self.assertEqual(f.widget_attrs(ClearableFileInput()), {'accept': 'image/*'}) self.assertWidgetRendersTo(f, '<input type="file" name="f" accept="image/*" required id="id_f" />') def test_widge_attrs_accept_specified(self): f = ImageField(widget=FileInput(attrs={'accept': 'image/png'})) self.assertEqual(f.widget_attrs(f.widget), {}) self.assertWidgetRendersTo(f, '<input type="file" name="f" accept="image/png" required id="id_f" />') def test_widge_attrs_accept_false(self): f = ImageField(widget=FileInput(attrs={'accept': False})) self.assertEqual(f.widget_attrs(f.widget), {}) self.assertWidgetRendersTo(f, '<input type="file" name="f" required id="id_f" />')
310ee954572b45b6ed7964d4f4dcf9e9f04110b3ea516e4e89c99ba8797e7f7b
from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import ( BooleanField, CharField, ChoiceField, DateField, DateTimeField, DecimalField, EmailField, FileField, FloatField, Form, GenericIPAddressField, IntegerField, ModelChoiceField, ModelMultipleChoiceField, MultipleChoiceField, RegexField, SplitDateTimeField, TimeField, URLField, ValidationError, utils, ) from django.template import Context, Template from django.test import SimpleTestCase, TestCase from django.utils.safestring import mark_safe from ..models import ChoiceModel class AssertFormErrorsMixin: def assertFormErrors(self, expected, the_callable, *args, **kwargs): with self.assertRaises(ValidationError) as cm: the_callable(*args, **kwargs) self.assertEqual(cm.exception.messages, expected) class FormsErrorMessagesTestCase(SimpleTestCase, AssertFormErrorsMixin): def test_charfield(self): e = { 'required': 'REQUIRED', 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s', 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', } f = CharField(min_length=5, max_length=10, error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['LENGTH 4, MIN LENGTH 5'], f.clean, '1234') self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901') def test_integerfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_value': 'MIN VALUE IS %(limit_value)s', 'max_value': 'MAX VALUE IS %(limit_value)s', } f = IntegerField(min_value=5, max_value=10, error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc') self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4') self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11') def test_floatfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_value': 'MIN VALUE IS %(limit_value)s', 'max_value': 'MAX VALUE IS %(limit_value)s', } f = FloatField(min_value=5, max_value=10, error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc') self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4') self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11') def test_decimalfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_value': 'MIN VALUE IS %(limit_value)s', 'max_value': 'MAX VALUE IS %(limit_value)s', 'max_digits': 'MAX DIGITS IS %(max)s', 'max_decimal_places': 'MAX DP IS %(max)s', 'max_whole_digits': 'MAX DIGITS BEFORE DP IS %(max)s', } f = DecimalField(min_value=5, max_value=10, error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc') self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4') self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11') f2 = DecimalField(max_digits=4, decimal_places=2, error_messages=e) self.assertFormErrors(['MAX DIGITS IS 4'], f2.clean, '123.45') self.assertFormErrors(['MAX DP IS 2'], f2.clean, '1.234') self.assertFormErrors(['MAX DIGITS BEFORE DP IS 2'], f2.clean, '123.4') def test_datefield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', } f = DateField(error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc') def test_timefield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', } f = TimeField(error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc') def test_datetimefield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', } f = DateTimeField(error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc') def test_regexfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s', 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', } f = RegexField(r'^[0-9]+$', min_length=5, max_length=10, error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abcde') self.assertFormErrors(['LENGTH 4, MIN LENGTH 5'], f.clean, '1234') self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901') def test_emailfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s', 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', } f = EmailField(min_length=8, max_length=10, error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abcdefgh') self.assertFormErrors(['LENGTH 7, MIN LENGTH 8'], f.clean, '[email protected]') self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, '[email protected]') def test_filefield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'missing': 'MISSING', 'empty': 'EMPTY FILE', } f = FileField(error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc') self.assertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', None)) self.assertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', '')) def test_urlfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'max_length': '"%(value)s" has more than %(limit_value)d characters.', } f = URLField(error_messages=e, max_length=17) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc.c') self.assertFormErrors( ['"http://djangoproject.com" has more than 17 characters.'], f.clean, 'djangoproject.com' ) def test_booleanfield(self): e = { 'required': 'REQUIRED', } f = BooleanField(error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') def test_choicefield(self): e = { 'required': 'REQUIRED', 'invalid_choice': '%(value)s IS INVALID CHOICE', } f = ChoiceField(choices=[('a', 'aye')], error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['b IS INVALID CHOICE'], f.clean, 'b') def test_multiplechoicefield(self): e = { 'required': 'REQUIRED', 'invalid_choice': '%(value)s IS INVALID CHOICE', 'invalid_list': 'NOT A LIST', } f = MultipleChoiceField(choices=[('a', 'aye')], error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['NOT A LIST'], f.clean, 'b') self.assertFormErrors(['b IS INVALID CHOICE'], f.clean, ['b']) def test_splitdatetimefield(self): e = { 'required': 'REQUIRED', 'invalid_date': 'INVALID DATE', 'invalid_time': 'INVALID TIME', } f = SplitDateTimeField(error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID DATE', 'INVALID TIME'], f.clean, ['a', 'b']) def test_generic_ipaddressfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID IP ADDRESS', } f = GenericIPAddressField(error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID IP ADDRESS'], f.clean, '127.0.0') def test_subclassing_errorlist(self): class TestForm(Form): first_name = CharField() last_name = CharField() birthday = DateField() def clean(self): raise ValidationError("I like to be awkward.") class CustomErrorList(utils.ErrorList): def __str__(self): return self.as_divs() def as_divs(self): if not self: return '' return mark_safe('<div class="error">%s</div>' % ''.join('<p>%s</p>' % e for e in self)) # This form should print errors the default way. form1 = TestForm({'first_name': 'John'}) self.assertHTMLEqual( str(form1['last_name'].errors), '<ul class="errorlist"><li>This field is required.</li></ul>' ) self.assertHTMLEqual( str(form1.errors['__all__']), '<ul class="errorlist nonfield"><li>I like to be awkward.</li></ul>' ) # This one should wrap error groups in the customized way. form2 = TestForm({'first_name': 'John'}, error_class=CustomErrorList) self.assertHTMLEqual(str(form2['last_name'].errors), '<div class="error"><p>This field is required.</p></div>') self.assertHTMLEqual(str(form2.errors['__all__']), '<div class="error"><p>I like to be awkward.</p></div>') def test_error_messages_escaping(self): # The forms layer doesn't escape input values directly because error # messages might be presented in non-HTML contexts. Instead, the # message is marked for escaping by the template engine, so a template # is needed to trigger the escaping. t = Template('{{ form.errors }}') class SomeForm(Form): field = ChoiceField(choices=[('one', 'One')]) f = SomeForm({'field': '<script>'}) self.assertHTMLEqual( t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist">' '<li>Select a valid choice. &lt;script&gt; is not one of the ' 'available choices.</li></ul></li></ul>' ) class SomeForm(Form): field = MultipleChoiceField(choices=[('one', 'One')]) f = SomeForm({'field': ['<script>']}) self.assertHTMLEqual( t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist">' '<li>Select a valid choice. &lt;script&gt; is not one of the ' 'available choices.</li></ul></li></ul>' ) class SomeForm(Form): field = ModelMultipleChoiceField(ChoiceModel.objects.all()) f = SomeForm({'field': ['<script>']}) self.assertHTMLEqual( t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist">' '<li>“&lt;script&gt;” is not a valid value.</li>' '</ul></li></ul>' ) class ModelChoiceFieldErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): def test_modelchoicefield(self): # Create choices for the model choice field tests below. ChoiceModel.objects.create(pk=1, name='a') ChoiceModel.objects.create(pk=2, name='b') ChoiceModel.objects.create(pk=3, name='c') # ModelChoiceField e = { 'required': 'REQUIRED', 'invalid_choice': 'INVALID CHOICE', } f = ModelChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID CHOICE'], f.clean, '4') # ModelMultipleChoiceField e = { 'required': 'REQUIRED', 'invalid_choice': '%(value)s IS INVALID CHOICE', 'list': 'NOT A LIST OF VALUES', } f = ModelMultipleChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['NOT A LIST OF VALUES'], f.clean, '3') self.assertFormErrors(['4 IS INVALID CHOICE'], f.clean, ['4'])
da069abe08e525b4c92a7c48a612836c796673598655af5596e951efc19ffd51
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_invalid_index(self): class TestForm(Form): name = ChoiceField(choices=[]) field = TestForm()['name'] msg = 'BoundField indices must be integers or slices, not str.' with self.assertRaisesMessage(TypeError, msg): field['foo'] 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) def test_field_deep_copy_error_messages(self): class CustomCharField(CharField): def __init__(self, **kwargs): kwargs['error_messages'] = {'invalid': 'Form custom error message.'} super().__init__(**kwargs) field = CustomCharField() field_copy = copy.deepcopy(field) self.assertIsInstance(field_copy, CustomCharField) self.assertIsNot(field_copy.error_messages, field.error_messages) 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)
d01b7eab741face8c1d1f83ef0ea6b74f63fef3b4be827c4f13e602736d3a609
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 ' '“Referer header” 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 “Referer” ' 'headers, please re-enable them, at least for this site, or for ' 'HTTPS connections, or for “same-origin” 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 ' '“Referrer-Policy: no-referrer” 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')
72d9ad5293321150ee537a008527dad12630d6d4938fe82ad75ef9ed6eb5f047
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.http import Http404 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.urls.converters import IntConverter 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') def test_technical_404_converter_raise_404(self): with mock.patch.object(IntConverter, 'to_python', side_effect=Http404): response = self.client.get('/path-post/1/') self.assertContains(response, 'Page not found', status_code=404) 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, line 2', html) self.assertIn( '"generated", line 2, in funcName\n' ' &lt;source code not available&gt;', html, ) text = reporter.get_traceback_text() self.assertIn( '"generated", line 2, in funcName\n' ' <source code not available>', 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 ) # COOKIES 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 (most recent call last):', 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 (most recent call last):', 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) # COOKIES 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)
3bb41de3234e80d957961db2db27dd5739f0136f011c240cccac4cbd06bef69d
from django.db import models class ParentManager(models.Manager): def get_by_natural_key(self, parent_data): return self.get(parent_data=parent_data) class Parent(models.Model): parent_data = models.CharField(max_length=30, unique=True) parent_m2m = models.ManyToManyField('self') objects = ParentManager() def natural_key(self): return (self.parent_data,) class Child(Parent): child_data = models.CharField(max_length=30, unique=True)
65c5382ca1a0f0b9214eb61573ba13fe13a3c719152de2b55654cb1c0c230f04
from django.template.base import TemplateSyntaxError from django.template.context import Context from django.test import SimpleTestCase from ..utils import SilentAttrClass, SilentGetItemClass, SomeClass, setup basic_templates = { 'basic-syntax01': 'something cool', 'basic-syntax02': '{{ headline }}', 'basic-syntax03': '{{ first }} --- {{ second }}', } class BasicSyntaxTests(SimpleTestCase): @setup(basic_templates) def test_basic_syntax01(self): """ Plain text should go through the template parser untouched. """ output = self.engine.render_to_string('basic-syntax01') self.assertEqual(output, "something cool") @setup(basic_templates) def test_basic_syntax02(self): """ Variables should be replaced with their value in the current context """ output = self.engine.render_to_string('basic-syntax02', {'headline': 'Success'}) self.assertEqual(output, 'Success') @setup(basic_templates) def test_basic_syntax03(self): """ More than one replacement variable is allowed in a template """ output = self.engine.render_to_string('basic-syntax03', {"first": 1, "second": 2}) self.assertEqual(output, '1 --- 2') @setup({'basic-syntax04': 'as{{ missing }}df'}) def test_basic_syntax04(self): """ Fail silently when a variable is not found in the current context """ output = self.engine.render_to_string('basic-syntax04') if self.engine.string_if_invalid: self.assertEqual(output, 'asINVALIDdf') else: self.assertEqual(output, 'asdf') @setup({'basic-syntax06': '{{ multi word variable }}'}) def test_basic_syntax06(self): """ A variable may not contain more than one word """ with self.assertRaises(TemplateSyntaxError): self.engine.get_template('basic-syntax06') @setup({'basic-syntax07': '{{ }}'}) def test_basic_syntax07(self): """ Raise TemplateSyntaxError for empty variable tags. """ with self.assertRaisesMessage(TemplateSyntaxError, 'Empty variable tag on line 1'): self.engine.get_template('basic-syntax07') @setup({'basic-syntax08': '{{ }}'}) def test_basic_syntax08(self): """ Raise TemplateSyntaxError for empty variable tags. """ with self.assertRaisesMessage(TemplateSyntaxError, 'Empty variable tag on line 1'): self.engine.get_template('basic-syntax08') @setup({'basic-syntax09': '{{ var.method }}'}) def test_basic_syntax09(self): """ Attribute syntax allows a template to call an object's attribute """ output = self.engine.render_to_string('basic-syntax09', {'var': SomeClass()}) self.assertEqual(output, 'SomeClass.method') @setup({'basic-syntax10': '{{ var.otherclass.method }}'}) def test_basic_syntax10(self): """ Multiple levels of attribute access are allowed. """ output = self.engine.render_to_string('basic-syntax10', {'var': SomeClass()}) self.assertEqual(output, 'OtherClass.method') @setup({'basic-syntax11': '{{ var.blech }}'}) def test_basic_syntax11(self): """ Fail silently when a variable's attribute isn't found. """ output = self.engine.render_to_string('basic-syntax11', {'var': SomeClass()}) if self.engine.string_if_invalid: self.assertEqual(output, 'INVALID') else: self.assertEqual(output, '') @setup({'basic-syntax12': '{{ var.__dict__ }}'}) def test_basic_syntax12(self): """ Raise TemplateSyntaxError when trying to access a variable beginning with an underscore. """ with self.assertRaises(TemplateSyntaxError): self.engine.get_template('basic-syntax12') # Raise TemplateSyntaxError when trying to access a variable # containing an illegal character. @setup({'basic-syntax13': "{{ va>r }}"}) def test_basic_syntax13(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template('basic-syntax13') @setup({'basic-syntax14': "{{ (var.r) }}"}) def test_basic_syntax14(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template('basic-syntax14') @setup({'basic-syntax15': "{{ sp%am }}"}) def test_basic_syntax15(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template('basic-syntax15') @setup({'basic-syntax16': "{{ eggs! }}"}) def test_basic_syntax16(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template('basic-syntax16') @setup({'basic-syntax17': "{{ moo? }}"}) def test_basic_syntax17(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template('basic-syntax17') @setup({'basic-syntax18': "{{ foo.bar }}"}) def test_basic_syntax18(self): """ Attribute syntax allows a template to call a dictionary key's value. """ output = self.engine.render_to_string('basic-syntax18', {"foo": {"bar": "baz"}}) self.assertEqual(output, "baz") @setup({'basic-syntax19': "{{ foo.spam }}"}) def test_basic_syntax19(self): """ Fail silently when a variable's dictionary key isn't found. """ output = self.engine.render_to_string('basic-syntax19', {"foo": {"bar": "baz"}}) if self.engine.string_if_invalid: self.assertEqual(output, 'INVALID') else: self.assertEqual(output, '') @setup({'basic-syntax20': "{{ var.method2 }}"}) def test_basic_syntax20(self): """ Fail silently when accessing a non-simple method """ output = self.engine.render_to_string('basic-syntax20', {'var': SomeClass()}) if self.engine.string_if_invalid: self.assertEqual(output, 'INVALID') else: self.assertEqual(output, '') @setup({'basic-syntax20b': "{{ var.method5 }}"}) def test_basic_syntax20b(self): """ Don't silence a TypeError if it was raised inside a callable. """ template = self.engine.get_template('basic-syntax20b') with self.assertRaises(TypeError): template.render(Context({'var': SomeClass()})) # Don't get confused when parsing something that is almost, but not # quite, a template tag. @setup({'basic-syntax21': "a {{ moo %} b"}) def test_basic_syntax21(self): output = self.engine.render_to_string('basic-syntax21') self.assertEqual(output, "a {{ moo %} b") @setup({'basic-syntax22': "{{ moo #}"}) def test_basic_syntax22(self): output = self.engine.render_to_string('basic-syntax22') self.assertEqual(output, "{{ moo #}") @setup({'basic-syntax23': "{{ moo #} {{ cow }}"}) def test_basic_syntax23(self): """ Treat "moo #} {{ cow" as the variable. Not ideal, but costly to work around, so this triggers an error. """ with self.assertRaises(TemplateSyntaxError): self.engine.get_template('basic-syntax23') @setup({'basic-syntax24': "{{ moo\n }}"}) def test_basic_syntax24(self): """ Embedded newlines make it not-a-tag. """ output = self.engine.render_to_string('basic-syntax24') self.assertEqual(output, "{{ moo\n }}") # Literal strings are permitted inside variables, mostly for i18n # purposes. @setup({'basic-syntax25': '{{ "fred" }}'}) def test_basic_syntax25(self): output = self.engine.render_to_string('basic-syntax25') self.assertEqual(output, "fred") @setup({'basic-syntax26': r'{{ "\"fred\"" }}'}) def test_basic_syntax26(self): output = self.engine.render_to_string('basic-syntax26') self.assertEqual(output, "\"fred\"") @setup({'basic-syntax27': r'{{ _("\"fred\"") }}'}) def test_basic_syntax27(self): output = self.engine.render_to_string('basic-syntax27') self.assertEqual(output, "\"fred\"") # #12554 -- Make sure a silent_variable_failure Exception is # suppressed on dictionary and attribute lookup. @setup({'basic-syntax28': "{{ a.b }}"}) def test_basic_syntax28(self): output = self.engine.render_to_string('basic-syntax28', {'a': SilentGetItemClass()}) if self.engine.string_if_invalid: self.assertEqual(output, 'INVALID') else: self.assertEqual(output, '') @setup({'basic-syntax29': "{{ a.b }}"}) def test_basic_syntax29(self): output = self.engine.render_to_string('basic-syntax29', {'a': SilentAttrClass()}) if self.engine.string_if_invalid: self.assertEqual(output, 'INVALID') else: self.assertEqual(output, '') # Something that starts like a number but has an extra lookup works # as a lookup. @setup({'basic-syntax30': "{{ 1.2.3 }}"}) def test_basic_syntax30(self): output = self.engine.render_to_string( 'basic-syntax30', {"1": {"2": {"3": "d"}}} ) self.assertEqual(output, 'd') @setup({'basic-syntax31': "{{ 1.2.3 }}"}) def test_basic_syntax31(self): output = self.engine.render_to_string( 'basic-syntax31', {"1": {"2": ("a", "b", "c", "d")}}, ) self.assertEqual(output, 'd') @setup({'basic-syntax32': "{{ 1.2.3 }}"}) def test_basic_syntax32(self): output = self.engine.render_to_string( 'basic-syntax32', {"1": (("x", "x", "x", "x"), ("y", "y", "y", "y"), ("a", "b", "c", "d"))}, ) self.assertEqual(output, 'd') @setup({'basic-syntax33': "{{ 1.2.3 }}"}) def test_basic_syntax33(self): output = self.engine.render_to_string( 'basic-syntax33', {"1": ("xxxx", "yyyy", "abcd")}, ) self.assertEqual(output, 'd') @setup({'basic-syntax34': "{{ 1.2.3 }}"}) def test_basic_syntax34(self): output = self.engine.render_to_string( 'basic-syntax34', {"1": ({"x": "x"}, {"y": "y"}, {"z": "z", "3": "d"})} ) self.assertEqual(output, 'd') # Numbers are numbers even if their digits are in the context. @setup({'basic-syntax35': "{{ 1 }}"}) def test_basic_syntax35(self): output = self.engine.render_to_string('basic-syntax35', {"1": "abc"}) self.assertEqual(output, '1') @setup({'basic-syntax36': "{{ 1.2 }}"}) def test_basic_syntax36(self): output = self.engine.render_to_string('basic-syntax36', {"1": "abc"}) self.assertEqual(output, '1.2') @setup({'basic-syntax37': '{{ callable }}'}) def test_basic_syntax37(self): """ Call methods in the top level of the context. """ output = self.engine.render_to_string('basic-syntax37', {"callable": lambda: "foo bar"}) self.assertEqual(output, 'foo bar') @setup({'basic-syntax38': '{{ var.callable }}'}) def test_basic_syntax38(self): """ Call methods returned from dictionary lookups. """ output = self.engine.render_to_string('basic-syntax38', {"var": {"callable": lambda: "foo bar"}}) self.assertEqual(output, 'foo bar') @setup({'template': '{% block content %}'}) def test_unclosed_block(self): msg = "Unclosed tag on line 1: 'block'. Looking for one of: endblock." with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% if a %}'}) def test_unclosed_block2(self): msg = "Unclosed tag on line 1: 'if'. Looking for one of: elif, else, endif." with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'tpl-str': '%s', 'tpl-percent': '%%', 'tpl-weird-percent': '% %s'}) def test_ignores_strings_that_look_like_format_interpolation(self): output = self.engine.render_to_string('tpl-str') self.assertEqual(output, '%s') output = self.engine.render_to_string('tpl-percent') self.assertEqual(output, '%%') output = self.engine.render_to_string('tpl-weird-percent') self.assertEqual(output, '% %s')
027afcd98812a2605f74ac462ec903ac22a30f72d02a1c78ddc3e827f039478b
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 …</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></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>')
7d2b9011d3f8146e9e46bc7017b83b73bf6c5a7ef10618395c8a117e6c13342a
import os from asgiref.local import Local from django.template import Context, Template, TemplateSyntaxError from django.test import SimpleTestCase, override_settings from django.utils import translation from django.utils.safestring import mark_safe from django.utils.translation import trans_real from ...utils import setup from .base import MultipleLocaleActivationTestCase, extended_locale_paths, here class I18nBlockTransTagTests(SimpleTestCase): libraries = {'i18n': 'django.templatetags.i18n'} @setup({'i18n03': '{% load i18n %}{% blocktrans %}{{ anton }}{% endblocktrans %}'}) def test_i18n03(self): """simple translation of a variable""" output = self.engine.render_to_string('i18n03', {'anton': 'Å'}) self.assertEqual(output, 'Å') @setup({'i18n04': '{% load i18n %}{% blocktrans with berta=anton|lower %}{{ berta }}{% endblocktrans %}'}) def test_i18n04(self): """simple translation of a variable and filter""" output = self.engine.render_to_string('i18n04', {'anton': 'Å'}) self.assertEqual(output, 'å') @setup({'legacyi18n04': '{% load i18n %}' '{% blocktrans with anton|lower as berta %}{{ berta }}{% endblocktrans %}'}) def test_legacyi18n04(self): """simple translation of a variable and filter""" output = self.engine.render_to_string('legacyi18n04', {'anton': 'Å'}) self.assertEqual(output, 'å') @setup({'i18n05': '{% load i18n %}{% blocktrans %}xxx{{ anton }}xxx{% endblocktrans %}'}) def test_i18n05(self): """simple translation of a string with interpolation""" output = self.engine.render_to_string('i18n05', {'anton': 'yyy'}) self.assertEqual(output, 'xxxyyyxxx') @setup({'i18n07': '{% load i18n %}' '{% blocktrans count counter=number %}singular{% plural %}' '{{ counter }} plural{% endblocktrans %}'}) def test_i18n07(self): """translation of singular form""" output = self.engine.render_to_string('i18n07', {'number': 1}) self.assertEqual(output, 'singular') @setup({'legacyi18n07': '{% load i18n %}' '{% blocktrans count number as counter %}singular{% plural %}' '{{ counter }} plural{% endblocktrans %}'}) def test_legacyi18n07(self): """translation of singular form""" output = self.engine.render_to_string('legacyi18n07', {'number': 1}) self.assertEqual(output, 'singular') @setup({'i18n08': '{% load i18n %}' '{% blocktrans count number as counter %}singular{% plural %}' '{{ counter }} plural{% endblocktrans %}'}) def test_i18n08(self): """translation of plural form""" output = self.engine.render_to_string('i18n08', {'number': 2}) self.assertEqual(output, '2 plural') @setup({'legacyi18n08': '{% load i18n %}' '{% blocktrans count counter=number %}singular{% plural %}' '{{ counter }} plural{% endblocktrans %}'}) def test_legacyi18n08(self): """translation of plural form""" output = self.engine.render_to_string('legacyi18n08', {'number': 2}) self.assertEqual(output, '2 plural') @setup({'i18n17': '{% load i18n %}' '{% blocktrans with berta=anton|escape %}{{ berta }}{% endblocktrans %}'}) def test_i18n17(self): """ Escaping inside blocktrans and trans works as if it was directly in the template. """ output = self.engine.render_to_string('i18n17', {'anton': 'α & β'}) self.assertEqual(output, 'α &amp; β') @setup({'i18n18': '{% load i18n %}' '{% blocktrans with berta=anton|force_escape %}{{ berta }}{% endblocktrans %}'}) def test_i18n18(self): output = self.engine.render_to_string('i18n18', {'anton': 'α & β'}) self.assertEqual(output, 'α &amp; β') @setup({'i18n19': '{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}'}) def test_i18n19(self): output = self.engine.render_to_string('i18n19', {'andrew': 'a & b'}) self.assertEqual(output, 'a &amp; b') @setup({'i18n21': '{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}'}) def test_i18n21(self): output = self.engine.render_to_string('i18n21', {'andrew': mark_safe('a & b')}) self.assertEqual(output, 'a & b') @setup({'legacyi18n17': '{% load i18n %}' '{% blocktrans with anton|escape as berta %}{{ berta }}{% endblocktrans %}'}) def test_legacyi18n17(self): output = self.engine.render_to_string('legacyi18n17', {'anton': 'α & β'}) self.assertEqual(output, 'α &amp; β') @setup({'legacyi18n18': '{% load i18n %}' '{% blocktrans with anton|force_escape as berta %}' '{{ berta }}{% endblocktrans %}'}) def test_legacyi18n18(self): output = self.engine.render_to_string('legacyi18n18', {'anton': 'α & β'}) self.assertEqual(output, 'α &amp; β') @setup({'i18n26': '{% load i18n %}' '{% blocktrans with extra_field=myextra_field count counter=number %}' 'singular {{ extra_field }}{% plural %}plural{% endblocktrans %}'}) def test_i18n26(self): """ translation of plural form with extra field in singular form (#13568) """ output = self.engine.render_to_string('i18n26', {'myextra_field': 'test', 'number': 1}) self.assertEqual(output, 'singular test') @setup({'legacyi18n26': '{% load i18n %}' '{% blocktrans with myextra_field as extra_field count number as counter %}' 'singular {{ extra_field }}{% plural %}plural{% endblocktrans %}'}) def test_legacyi18n26(self): output = self.engine.render_to_string('legacyi18n26', {'myextra_field': 'test', 'number': 1}) self.assertEqual(output, 'singular test') @setup({'i18n27': '{% load i18n %}{% blocktrans count counter=number %}' '{{ counter }} result{% plural %}{{ counter }} results' '{% endblocktrans %}'}) def test_i18n27(self): """translation of singular form in Russian (#14126)""" with translation.override('ru'): output = self.engine.render_to_string('i18n27', {'number': 1}) self.assertEqual(output, '1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442') @setup({'legacyi18n27': '{% load i18n %}' '{% blocktrans count number as counter %}{{ counter }} result' '{% plural %}{{ counter }} results{% endblocktrans %}'}) def test_legacyi18n27(self): with translation.override('ru'): output = self.engine.render_to_string('legacyi18n27', {'number': 1}) self.assertEqual(output, '1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442') @setup({'i18n28': '{% load i18n %}' '{% blocktrans with a=anton b=berta %}{{ a }} + {{ b }}{% endblocktrans %}'}) def test_i18n28(self): """simple translation of multiple variables""" output = self.engine.render_to_string('i18n28', {'anton': 'α', 'berta': 'β'}) self.assertEqual(output, 'α + β') @setup({'legacyi18n28': '{% load i18n %}' '{% blocktrans with anton as a and berta as b %}' '{{ a }} + {{ b }}{% endblocktrans %}'}) def test_legacyi18n28(self): output = self.engine.render_to_string('legacyi18n28', {'anton': 'α', 'berta': 'β'}) self.assertEqual(output, 'α + β') # blocktrans handling of variables which are not in the context. # this should work as if blocktrans was not there (#19915) @setup({'i18n34': '{% load i18n %}{% blocktrans %}{{ missing }}{% endblocktrans %}'}) def test_i18n34(self): output = self.engine.render_to_string('i18n34') if self.engine.string_if_invalid: self.assertEqual(output, 'INVALID') else: self.assertEqual(output, '') @setup({'i18n34_2': '{% load i18n %}{% blocktrans with a=\'α\' %}{{ missing }}{% endblocktrans %}'}) def test_i18n34_2(self): output = self.engine.render_to_string('i18n34_2') if self.engine.string_if_invalid: self.assertEqual(output, 'INVALID') else: self.assertEqual(output, '') @setup({'i18n34_3': '{% load i18n %}{% blocktrans with a=anton %}{{ missing }}{% endblocktrans %}'}) def test_i18n34_3(self): output = self.engine.render_to_string( 'i18n34_3', {'anton': '\xce\xb1'}) if self.engine.string_if_invalid: self.assertEqual(output, 'INVALID') else: self.assertEqual(output, '') @setup({'i18n37': '{% load i18n %}' '{% trans "Page not found" as page_not_found %}' '{% blocktrans %}Error: {{ page_not_found }}{% endblocktrans %}'}) def test_i18n37(self): with translation.override('de'): output = self.engine.render_to_string('i18n37') self.assertEqual(output, 'Error: Seite nicht gefunden') # blocktrans tag with asvar @setup({'i18n39': '{% load i18n %}' '{% blocktrans asvar page_not_found %}Page not found{% endblocktrans %}' '>{{ page_not_found }}<'}) def test_i18n39(self): with translation.override('de'): output = self.engine.render_to_string('i18n39') self.assertEqual(output, '>Seite nicht gefunden<') @setup({'i18n40': '{% load i18n %}' '{% trans "Page not found" as pg_404 %}' '{% blocktrans with page_not_found=pg_404 asvar output %}' 'Error: {{ page_not_found }}' '{% endblocktrans %}'}) def test_i18n40(self): output = self.engine.render_to_string('i18n40') self.assertEqual(output, '') @setup({'i18n41': '{% load i18n %}' '{% trans "Page not found" as pg_404 %}' '{% blocktrans with page_not_found=pg_404 asvar output %}' 'Error: {{ page_not_found }}' '{% endblocktrans %}' '>{{ output }}<'}) def test_i18n41(self): with translation.override('de'): output = self.engine.render_to_string('i18n41') self.assertEqual(output, '>Error: Seite nicht gefunden<') @setup({'template': '{% load i18n %}{% blocktrans asvar %}Yes{% endblocktrans %}'}) def test_blocktrans_syntax_error_missing_assignment(self): msg = "No argument provided to the 'blocktrans' tag for the asvar option." with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% blocktrans %}%s{% endblocktrans %}'}) def test_blocktrans_tag_using_a_string_that_looks_like_str_fmt(self): output = self.engine.render_to_string('template') self.assertEqual(output, '%s') @setup({'template': '{% load i18n %}{% blocktrans %}{% block b %} {% endblock %}{% endblocktrans %}'}) def test_with_block(self): msg = "'blocktrans' doesn't allow other block tags (seen 'block b') inside it" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% blocktrans %}{% for b in [1, 2, 3] %} {% endfor %}{% endblocktrans %}'}) def test_with_for(self): msg = "'blocktrans' doesn't allow other block tags (seen 'for b in [1, 2, 3]') inside it" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% blocktrans with foo=bar with %}{{ foo }}{% endblocktrans %}'}) def test_variable_twice(self): with self.assertRaisesMessage(TemplateSyntaxError, "The 'with' option was specified more than once"): self.engine.render_to_string('template', {'foo': 'bar'}) @setup({'template': '{% load i18n %}{% blocktrans with %}{% endblocktrans %}'}) def test_no_args_with(self): msg = '"with" in \'blocktrans\' tag needs at least one keyword argument.' with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% blocktrans count a %}{% endblocktrans %}'}) def test_count(self): msg = '"count" in \'blocktrans\' tag expected exactly one keyword argument.' with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template', {'a': [1, 2, 3]}) @setup({'template': ( '{% load i18n %}{% blocktrans count count=var|length %}' 'There is {{ count }} object. {% block a %} {% endblock %}' '{% endblocktrans %}' )}) def test_plural_bad_syntax(self): msg = "'blocktrans' doesn't allow other block tags inside it" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template', {'var': [1, 2, 3]}) class TranslationBlockTransTagTests(SimpleTestCase): @override_settings(LOCALE_PATHS=extended_locale_paths) def test_template_tags_pgettext(self): """{% blocktrans %} takes message contexts into account (#14806).""" trans_real._active = Local() trans_real._translations = {} with translation.override('de'): # Nonexistent context t = Template('{% load i18n %}{% blocktrans context "nonexistent" %}May{% endblocktrans %}') rendered = t.render(Context()) self.assertEqual(rendered, 'May') # Existing context... using a literal t = Template('{% load i18n %}{% blocktrans context "month name" %}May{% endblocktrans %}') rendered = t.render(Context()) self.assertEqual(rendered, 'Mai') t = Template('{% load i18n %}{% blocktrans context "verb" %}May{% endblocktrans %}') rendered = t.render(Context()) self.assertEqual(rendered, 'Kann') # Using a variable t = Template('{% load i18n %}{% blocktrans context message_context %}May{% endblocktrans %}') rendered = t.render(Context({'message_context': 'month name'})) self.assertEqual(rendered, 'Mai') t = Template('{% load i18n %}{% blocktrans context message_context %}May{% endblocktrans %}') rendered = t.render(Context({'message_context': 'verb'})) self.assertEqual(rendered, 'Kann') # Using a filter t = Template('{% load i18n %}{% blocktrans context message_context|lower %}May{% endblocktrans %}') rendered = t.render(Context({'message_context': 'MONTH NAME'})) self.assertEqual(rendered, 'Mai') t = Template('{% load i18n %}{% blocktrans context message_context|lower %}May{% endblocktrans %}') rendered = t.render(Context({'message_context': 'VERB'})) self.assertEqual(rendered, 'Kann') # Using 'count' t = Template( '{% load i18n %}{% blocktrans count number=1 context "super search" %}' '{{ number }} super result{% plural %}{{ number }} super results{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, '1 Super-Ergebnis') t = Template( '{% load i18n %}{% blocktrans count number=2 context "super search" %}{{ number }}' ' super result{% plural %}{{ number }} super results{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, '2 Super-Ergebnisse') t = Template( '{% load i18n %}{% blocktrans context "other super search" count number=1 %}' '{{ number }} super result{% plural %}{{ number }} super results{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, '1 anderen Super-Ergebnis') t = Template( '{% load i18n %}{% blocktrans context "other super search" count number=2 %}' '{{ number }} super result{% plural %}{{ number }} super results{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, '2 andere Super-Ergebnisse') # Using 'with' t = Template( '{% load i18n %}{% blocktrans with num_comments=5 context "comment count" %}' 'There are {{ num_comments }} comments{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, 'Es gibt 5 Kommentare') t = Template( '{% load i18n %}{% blocktrans with num_comments=5 context "other comment count" %}' 'There are {{ num_comments }} comments{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, 'Andere: Es gibt 5 Kommentare') # Using trimmed t = Template( '{% load i18n %}{% blocktrans trimmed %}\n\nThere\n\t are 5 ' '\n\n comments\n{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, 'There are 5 comments') t = Template( '{% load i18n %}{% blocktrans with num_comments=5 context "comment count" trimmed %}\n\n' 'There are \t\n \t {{ num_comments }} comments\n\n{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, 'Es gibt 5 Kommentare') t = Template( '{% load i18n %}{% blocktrans context "other super search" count number=2 trimmed %}\n' '{{ number }} super \n result{% plural %}{{ number }} super results{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, '2 andere Super-Ergebnisse') # Misuses msg = "Unknown argument for 'blocktrans' tag: %r." with self.assertRaisesMessage(TemplateSyntaxError, msg % 'month="May"'): Template('{% load i18n %}{% blocktrans context with month="May" %}{{ month }}{% endblocktrans %}') msg = '"context" in %r tag expected exactly one argument.' % 'blocktrans' with self.assertRaisesMessage(TemplateSyntaxError, msg): Template('{% load i18n %}{% blocktrans context %}{% endblocktrans %}') with self.assertRaisesMessage(TemplateSyntaxError, msg): Template( '{% load i18n %}{% blocktrans count number=2 context %}' '{{ number }} super result{% plural %}{{ number }}' ' super results{% endblocktrans %}' ) @override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')]) def test_bad_placeholder_1(self): """ Error in translation file should not crash template rendering (#16516). (%(person)s is translated as %(personne)s in fr.po). """ with translation.override('fr'): t = Template('{% load i18n %}{% blocktrans %}My name is {{ person }}.{% endblocktrans %}') rendered = t.render(Context({'person': 'James'})) self.assertEqual(rendered, 'My name is James.') @override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')]) def test_bad_placeholder_2(self): """ Error in translation file should not crash template rendering (#18393). (%(person) misses a 's' in fr.po, causing the string formatting to fail) . """ with translation.override('fr'): t = Template('{% load i18n %}{% blocktrans %}My other name is {{ person }}.{% endblocktrans %}') rendered = t.render(Context({'person': 'James'})) self.assertEqual(rendered, 'My other name is James.') class MultipleLocaleActivationBlockTransTests(MultipleLocaleActivationTestCase): def test_single_locale_activation(self): """ Simple baseline behavior with one locale for all the supported i18n constructs. """ with translation.override('fr'): self.assertEqual( Template("{% load i18n %}{% blocktrans %}Yes{% endblocktrans %}").render(Context({})), 'Oui' ) def test_multiple_locale_btrans(self): with translation.override('de'): t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}") with translation.override(self._old_language), translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_deactivate_btrans(self): with translation.override('de', deactivate=True): t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}") with translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_direct_switch_btrans(self): with translation.override('de'): t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}") with translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') class MiscTests(SimpleTestCase): @override_settings(LOCALE_PATHS=extended_locale_paths) def test_percent_in_translatable_block(self): t_sing = Template("{% load i18n %}{% blocktrans %}The result was {{ percent }}%{% endblocktrans %}") t_plur = Template( "{% load i18n %}{% blocktrans count num as number %}" "{{ percent }}% represents {{ num }} object{% plural %}" "{{ percent }}% represents {{ num }} objects{% endblocktrans %}" ) with translation.override('de'): self.assertEqual(t_sing.render(Context({'percent': 42})), 'Das Ergebnis war 42%') self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), '42% stellt 1 Objekt dar') self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), '42% stellt 4 Objekte dar') @override_settings(LOCALE_PATHS=extended_locale_paths) def test_percent_formatting_in_blocktrans(self): """ Python's %-formatting is properly escaped in blocktrans, singular, or plural. """ t_sing = Template("{% load i18n %}{% blocktrans %}There are %(num_comments)s comments{% endblocktrans %}") t_plur = Template( "{% load i18n %}{% blocktrans count num as number %}" "%(percent)s% represents {{ num }} object{% plural %}" "%(percent)s% represents {{ num }} objects{% endblocktrans %}" ) with translation.override('de'): # Strings won't get translated as they don't match after escaping % self.assertEqual(t_sing.render(Context({'num_comments': 42})), 'There are %(num_comments)s comments') self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), '%(percent)s% represents 1 object') self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), '%(percent)s% represents 4 objects')
f8484fd73f9d87812cd80f19db0d7d752ecd17856c350189ad72addef64cc26f
from asgiref.local import Local from django.template import Context, Template, TemplateSyntaxError from django.templatetags.l10n import LocalizeNode from django.test import SimpleTestCase, override_settings from django.utils import translation from django.utils.safestring import mark_safe from django.utils.translation import trans_real from ...utils import setup from .base import MultipleLocaleActivationTestCase, extended_locale_paths class I18nTransTagTests(SimpleTestCase): libraries = {'i18n': 'django.templatetags.i18n'} @setup({'i18n01': '{% load i18n %}{% trans \'xxxyyyxxx\' %}'}) def test_i18n01(self): """simple translation of a string delimited by '.""" output = self.engine.render_to_string('i18n01') self.assertEqual(output, 'xxxyyyxxx') @setup({'i18n02': '{% load i18n %}{% trans "xxxyyyxxx" %}'}) def test_i18n02(self): """simple translation of a string delimited by ".""" output = self.engine.render_to_string('i18n02') self.assertEqual(output, 'xxxyyyxxx') @setup({'i18n06': '{% load i18n %}{% trans "Page not found" %}'}) def test_i18n06(self): """simple translation of a string to German""" with translation.override('de'): output = self.engine.render_to_string('i18n06') self.assertEqual(output, 'Seite nicht gefunden') @setup({'i18n09': '{% load i18n %}{% trans "Page not found" noop %}'}) def test_i18n09(self): """simple non-translation (only marking) of a string to German""" with translation.override('de'): output = self.engine.render_to_string('i18n09') self.assertEqual(output, 'Page not found') @setup({'i18n20': '{% load i18n %}{% trans andrew %}'}) def test_i18n20(self): output = self.engine.render_to_string('i18n20', {'andrew': 'a & b'}) self.assertEqual(output, 'a &amp; b') @setup({'i18n22': '{% load i18n %}{% trans andrew %}'}) def test_i18n22(self): output = self.engine.render_to_string('i18n22', {'andrew': mark_safe('a & b')}) self.assertEqual(output, 'a & b') @setup({'i18n23': '{% load i18n %}{% trans "Page not found"|capfirst|slice:"6:" %}'}) def test_i18n23(self): """Using filters with the {% trans %} tag (#5972).""" with translation.override('de'): output = self.engine.render_to_string('i18n23') self.assertEqual(output, 'nicht gefunden') @setup({'i18n24': '{% load i18n %}{% trans \'Page not found\'|upper %}'}) def test_i18n24(self): with translation.override('de'): output = self.engine.render_to_string('i18n24') self.assertEqual(output, 'SEITE NICHT GEFUNDEN') @setup({'i18n25': '{% load i18n %}{% trans somevar|upper %}'}) def test_i18n25(self): with translation.override('de'): output = self.engine.render_to_string('i18n25', {'somevar': 'Page not found'}) self.assertEqual(output, 'SEITE NICHT GEFUNDEN') # trans tag with as var @setup({'i18n35': '{% load i18n %}{% trans "Page not found" as page_not_found %}{{ page_not_found }}'}) def test_i18n35(self): with translation.override('de'): output = self.engine.render_to_string('i18n35') self.assertEqual(output, 'Seite nicht gefunden') @setup({'i18n36': '{% load i18n %}' '{% trans "Page not found" noop as page_not_found %}{{ page_not_found }}'}) def test_i18n36(self): with translation.override('de'): output = self.engine.render_to_string('i18n36') self.assertEqual(output, 'Page not found') @setup({'template': '{% load i18n %}{% trans %}A}'}) def test_syntax_error_no_arguments(self): msg = "'trans' takes at least one argument" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% trans "Yes" badoption %}'}) def test_syntax_error_bad_option(self): msg = "Unknown argument for 'trans' tag: 'badoption'" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% trans "Yes" as %}'}) def test_syntax_error_missing_assignment(self): msg = "No argument provided to the 'trans' tag for the as option." with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% trans "Yes" as var context %}'}) def test_syntax_error_missing_context(self): msg = "No argument provided to the 'trans' tag for the context option." with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% trans "Yes" context as var %}'}) def test_syntax_error_context_as(self): msg = "Invalid argument 'as' provided to the 'trans' tag for the context option" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% trans "Yes" context noop %}'}) def test_syntax_error_context_noop(self): msg = "Invalid argument 'noop' provided to the 'trans' tag for the context option" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% trans "Yes" noop noop %}'}) def test_syntax_error_duplicate_option(self): msg = "The 'noop' option was specified more than once." with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% trans "%s" %}'}) def test_trans_tag_using_a_string_that_looks_like_str_fmt(self): output = self.engine.render_to_string('template') self.assertEqual(output, '%s') class TranslationTransTagTests(SimpleTestCase): @override_settings(LOCALE_PATHS=extended_locale_paths) def test_template_tags_pgettext(self): """{% trans %} takes message contexts into account (#14806).""" trans_real._active = Local() trans_real._translations = {} with translation.override('de'): # Nonexistent context... t = Template('{% load i18n %}{% trans "May" context "nonexistent" %}') rendered = t.render(Context()) self.assertEqual(rendered, 'May') # Existing context... using a literal t = Template('{% load i18n %}{% trans "May" context "month name" %}') rendered = t.render(Context()) self.assertEqual(rendered, 'Mai') t = Template('{% load i18n %}{% trans "May" context "verb" %}') rendered = t.render(Context()) self.assertEqual(rendered, 'Kann') # Using a variable t = Template('{% load i18n %}{% trans "May" context message_context %}') rendered = t.render(Context({'message_context': 'month name'})) self.assertEqual(rendered, 'Mai') t = Template('{% load i18n %}{% trans "May" context message_context %}') rendered = t.render(Context({'message_context': 'verb'})) self.assertEqual(rendered, 'Kann') # Using a filter t = Template('{% load i18n %}{% trans "May" context message_context|lower %}') rendered = t.render(Context({'message_context': 'MONTH NAME'})) self.assertEqual(rendered, 'Mai') t = Template('{% load i18n %}{% trans "May" context message_context|lower %}') rendered = t.render(Context({'message_context': 'VERB'})) self.assertEqual(rendered, 'Kann') # Using 'as' t = Template('{% load i18n %}{% trans "May" context "month name" as var %}Value: {{ var }}') rendered = t.render(Context()) self.assertEqual(rendered, 'Value: Mai') t = Template('{% load i18n %}{% trans "May" as var context "verb" %}Value: {{ var }}') rendered = t.render(Context()) self.assertEqual(rendered, 'Value: Kann') class MultipleLocaleActivationTransTagTests(MultipleLocaleActivationTestCase): def test_single_locale_activation(self): """ Simple baseline behavior with one locale for all the supported i18n constructs. """ with translation.override('fr'): self.assertEqual(Template("{% load i18n %}{% trans 'Yes' %}").render(Context({})), 'Oui') def test_multiple_locale_trans(self): with translation.override('de'): t = Template("{% load i18n %}{% trans 'No' %}") with translation.override(self._old_language), translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_deactivate_trans(self): with translation.override('de', deactivate=True): t = Template("{% load i18n %}{% trans 'No' %}") with translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_direct_switch_trans(self): with translation.override('de'): t = Template("{% load i18n %}{% trans 'No' %}") with translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') class LocalizeNodeTests(SimpleTestCase): def test_repr(self): node = LocalizeNode(nodelist=[], use_l10n=True) self.assertEqual(repr(node), '<LocalizeNode>')
744be77e34b87955012e3cb18d82299f88aacabb5a85ddcb4203e50a24c2231e
from unittest import skipUnless from django.db import connection from django.test import TestCase @skipUnless(connection.vendor == 'mysql', 'MySQL tests') class ParsingTests(TestCase): def test_parse_constraint_columns(self): _parse_constraint_columns = connection.introspection._parse_constraint_columns tests = ( ('`height` >= 0', ['height'], ['height']), ('`cost` BETWEEN 1 AND 10', ['cost'], ['cost']), ('`ref1` > `ref2`', ['id', 'ref1', 'ref2'], ['ref1', 'ref2']), ( '`start` IS NULL OR `end` IS NULL OR `start` < `end`', ['id', 'start', 'end'], ['start', 'end'], ), ('JSON_VALID(`json_field`)', ['json_field'], ['json_field']), ('CHAR_LENGTH(`name`) > 2', ['name'], ['name']), ("lower(`ref1`) != 'test'", ['id', 'owe', 'ref1'], ['ref1']), ("lower(`ref1`) != 'test'", ['id', 'lower', 'ref1'], ['ref1']), ("`name` LIKE 'test%'", ['name'], ['name']), ) for check_clause, table_columns, expected_columns in tests: with self.subTest(check_clause): check_columns = _parse_constraint_columns(check_clause, table_columns) self.assertEqual(list(check_columns), expected_columns)
227336d295b72511d0a6b66b4128e23a9da74026f0c7bed086f2720cde4f4eb2
import subprocess 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() def test_clone_test_db_options_ordering(self): creation = DatabaseCreation(connection) try: saved_settings = connection.settings_dict connection.settings_dict = { 'NAME': 'source_db', 'USER': '', 'PASSWORD': '', 'PORT': '', 'HOST': '', 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': 'my.cnf', }, } with mock.patch.object(subprocess, 'Popen') as mocked_popen: creation._clone_db('source_db', 'target_db') mocked_popen.assert_has_calls([ mock.call( [ 'mysqldump', '--defaults-file=my.cnf', '--routines', '--events', 'source_db', ], stdout=subprocess.PIPE, ), ]) finally: connection.settings_dict = saved_settings
a537420943f7085460d851d3e2454d93edb7dbd973fa4c56ec57bb888837de85
import unittest from django.contrib.gis.db.models.functions import ( Area, Distance, Length, Perimeter, Transform, Union, ) from django.contrib.gis.geos import GEOSGeometry, LineString, Point from django.contrib.gis.measure import D # alias for Distance from django.db import NotSupportedError, connection from django.db.models import Exists, F, OuterRef, Q from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from ..utils import ( FuncTestMixin, mysql, no_oracle, oracle, postgis, spatialite, ) from .models import ( AustraliaCity, CensusZipcode, Interstate, SouthTexasCity, SouthTexasCityFt, SouthTexasInterstate, SouthTexasZipcode, ) class DistanceTest(TestCase): fixtures = ['initial'] def setUp(self): # A point we are testing distances with -- using a WGS84 # coordinate that'll be implicitly transformed to that to # the coordinate system of the field, EPSG:32140 (Texas South Central # w/units in meters) self.stx_pnt = GEOSGeometry('POINT (-95.370401017314293 29.704867409475465)', 4326) # Another one for Australia self.au_pnt = GEOSGeometry('POINT (150.791 -34.4919)', 4326) def get_names(self, qs): cities = [c.name for c in qs] cities.sort() return cities def test_init(self): """ Test initialization of distance models. """ self.assertEqual(9, SouthTexasCity.objects.count()) self.assertEqual(9, SouthTexasCityFt.objects.count()) self.assertEqual(11, AustraliaCity.objects.count()) self.assertEqual(4, SouthTexasZipcode.objects.count()) self.assertEqual(4, CensusZipcode.objects.count()) self.assertEqual(1, Interstate.objects.count()) self.assertEqual(1, SouthTexasInterstate.objects.count()) @skipUnlessDBFeature("supports_dwithin_lookup") def test_dwithin(self): """ Test the `dwithin` lookup type. """ # Distances -- all should be equal (except for the # degree/meter pair in au_cities, that's somewhat # approximate). tx_dists = [(7000, 22965.83), D(km=7), D(mi=4.349)] au_dists = [(0.5, 32000), D(km=32), D(mi=19.884)] # Expected cities for Australia and Texas. tx_cities = ['Downtown Houston', 'Southside Place'] au_cities = ['Mittagong', 'Shellharbour', 'Thirroul', 'Wollongong'] # Performing distance queries on two projected coordinate systems one # with units in meters and the other in units of U.S. survey feet. for dist in tx_dists: if isinstance(dist, tuple): dist1, dist2 = dist else: dist1 = dist2 = dist qs1 = SouthTexasCity.objects.filter(point__dwithin=(self.stx_pnt, dist1)) qs2 = SouthTexasCityFt.objects.filter(point__dwithin=(self.stx_pnt, dist2)) for qs in qs1, qs2: with self.subTest(dist=dist, qs=qs): self.assertEqual(tx_cities, self.get_names(qs)) # With a complex geometry expression self.assertFalse(SouthTexasCity.objects.exclude(point__dwithin=(Union('point', 'point'), 0))) # Now performing the `dwithin` queries on a geodetic coordinate system. for dist in au_dists: with self.subTest(dist=dist): type_error = isinstance(dist, D) and not oracle if isinstance(dist, tuple): if oracle or spatialite: # Result in meters dist = dist[1] else: # Result in units of the field dist = dist[0] # Creating the query set. qs = AustraliaCity.objects.order_by('name') if type_error: # A ValueError should be raised on PostGIS when trying to # pass Distance objects into a DWithin query using a # geodetic field. with self.assertRaises(ValueError): AustraliaCity.objects.filter(point__dwithin=(self.au_pnt, dist)).count() else: self.assertEqual(au_cities, self.get_names(qs.filter(point__dwithin=(self.au_pnt, dist)))) @skipUnlessDBFeature("supports_distances_lookups") def test_distance_lookups(self): """ Test the `distance_lt`, `distance_gt`, `distance_lte`, and `distance_gte` lookup types. """ # Retrieving the cities within a 20km 'donut' w/a 7km radius 'hole' # (thus, Houston and Southside place will be excluded as tested in # the `test02_dwithin` above). for model in [SouthTexasCity, SouthTexasCityFt]: stx_pnt = self.stx_pnt.transform(model._meta.get_field('point').srid, clone=True) qs = model.objects.filter(point__distance_gte=(stx_pnt, D(km=7))).filter( point__distance_lte=(stx_pnt, D(km=20)), ) cities = self.get_names(qs) self.assertEqual(cities, ['Bellaire', 'Pearland', 'West University Place']) # Doing a distance query using Polygons instead of a Point. z = SouthTexasZipcode.objects.get(name='77005') qs = SouthTexasZipcode.objects.exclude(name='77005').filter(poly__distance_lte=(z.poly, D(m=275))) self.assertEqual(['77025', '77401'], self.get_names(qs)) # If we add a little more distance 77002 should be included. qs = SouthTexasZipcode.objects.exclude(name='77005').filter(poly__distance_lte=(z.poly, D(m=300))) self.assertEqual(['77002', '77025', '77401'], self.get_names(qs)) @skipUnlessDBFeature("supports_distances_lookups", "supports_distance_geodetic") def test_geodetic_distance_lookups(self): """ Test distance lookups on geodetic coordinate systems. """ # Line is from Canberra to Sydney. Query is for all other cities within # a 100km of that line (which should exclude only Hobart & Adelaide). line = GEOSGeometry('LINESTRING(144.9630 -37.8143,151.2607 -33.8870)', 4326) dist_qs = AustraliaCity.objects.filter(point__distance_lte=(line, D(km=100))) expected_cities = [ 'Batemans Bay', 'Canberra', 'Hillsdale', 'Melbourne', 'Mittagong', 'Shellharbour', 'Sydney', 'Thirroul', 'Wollongong', ] if spatialite: # SpatiaLite is less accurate and returns 102.8km for Batemans Bay. expected_cities.pop(0) self.assertEqual(expected_cities, self.get_names(dist_qs)) msg = "2, 3, or 4-element tuple required for 'distance_lte' lookup." with self.assertRaisesMessage(ValueError, msg): # Too many params. len(AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)', D(km=100), 'spheroid', '4', None))) with self.assertRaisesMessage(ValueError, msg): # Too few params. len(AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)',))) msg = "For 4-element tuples the last argument must be the 'spheroid' directive." with self.assertRaisesMessage(ValueError, msg): len(AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)', D(km=100), 'spheroid', '4'))) # Getting all cities w/in 550 miles of Hobart. hobart = AustraliaCity.objects.get(name='Hobart') qs = AustraliaCity.objects.exclude(name='Hobart').filter(point__distance_lte=(hobart.point, D(mi=550))) cities = self.get_names(qs) self.assertEqual(cities, ['Batemans Bay', 'Canberra', 'Melbourne']) # Cities that are either really close or really far from Wollongong -- # and using different units of distance. wollongong = AustraliaCity.objects.get(name='Wollongong') d1, d2 = D(yd=19500), D(nm=400) # Yards (~17km) & Nautical miles. # Normal geodetic distance lookup (uses `distance_sphere` on PostGIS. gq1 = Q(point__distance_lte=(wollongong.point, d1)) gq2 = Q(point__distance_gte=(wollongong.point, d2)) qs1 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq1 | gq2) # Geodetic distance lookup but telling GeoDjango to use `distance_spheroid` # instead (we should get the same results b/c accuracy variance won't matter # in this test case). querysets = [qs1] if connection.features.has_DistanceSpheroid_function: gq3 = Q(point__distance_lte=(wollongong.point, d1, 'spheroid')) gq4 = Q(point__distance_gte=(wollongong.point, d2, 'spheroid')) qs2 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq3 | gq4) querysets.append(qs2) for qs in querysets: cities = self.get_names(qs) self.assertEqual(cities, ['Adelaide', 'Hobart', 'Shellharbour', 'Thirroul']) @skipUnlessDBFeature("supports_distances_lookups") def test_distance_lookups_with_expression_rhs(self): stx_pnt = self.stx_pnt.transform(SouthTexasCity._meta.get_field('point').srid, clone=True) qs = SouthTexasCity.objects.filter( point__distance_lte=(stx_pnt, F('radius')), ).order_by('name') self.assertEqual( self.get_names(qs), ['Bellaire', 'Downtown Houston', 'Southside Place', 'West University Place'] ) # With a combined expression qs = SouthTexasCity.objects.filter( point__distance_lte=(stx_pnt, F('radius') * 2), ).order_by('name') self.assertEqual(len(qs), 5) self.assertIn('Pearland', self.get_names(qs)) # With spheroid param if connection.features.supports_distance_geodetic: hobart = AustraliaCity.objects.get(name='Hobart') qs = AustraliaCity.objects.filter( point__distance_lte=(hobart.point, F('radius') * 70, 'spheroid'), ).order_by('name') self.assertEqual(self.get_names(qs), ['Canberra', 'Hobart', 'Melbourne']) # With a complex geometry expression self.assertFalse(SouthTexasCity.objects.filter(point__distance_gt=(Union('point', 'point'), 0))) self.assertEqual( SouthTexasCity.objects.filter(point__distance_lte=(Union('point', 'point'), 0)).count(), SouthTexasCity.objects.count(), ) @unittest.skipUnless(mysql, 'This is a MySQL-specific test') def test_mysql_geodetic_distance_error(self): msg = 'Only numeric values of degree units are allowed on geodetic distance queries.' with self.assertRaisesMessage(ValueError, msg): AustraliaCity.objects.filter(point__distance_lte=(Point(0, 0), D(m=100))).exists() @skipUnlessDBFeature('supports_dwithin_lookup') def test_dwithin_subquery(self): """dwithin lookup in a subquery using OuterRef as a parameter.""" qs = CensusZipcode.objects.annotate( annotated_value=Exists(SouthTexasCity.objects.filter( point__dwithin=(OuterRef('poly'), D(m=10)), )) ).filter(annotated_value=True) self.assertEqual(self.get_names(qs), ['77002', '77025', '77401']) @skipUnlessDBFeature('supports_dwithin_lookup', 'supports_dwithin_distance_expr') def test_dwithin_with_expression_rhs(self): # LineString of Wollongong and Adelaide coords. ls = LineString(((150.902, -34.4245), (138.6, -34.9258)), srid=4326) qs = AustraliaCity.objects.filter( point__dwithin=(ls, F('allowed_distance')), ).order_by('name') self.assertEqual( self.get_names(qs), ['Adelaide', 'Mittagong', 'Shellharbour', 'Thirroul', 'Wollongong'], ) @skipIfDBFeature('supports_dwithin_distance_expr') def test_dwithin_with_expression_rhs_not_supported(self): ls = LineString(((150.902, -34.4245), (138.6, -34.9258)), srid=4326) msg = ( 'This backend does not support expressions for specifying ' 'distance in the dwithin lookup.' ) with self.assertRaisesMessage(NotSupportedError, msg): list(AustraliaCity.objects.filter( point__dwithin=(ls, F('allowed_distance')), )) ''' ============================= Distance functions on PostGIS ============================= | Projected Geometry | Lon/lat Geometry | Geography (4326) ST_Distance(geom1, geom2) | OK (meters) | :-( (degrees) | OK (meters) ST_Distance(geom1, geom2, use_spheroid=False) | N/A | N/A | OK (meters), less accurate, quick Distance_Sphere(geom1, geom2) | N/A | OK (meters) | N/A Distance_Spheroid(geom1, geom2, spheroid) | N/A | OK (meters) | N/A ST_Perimeter(geom1) | OK | :-( (degrees) | OK ================================ Distance functions on SpatiaLite ================================ | Projected Geometry | Lon/lat Geometry ST_Distance(geom1, geom2) | OK (meters) | N/A ST_Distance(geom1, geom2, use_ellipsoid=True) | N/A | OK (meters) ST_Distance(geom1, geom2, use_ellipsoid=False) | N/A | OK (meters), less accurate, quick Perimeter(geom1) | OK | :-( (degrees) ''' # NOQA class DistanceFunctionsTests(FuncTestMixin, TestCase): fixtures = ['initial'] @skipUnlessDBFeature("has_Area_function") def test_area(self): # Reference queries: # SELECT ST_Area(poly) FROM distapp_southtexaszipcode; area_sq_m = [5437908.90234375, 10183031.4389648, 11254471.0073242, 9881708.91772461] # Tolerance has to be lower for Oracle tol = 2 for i, z in enumerate(SouthTexasZipcode.objects.annotate(area=Area('poly')).order_by('name')): self.assertAlmostEqual(area_sq_m[i], z.area.sq_m, tol) @skipUnlessDBFeature("has_Distance_function") def test_distance_simple(self): """ Test a simple distance query, with projected coordinates and without transformation. """ lagrange = GEOSGeometry('POINT(805066.295722839 4231496.29461335)', 32140) houston = SouthTexasCity.objects.annotate(dist=Distance('point', lagrange)).order_by('id').first() tol = 2 if oracle else 5 self.assertAlmostEqual( houston.dist.m, 147075.069813, tol ) @skipUnlessDBFeature("has_Distance_function", "has_Transform_function") def test_distance_projected(self): """ Test the `Distance` function on projected coordinate systems. """ # The point for La Grange, TX lagrange = GEOSGeometry('POINT(-96.876369 29.905320)', 4326) # Reference distances in feet and in meters. Got these values from # using the provided raw SQL statements. # SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 32140)) # FROM distapp_southtexascity; m_distances = [147075.069813, 139630.198056, 140888.552826, 138809.684197, 158309.246259, 212183.594374, 70870.188967, 165337.758878, 139196.085105] # SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 2278)) # FROM distapp_southtexascityft; ft_distances = [482528.79154625, 458103.408123001, 462231.860397575, 455411.438904354, 519386.252102563, 696139.009211594, 232513.278304279, 542445.630586414, 456679.155883207] # Testing using different variations of parameters and using models # with different projected coordinate systems. dist1 = SouthTexasCity.objects.annotate(distance=Distance('point', lagrange)).order_by('id') dist2 = SouthTexasCityFt.objects.annotate(distance=Distance('point', lagrange)).order_by('id') dist_qs = [dist1, dist2] # Original query done on PostGIS, have to adjust AlmostEqual tolerance # for Oracle. tol = 2 if oracle else 5 # Ensuring expected distances are returned for each distance queryset. for qs in dist_qs: for i, c in enumerate(qs): with self.subTest(c=c): self.assertAlmostEqual(m_distances[i], c.distance.m, tol) self.assertAlmostEqual(ft_distances[i], c.distance.survey_ft, tol) @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic") def test_distance_geodetic(self): """ Test the `Distance` function on geodetic coordinate systems. """ # Testing geodetic distance calculation with a non-point geometry # (a LineString of Wollongong and Shellharbour coords). ls = LineString(((150.902, -34.4245), (150.87, -34.5789)), srid=4326) # Reference query: # SELECT ST_distance_sphere(point, ST_GeomFromText('LINESTRING(150.9020 -34.4245,150.8700 -34.5789)', 4326)) # FROM distapp_australiacity ORDER BY name; distances = [1120954.92533513, 140575.720018241, 640396.662906304, 60580.9693849269, 972807.955955075, 568451.8357838, 40435.4335201384, 0, 68272.3896586844, 12375.0643697706, 0] qs = AustraliaCity.objects.annotate(distance=Distance('point', ls)).order_by('name') for city, distance in zip(qs, distances): with self.subTest(city=city, distance=distance): # Testing equivalence to within a meter (kilometer on SpatiaLite). tol = -3 if spatialite else 0 self.assertAlmostEqual(distance, city.distance.m, tol) @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic") def test_distance_geodetic_spheroid(self): tol = 2 if oracle else 4 # Got the reference distances using the raw SQL statements: # SELECT ST_distance_spheroid(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326), # 'SPHEROID["WGS 84",6378137.0,298.257223563]') FROM distapp_australiacity WHERE (NOT (id = 11)); # SELECT ST_distance_sphere(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326)) # FROM distapp_australiacity WHERE (NOT (id = 11)); st_distance_sphere spheroid_distances = [ 60504.0628957201, 77023.9489850262, 49154.8867574404, 90847.4358768573, 217402.811919332, 709599.234564757, 640011.483550888, 7772.00667991925, 1047861.78619339, 1165126.55236034, ] sphere_distances = [ 60580.9693849267, 77144.0435286473, 49199.4415344719, 90804.7533823494, 217713.384600405, 709134.127242793, 639828.157159169, 7786.82949717788, 1049204.06569028, 1162623.7238134, ] # Testing with spheroid distances first. hillsdale = AustraliaCity.objects.get(name='Hillsdale') qs = AustraliaCity.objects.exclude(id=hillsdale.id).annotate( distance=Distance('point', hillsdale.point, spheroid=True) ).order_by('id') for i, c in enumerate(qs): with self.subTest(c=c): self.assertAlmostEqual(spheroid_distances[i], c.distance.m, tol) if postgis or spatialite: # PostGIS uses sphere-only distances by default, testing these as well. qs = AustraliaCity.objects.exclude(id=hillsdale.id).annotate( distance=Distance('point', hillsdale.point) ).order_by('id') for i, c in enumerate(qs): with self.subTest(c=c): self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol) @skipIfDBFeature("supports_distance_geodetic") @skipUnlessDBFeature("has_Distance_function") def test_distance_function_raw_result(self): distance = Interstate.objects.annotate( d=Distance(Point(0, 0, srid=4326), Point(0, 1, srid=4326)), ).first().d self.assertEqual(distance, 1) @skipUnlessDBFeature("has_Distance_function") def test_distance_function_d_lookup(self): qs = Interstate.objects.annotate( d=Distance(Point(0, 0, srid=3857), Point(0, 1, srid=3857)), ).filter(d=D(m=1)) self.assertTrue(qs.exists()) @skipIfDBFeature("supports_distance_geodetic") @skipUnlessDBFeature("has_Distance_function") def test_distance_function_raw_result_d_lookup(self): qs = Interstate.objects.annotate( d=Distance(Point(0, 0, srid=4326), Point(0, 1, srid=4326)), ).filter(d=D(m=1)) msg = 'Distance measure is supplied, but units are unknown for result.' with self.assertRaisesMessage(ValueError, msg): list(qs) @no_oracle # Oracle already handles geographic distance calculation. @skipUnlessDBFeature("has_Distance_function", 'has_Transform_function') def test_distance_transform(self): """ Test the `Distance` function used with `Transform` on a geographic field. """ # We'll be using a Polygon (created by buffering the centroid # of 77005 to 100m) -- which aren't allowed in geographic distance # queries normally, however our field has been transformed to # a non-geographic system. z = SouthTexasZipcode.objects.get(name='77005') # Reference query: # SELECT ST_Distance(ST_Transform("distapp_censuszipcode"."poly", 32140), # ST_GeomFromText('<buffer_wkt>', 32140)) # FROM "distapp_censuszipcode"; dists_m = [3553.30384972258, 1243.18391525602, 2186.15439472242] # Having our buffer in the SRID of the transformation and of the field # -- should get the same results. The first buffer has no need for # transformation SQL because it is the same SRID as what was given # to `transform()`. The second buffer will need to be transformed, # however. buf1 = z.poly.centroid.buffer(100) buf2 = buf1.transform(4269, clone=True) ref_zips = ['77002', '77025', '77401'] for buf in [buf1, buf2]: qs = CensusZipcode.objects.exclude(name='77005').annotate( distance=Distance(Transform('poly', 32140), buf) ).order_by('name') self.assertEqual(ref_zips, sorted(c.name for c in qs)) for i, z in enumerate(qs): self.assertAlmostEqual(z.distance.m, dists_m[i], 5) @skipUnlessDBFeature("has_Distance_function") def test_distance_order_by(self): qs = SouthTexasCity.objects.annotate(distance=Distance('point', Point(3, 3, srid=32140))).order_by( 'distance' ).values_list('name', flat=True).filter(name__in=('San Antonio', 'Pearland')) self.assertSequenceEqual(qs, ['San Antonio', 'Pearland']) @skipUnlessDBFeature("has_Length_function") def test_length(self): """ Test the `Length` function. """ # Reference query (should use `length_spheroid`). # SELECT ST_length_spheroid(ST_GeomFromText('<wkt>', 4326) 'SPHEROID["WGS 84",6378137,298.257223563, # AUTHORITY["EPSG","7030"]]'); len_m1 = 473504.769553813 len_m2 = 4617.668 if connection.features.supports_length_geodetic: qs = Interstate.objects.annotate(length=Length('path')) tol = 2 if oracle else 3 self.assertAlmostEqual(len_m1, qs[0].length.m, tol) # TODO: test with spheroid argument (True and False) else: # Does not support geodetic coordinate systems. with self.assertRaises(NotSupportedError): list(Interstate.objects.annotate(length=Length('path'))) # Now doing length on a projected coordinate system. i10 = SouthTexasInterstate.objects.annotate(length=Length('path')).get(name='I-10') self.assertAlmostEqual(len_m2, i10.length.m, 2) self.assertTrue( SouthTexasInterstate.objects.annotate(length=Length('path')).filter(length__gt=4000).exists() ) # Length with an explicit geometry value. qs = Interstate.objects.annotate(length=Length(i10.path)) self.assertAlmostEqual(qs.first().length.m, len_m2, 2) @skipUnlessDBFeature("has_Perimeter_function") def test_perimeter(self): """ Test the `Perimeter` function. """ # Reference query: # SELECT ST_Perimeter(distapp_southtexaszipcode.poly) FROM distapp_southtexaszipcode; perim_m = [18404.3550889361, 15627.2108551001, 20632.5588368978, 17094.5996143697] tol = 2 if oracle else 7 qs = SouthTexasZipcode.objects.annotate(perimeter=Perimeter('poly')).order_by('name') for i, z in enumerate(qs): self.assertAlmostEqual(perim_m[i], z.perimeter.m, tol) # Running on points; should return 0. qs = SouthTexasCity.objects.annotate(perim=Perimeter('point')) for city in qs: self.assertEqual(0, city.perim.m) @skipUnlessDBFeature("has_Perimeter_function") def test_perimeter_geodetic(self): # Currently only Oracle supports calculating the perimeter on geodetic # geometries (without being transformed). qs1 = CensusZipcode.objects.annotate(perim=Perimeter('poly')) if connection.features.supports_perimeter_geodetic: self.assertAlmostEqual(qs1[0].perim.m, 18406.3818954314, 3) else: with self.assertRaises(NotSupportedError): list(qs1) # But should work fine when transformed to projected coordinates qs2 = CensusZipcode.objects.annotate(perim=Perimeter(Transform('poly', 32140))).filter(name='77002') self.assertAlmostEqual(qs2[0].perim.m, 18404.355, 3) @skipUnlessDBFeature("supports_null_geometries", "has_Area_function", "has_Distance_function") def test_measurement_null_fields(self): """ Test the measurement functions on fields with NULL values. """ # Creating SouthTexasZipcode w/NULL value. SouthTexasZipcode.objects.create(name='78212') # Performing distance/area queries against the NULL PolygonField, # and ensuring the result of the operations is None. htown = SouthTexasCity.objects.get(name='Downtown Houston') z = SouthTexasZipcode.objects.annotate( distance=Distance('poly', htown.point), area=Area('poly') ).get(name='78212') self.assertIsNone(z.distance) self.assertIsNone(z.area)
5e509edd6536e85f834a6521750ea6ffabe4b6adfc63d0ce29cc61adddfd0fc8
from django.contrib.gis.db import models from ..utils import gisfield_may_be_null class NamedModel(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True def __str__(self): return self.name class SouthTexasCity(NamedModel): "City model on projected coordinate system for South Texas." point = models.PointField(srid=32140) radius = models.IntegerField(default=10000) class SouthTexasCityFt(NamedModel): "Same City model as above, but U.S. survey feet are the units." point = models.PointField(srid=2278) class AustraliaCity(NamedModel): "City model for Australia, using WGS84." point = models.PointField() radius = models.IntegerField(default=10000) allowed_distance = models.FloatField(default=0.5) class CensusZipcode(NamedModel): "Model for a few South Texas ZIP codes (in original Census NAD83)." poly = models.PolygonField(srid=4269) class SouthTexasZipcode(NamedModel): "Model for a few South Texas ZIP codes." poly = models.PolygonField(srid=32140, null=gisfield_may_be_null) class Interstate(NamedModel): "Geodetic model for U.S. Interstates." path = models.LineStringField() class SouthTexasInterstate(NamedModel): "Projected model for South Texas Interstates." path = models.LineStringField(srid=32140)
585727eaadc73c37b680b7fd11733b0e3b3eebc2e25b2ce37e30c7fd284a0071
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_point_reverse(self): point = GEOSGeometry('POINT(144.963 -37.8143)', 4326) self.assertEqual(point.srid, 4326) point.reverse() self.assertEqual(point.ewkt, 'SRID=4326;POINT (-37.8143 144.963)') 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_linestring_reverse(self): line = GEOSGeometry('LINESTRING(144.963 -37.8143,151.2607 -33.887)', 4326) self.assertEqual(line.srid, 4326) line.reverse() self.assertEqual(line.ewkt, 'SRID=4326;LINESTRING (151.2607 -33.887, 144.963 -37.8143)') 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))
042e85a8fb067cae1cc5abe5b3f1f613d1ef98248eb6e7684f1bb2a392e2b539
from datetime import datetime, timedelta, timezone as datetime_timezone import pytz from django.conf import settings from django.db.models import ( DateField, DateTimeField, F, IntegerField, Max, OuterRef, Subquery, TimeField, ) from django.db.models.functions import ( Extract, ExtractDay, ExtractHour, ExtractIsoWeekDay, ExtractIsoYear, ExtractMinute, ExtractMonth, ExtractQuarter, ExtractSecond, ExtractWeek, ExtractWeekDay, ExtractYear, Trunc, TruncDate, TruncDay, TruncHour, TruncMinute, TruncMonth, TruncQuarter, TruncSecond, TruncTime, TruncWeek, TruncYear, ) from django.test import ( TestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from django.utils import timezone from ..models import Author, DTModel, Fan def truncate_to(value, kind, tzinfo=None): # Convert to target timezone before truncation if tzinfo is not None: value = value.astimezone(tzinfo) def truncate(value, kind): if kind == 'second': return value.replace(microsecond=0) if kind == 'minute': return value.replace(second=0, microsecond=0) if kind == 'hour': return value.replace(minute=0, second=0, microsecond=0) if kind == 'day': if isinstance(value, datetime): return value.replace(hour=0, minute=0, second=0, microsecond=0) return value if kind == 'week': if isinstance(value, datetime): return (value - timedelta(days=value.weekday())).replace(hour=0, minute=0, second=0, microsecond=0) return value - timedelta(days=value.weekday()) if kind == 'month': if isinstance(value, datetime): return value.replace(day=1, hour=0, minute=0, second=0, microsecond=0) return value.replace(day=1) if kind == 'quarter': month_in_quarter = value.month - (value.month - 1) % 3 if isinstance(value, datetime): return value.replace(month=month_in_quarter, day=1, hour=0, minute=0, second=0, microsecond=0) return value.replace(month=month_in_quarter, day=1) # otherwise, truncate to year if isinstance(value, datetime): return value.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0) return value.replace(month=1, day=1) value = truncate(value, kind) if tzinfo is not None: # If there was a daylight saving transition, then reset the timezone. value = timezone.make_aware(value.replace(tzinfo=None), tzinfo) return value @override_settings(USE_TZ=False) class DateFunctionTests(TestCase): def create_model(self, start_datetime, end_datetime): return DTModel.objects.create( name=start_datetime.isoformat() if start_datetime else 'None', start_datetime=start_datetime, end_datetime=end_datetime, start_date=start_datetime.date() if start_datetime else None, end_date=end_datetime.date() if end_datetime else None, start_time=start_datetime.time() if start_datetime else None, end_time=end_datetime.time() if end_datetime else None, duration=(end_datetime - start_datetime) if start_datetime and end_datetime else None, ) def test_extract_year_exact_lookup(self): """ Extract year uses a BETWEEN filter to compare the year to allow indexes to be used. """ start_datetime = datetime(2015, 6, 15, 14, 10) end_datetime = datetime(2016, 6, 15, 14, 10) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for lookup in ('year', 'iso_year'): with self.subTest(lookup): qs = DTModel.objects.filter(**{'start_datetime__%s__exact' % lookup: 2015}) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(' between '), 1) self.assertEqual(query_string.count('extract'), 0) # exact is implied and should be the same qs = DTModel.objects.filter(**{'start_datetime__%s' % lookup: 2015}) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(' between '), 1) self.assertEqual(query_string.count('extract'), 0) # date and datetime fields should behave the same qs = DTModel.objects.filter(**{'start_date__%s' % lookup: 2015}) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(' between '), 1) self.assertEqual(query_string.count('extract'), 0) # an expression rhs cannot use the between optimization. qs = DTModel.objects.annotate( start_year=ExtractYear('start_datetime'), ).filter(end_datetime__year=F('start_year') + 1) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(' between '), 0) self.assertEqual(query_string.count('extract'), 3) def test_extract_year_greaterthan_lookup(self): start_datetime = datetime(2015, 6, 15, 14, 10) end_datetime = datetime(2016, 6, 15, 14, 10) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for lookup in ('year', 'iso_year'): with self.subTest(lookup): qs = DTModel.objects.filter(**{'start_datetime__%s__gt' % lookup: 2015}) self.assertEqual(qs.count(), 1) self.assertEqual(str(qs.query).lower().count('extract'), 0) qs = DTModel.objects.filter(**{'start_datetime__%s__gte' % lookup: 2015}) self.assertEqual(qs.count(), 2) self.assertEqual(str(qs.query).lower().count('extract'), 0) qs = DTModel.objects.annotate( start_year=ExtractYear('start_datetime'), ).filter(**{'end_datetime__%s__gte' % lookup: F('start_year')}) self.assertEqual(qs.count(), 1) self.assertGreaterEqual(str(qs.query).lower().count('extract'), 2) def test_extract_year_lessthan_lookup(self): start_datetime = datetime(2015, 6, 15, 14, 10) end_datetime = datetime(2016, 6, 15, 14, 10) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for lookup in ('year', 'iso_year'): with self.subTest(lookup): qs = DTModel.objects.filter(**{'start_datetime__%s__lt' % lookup: 2016}) self.assertEqual(qs.count(), 1) self.assertEqual(str(qs.query).count('extract'), 0) qs = DTModel.objects.filter(**{'start_datetime__%s__lte' % lookup: 2016}) self.assertEqual(qs.count(), 2) self.assertEqual(str(qs.query).count('extract'), 0) qs = DTModel.objects.annotate( end_year=ExtractYear('end_datetime'), ).filter(**{'start_datetime__%s__lte' % lookup: F('end_year')}) self.assertEqual(qs.count(), 1) self.assertGreaterEqual(str(qs.query).lower().count('extract'), 2) def test_extract_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) with self.assertRaisesMessage(ValueError, 'lookup_name must be provided'): Extract('start_datetime') msg = 'Extract input expression must be DateField, DateTimeField, TimeField, or DurationField.' with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(extracted=Extract('name', 'hour'))) with self.assertRaisesMessage( ValueError, "Cannot extract time component 'second' from DateField 'start_date'."): list(DTModel.objects.annotate(extracted=Extract('start_date', 'second'))) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'year')).order_by('start_datetime'), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'quarter')).order_by('start_datetime'), [(start_datetime, 2), (end_datetime, 2)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'month')).order_by('start_datetime'), [(start_datetime, start_datetime.month), (end_datetime, end_datetime.month)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'day')).order_by('start_datetime'), [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'week')).order_by('start_datetime'), [(start_datetime, 25), (end_datetime, 24)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'week_day')).order_by('start_datetime'), [ (start_datetime, (start_datetime.isoweekday() % 7) + 1), (end_datetime, (end_datetime.isoweekday() % 7) + 1) ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=Extract('start_datetime', 'iso_week_day'), ).order_by('start_datetime'), [ (start_datetime, start_datetime.isoweekday()), (end_datetime, end_datetime.isoweekday()), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'hour')).order_by('start_datetime'), [(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'minute')).order_by('start_datetime'), [(start_datetime, start_datetime.minute), (end_datetime, end_datetime.minute)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'second')).order_by('start_datetime'), [(start_datetime, start_datetime.second), (end_datetime, end_datetime.second)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__year=Extract('start_datetime', 'year')).count(), 2) self.assertEqual(DTModel.objects.filter(start_datetime__hour=Extract('start_datetime', 'hour')).count(), 2) self.assertEqual(DTModel.objects.filter(start_date__month=Extract('start_date', 'month')).count(), 2) self.assertEqual(DTModel.objects.filter(start_time__hour=Extract('start_time', 'hour')).count(), 2) def test_extract_none(self): self.create_model(None, None) for t in (Extract('start_datetime', 'year'), Extract('start_date', 'year'), Extract('start_time', 'hour')): with self.subTest(t): self.assertIsNone(DTModel.objects.annotate(extracted=t).first().extracted) @skipUnlessDBFeature('has_native_duration_field') def test_extract_duration(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('duration', 'second')).order_by('start_datetime'), [ (start_datetime, (end_datetime - start_datetime).seconds % 60), (end_datetime, (start_datetime - end_datetime).seconds % 60) ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual( DTModel.objects.annotate( duration_days=Extract('duration', 'day'), ).filter(duration_days__gt=200).count(), 1 ) @skipIfDBFeature('has_native_duration_field') def test_extract_duration_without_native_duration_field(self): msg = 'Extract requires native DurationField database support.' with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(extracted=Extract('duration', 'second'))) def test_extract_duration_unsupported_lookups(self): msg = "Cannot extract component '%s' from DurationField 'duration'." for lookup in ( 'year', 'iso_year', 'month', 'week', 'week_day', 'iso_week_day', 'quarter', ): with self.subTest(lookup): with self.assertRaisesMessage(ValueError, msg % lookup): DTModel.objects.annotate(extracted=Extract('duration', lookup)) def test_extract_year_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractYear('start_datetime')).order_by('start_datetime'), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractYear('start_date')).order_by('start_datetime'), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__year=ExtractYear('start_datetime')).count(), 2) def test_extract_iso_year_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractIsoYear('start_datetime')).order_by('start_datetime'), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractIsoYear('start_date')).order_by('start_datetime'), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted) ) # Both dates are from the same week year. self.assertEqual(DTModel.objects.filter(start_datetime__iso_year=ExtractIsoYear('start_datetime')).count(), 2) def test_extract_iso_year_func_boundaries(self): end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: end_datetime = timezone.make_aware(end_datetime, is_dst=False) week_52_day_2014 = datetime(2014, 12, 27, 13, 0) # Sunday week_1_day_2014_2015 = datetime(2014, 12, 31, 13, 0) # Wednesday week_53_day_2015 = datetime(2015, 12, 31, 13, 0) # Thursday if settings.USE_TZ: week_1_day_2014_2015 = timezone.make_aware(week_1_day_2014_2015, is_dst=False) week_52_day_2014 = timezone.make_aware(week_52_day_2014, is_dst=False) week_53_day_2015 = timezone.make_aware(week_53_day_2015, is_dst=False) days = [week_52_day_2014, week_1_day_2014_2015, week_53_day_2015] self.create_model(week_53_day_2015, end_datetime) self.create_model(week_52_day_2014, end_datetime) self.create_model(week_1_day_2014_2015, end_datetime) qs = DTModel.objects.filter(start_datetime__in=days).annotate( extracted=ExtractIsoYear('start_datetime'), ).order_by('start_datetime') self.assertQuerysetEqual(qs, [ (week_52_day_2014, 2014), (week_1_day_2014_2015, 2015), (week_53_day_2015, 2015), ], lambda m: (m.start_datetime, m.extracted)) def test_extract_month_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractMonth('start_datetime')).order_by('start_datetime'), [(start_datetime, start_datetime.month), (end_datetime, end_datetime.month)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractMonth('start_date')).order_by('start_datetime'), [(start_datetime, start_datetime.month), (end_datetime, end_datetime.month)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__month=ExtractMonth('start_datetime')).count(), 2) def test_extract_day_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractDay('start_datetime')).order_by('start_datetime'), [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractDay('start_date')).order_by('start_datetime'), [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__day=ExtractDay('start_datetime')).count(), 2) def test_extract_week_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractWeek('start_datetime')).order_by('start_datetime'), [(start_datetime, 25), (end_datetime, 24)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractWeek('start_date')).order_by('start_datetime'), [(start_datetime, 25), (end_datetime, 24)], lambda m: (m.start_datetime, m.extracted) ) # both dates are from the same week. self.assertEqual(DTModel.objects.filter(start_datetime__week=ExtractWeek('start_datetime')).count(), 2) def test_extract_quarter_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 8, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractQuarter('start_datetime')).order_by('start_datetime'), [(start_datetime, 2), (end_datetime, 3)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractQuarter('start_date')).order_by('start_datetime'), [(start_datetime, 2), (end_datetime, 3)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__quarter=ExtractQuarter('start_datetime')).count(), 2) def test_extract_quarter_func_boundaries(self): end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: end_datetime = timezone.make_aware(end_datetime, is_dst=False) last_quarter_2014 = datetime(2014, 12, 31, 13, 0) first_quarter_2015 = datetime(2015, 1, 1, 13, 0) if settings.USE_TZ: last_quarter_2014 = timezone.make_aware(last_quarter_2014, is_dst=False) first_quarter_2015 = timezone.make_aware(first_quarter_2015, is_dst=False) dates = [last_quarter_2014, first_quarter_2015] self.create_model(last_quarter_2014, end_datetime) self.create_model(first_quarter_2015, end_datetime) qs = DTModel.objects.filter(start_datetime__in=dates).annotate( extracted=ExtractQuarter('start_datetime'), ).order_by('start_datetime') self.assertQuerysetEqual(qs, [ (last_quarter_2014, 4), (first_quarter_2015, 1), ], lambda m: (m.start_datetime, m.extracted)) def test_extract_week_func_boundaries(self): end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: end_datetime = timezone.make_aware(end_datetime, is_dst=False) week_52_day_2014 = datetime(2014, 12, 27, 13, 0) # Sunday week_1_day_2014_2015 = datetime(2014, 12, 31, 13, 0) # Wednesday week_53_day_2015 = datetime(2015, 12, 31, 13, 0) # Thursday if settings.USE_TZ: week_1_day_2014_2015 = timezone.make_aware(week_1_day_2014_2015, is_dst=False) week_52_day_2014 = timezone.make_aware(week_52_day_2014, is_dst=False) week_53_day_2015 = timezone.make_aware(week_53_day_2015, is_dst=False) days = [week_52_day_2014, week_1_day_2014_2015, week_53_day_2015] self.create_model(week_53_day_2015, end_datetime) self.create_model(week_52_day_2014, end_datetime) self.create_model(week_1_day_2014_2015, end_datetime) qs = DTModel.objects.filter(start_datetime__in=days).annotate( extracted=ExtractWeek('start_datetime'), ).order_by('start_datetime') self.assertQuerysetEqual(qs, [ (week_52_day_2014, 52), (week_1_day_2014_2015, 1), (week_53_day_2015, 53), ], lambda m: (m.start_datetime, m.extracted)) def test_extract_weekday_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractWeekDay('start_datetime')).order_by('start_datetime'), [ (start_datetime, (start_datetime.isoweekday() % 7) + 1), (end_datetime, (end_datetime.isoweekday() % 7) + 1), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractWeekDay('start_date')).order_by('start_datetime'), [ (start_datetime, (start_datetime.isoweekday() % 7) + 1), (end_datetime, (end_datetime.isoweekday() % 7) + 1), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__week_day=ExtractWeekDay('start_datetime')).count(), 2) def test_extract_iso_weekday_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=ExtractIsoWeekDay('start_datetime'), ).order_by('start_datetime'), [ (start_datetime, start_datetime.isoweekday()), (end_datetime, end_datetime.isoweekday()), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=ExtractIsoWeekDay('start_date'), ).order_by('start_datetime'), [ (start_datetime, start_datetime.isoweekday()), (end_datetime, end_datetime.isoweekday()), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual( DTModel.objects.filter( start_datetime__week_day=ExtractWeekDay('start_datetime'), ).count(), 2, ) def test_extract_hour_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractHour('start_datetime')).order_by('start_datetime'), [(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractHour('start_time')).order_by('start_datetime'), [(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__hour=ExtractHour('start_datetime')).count(), 2) def test_extract_minute_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractMinute('start_datetime')).order_by('start_datetime'), [(start_datetime, start_datetime.minute), (end_datetime, end_datetime.minute)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractMinute('start_time')).order_by('start_datetime'), [(start_datetime, start_datetime.minute), (end_datetime, end_datetime.minute)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__minute=ExtractMinute('start_datetime')).count(), 2) def test_extract_second_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractSecond('start_datetime')).order_by('start_datetime'), [(start_datetime, start_datetime.second), (end_datetime, end_datetime.second)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractSecond('start_time')).order_by('start_datetime'), [(start_datetime, start_datetime.second), (end_datetime, end_datetime.second)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__second=ExtractSecond('start_datetime')).count(), 2) def test_trunc_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) msg = 'output_field must be either DateField, TimeField, or DateTimeField' with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(truncated=Trunc('start_datetime', 'year', output_field=IntegerField()))) with self.assertRaisesMessage(AssertionError, "'name' isn't a DateField, TimeField, or DateTimeField."): list(DTModel.objects.annotate(truncated=Trunc('name', 'year', output_field=DateTimeField()))) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=Trunc('start_date', 'second'))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=Trunc('start_time', 'month'))) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=Trunc('start_date', 'month', output_field=DateTimeField()))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=Trunc('start_time', 'second', output_field=DateTimeField()))) def test_datetime_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc('start_datetime', kind, output_field=DateTimeField()) ).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, kind)), (end_datetime, truncate_to(end_datetime, kind)) ], lambda m: (m.start_datetime, m.truncated) ) def test_date_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc('start_date', kind, output_field=DateField()) ).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.date(), kind)), (end_datetime, truncate_to(end_datetime.date(), kind)) ], lambda m: (m.start_datetime, m.truncated) ) def test_time_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc('start_time', kind, output_field=TimeField()) ).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.time(), kind)), (end_datetime, truncate_to(end_datetime.time(), kind)) ], lambda m: (m.start_datetime, m.truncated) ) test_date_kind('year') test_date_kind('quarter') test_date_kind('month') test_date_kind('week') test_date_kind('day') test_time_kind('hour') test_time_kind('minute') test_time_kind('second') test_datetime_kind('year') test_datetime_kind('quarter') test_datetime_kind('month') test_datetime_kind('week') test_datetime_kind('day') test_datetime_kind('hour') test_datetime_kind('minute') test_datetime_kind('second') qs = DTModel.objects.filter(start_datetime__date=Trunc('start_datetime', 'day', output_field=DateField())) self.assertEqual(qs.count(), 2) def test_trunc_none(self): self.create_model(None, None) for t in (Trunc('start_datetime', 'year'), Trunc('start_date', 'year'), Trunc('start_time', 'hour')): with self.subTest(t): self.assertIsNone(DTModel.objects.annotate(truncated=t).first().truncated) def test_trunc_year_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'year') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncYear('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'year')), (end_datetime, truncate_to(end_datetime, 'year')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncYear('start_date')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.date(), 'year')), (end_datetime, truncate_to(end_datetime.date(), 'year')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime=TruncYear('start_datetime')).count(), 1) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncYear('start_time'))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncYear('start_time', output_field=TimeField()))) def test_trunc_quarter_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 10, 15, 14, 10, 50, 123), 'quarter') last_quarter_2015 = truncate_to(datetime(2015, 12, 31, 14, 10, 50, 123), 'quarter') first_quarter_2016 = truncate_to(datetime(2016, 1, 1, 14, 10, 50, 123), 'quarter') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) last_quarter_2015 = timezone.make_aware(last_quarter_2015, is_dst=False) first_quarter_2016 = timezone.make_aware(first_quarter_2016, is_dst=False) self.create_model(start_datetime=start_datetime, end_datetime=end_datetime) self.create_model(start_datetime=end_datetime, end_datetime=start_datetime) self.create_model(start_datetime=last_quarter_2015, end_datetime=end_datetime) self.create_model(start_datetime=first_quarter_2016, end_datetime=end_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncQuarter('start_date')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.date(), 'quarter')), (last_quarter_2015, truncate_to(last_quarter_2015.date(), 'quarter')), (first_quarter_2016, truncate_to(first_quarter_2016.date(), 'quarter')), (end_datetime, truncate_to(end_datetime.date(), 'quarter')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncQuarter('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'quarter')), (last_quarter_2015, truncate_to(last_quarter_2015, 'quarter')), (first_quarter_2016, truncate_to(first_quarter_2016, 'quarter')), (end_datetime, truncate_to(end_datetime, 'quarter')), ], lambda m: (m.start_datetime, m.extracted) ) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncQuarter('start_time'))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncQuarter('start_time', output_field=TimeField()))) def test_trunc_month_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'month') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncMonth('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'month')), (end_datetime, truncate_to(end_datetime, 'month')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncMonth('start_date')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.date(), 'month')), (end_datetime, truncate_to(end_datetime.date(), 'month')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime=TruncMonth('start_datetime')).count(), 1) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncMonth('start_time'))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncMonth('start_time', output_field=TimeField()))) def test_trunc_week_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'week') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncWeek('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'week')), (end_datetime, truncate_to(end_datetime, 'week')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime=TruncWeek('start_datetime')).count(), 1) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncWeek('start_time'))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncWeek('start_time', output_field=TimeField()))) def test_trunc_date_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncDate('start_datetime')).order_by('start_datetime'), [ (start_datetime, start_datetime.date()), (end_datetime, end_datetime.date()), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__date=TruncDate('start_datetime')).count(), 2) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateField"): list(DTModel.objects.annotate(truncated=TruncDate('start_time'))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateField"): list(DTModel.objects.annotate(truncated=TruncDate('start_time', output_field=TimeField()))) def test_trunc_date_none(self): self.create_model(None, None) self.assertIsNone(DTModel.objects.annotate(truncated=TruncDate('start_datetime')).first().truncated) def test_trunc_time_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncTime('start_datetime')).order_by('start_datetime'), [ (start_datetime, start_datetime.time()), (end_datetime, end_datetime.time()), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__time=TruncTime('start_datetime')).count(), 2) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to TimeField"): list(DTModel.objects.annotate(truncated=TruncTime('start_date'))) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to TimeField"): list(DTModel.objects.annotate(truncated=TruncTime('start_date', output_field=DateField()))) def test_trunc_time_none(self): self.create_model(None, None) self.assertIsNone(DTModel.objects.annotate(truncated=TruncTime('start_datetime')).first().truncated) def test_trunc_day_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'day') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncDay('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'day')), (end_datetime, truncate_to(end_datetime, 'day')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime=TruncDay('start_datetime')).count(), 1) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncDay('start_time'))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncDay('start_time', output_field=TimeField()))) def test_trunc_hour_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'hour') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncHour('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'hour')), (end_datetime, truncate_to(end_datetime, 'hour')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncHour('start_time')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.time(), 'hour')), (end_datetime, truncate_to(end_datetime.time(), 'hour')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime=TruncHour('start_datetime')).count(), 1) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncHour('start_date'))) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncHour('start_date', output_field=DateField()))) def test_trunc_minute_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'minute') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncMinute('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'minute')), (end_datetime, truncate_to(end_datetime, 'minute')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncMinute('start_time')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.time(), 'minute')), (end_datetime, truncate_to(end_datetime.time(), 'minute')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime=TruncMinute('start_datetime')).count(), 1) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncMinute('start_date'))) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncMinute('start_date', output_field=DateField()))) def test_trunc_second_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'second') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncSecond('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'second')), (end_datetime, truncate_to(end_datetime, 'second')) ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncSecond('start_time')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.time(), 'second')), (end_datetime, truncate_to(end_datetime.time(), 'second')) ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime=TruncSecond('start_datetime')).count(), 1) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncSecond('start_date'))) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncSecond('start_date', output_field=DateField()))) def test_trunc_subquery_with_parameters(self): author_1 = Author.objects.create(name='J. R. R. Tolkien') author_2 = Author.objects.create(name='G. R. R. Martin') fan_since_1 = datetime(2016, 2, 3, 15, 0, 0) fan_since_2 = datetime(2015, 2, 3, 15, 0, 0) fan_since_3 = datetime(2017, 2, 3, 15, 0, 0) if settings.USE_TZ: fan_since_1 = timezone.make_aware(fan_since_1, is_dst=False) fan_since_2 = timezone.make_aware(fan_since_2, is_dst=False) fan_since_3 = timezone.make_aware(fan_since_3, is_dst=False) Fan.objects.create(author=author_1, name='Tom', fan_since=fan_since_1) Fan.objects.create(author=author_1, name='Emma', fan_since=fan_since_2) Fan.objects.create(author=author_2, name='Isabella', fan_since=fan_since_3) inner = Fan.objects.filter( author=OuterRef('pk'), name__in=('Emma', 'Isabella', 'Tom') ).values('author').annotate(newest_fan=Max('fan_since')).values('newest_fan') outer = Author.objects.annotate( newest_fan_year=TruncYear(Subquery(inner, output_field=DateTimeField())) ) tz = pytz.UTC if settings.USE_TZ else None self.assertSequenceEqual( outer.order_by('name').values('name', 'newest_fan_year'), [ {'name': 'G. R. R. Martin', 'newest_fan_year': datetime(2017, 1, 1, 0, 0, tzinfo=tz)}, {'name': 'J. R. R. Tolkien', 'newest_fan_year': datetime(2016, 1, 1, 0, 0, tzinfo=tz)}, ] ) @override_settings(USE_TZ=True, TIME_ZONE='UTC') class DateFunctionWithTimeZoneTests(DateFunctionTests): def test_extract_func_with_timezone(self): start_datetime = datetime(2015, 6, 15, 23, 30, 1, 321) end_datetime = datetime(2015, 6, 16, 13, 11, 27, 123) start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) melb = pytz.timezone('Australia/Melbourne') delta_tzinfo_pos = datetime_timezone(timedelta(hours=5)) delta_tzinfo_neg = datetime_timezone(timedelta(hours=-5, minutes=17)) qs = DTModel.objects.annotate( day=Extract('start_datetime', 'day'), day_melb=Extract('start_datetime', 'day', tzinfo=melb), week=Extract('start_datetime', 'week', tzinfo=melb), isoyear=ExtractIsoYear('start_datetime', tzinfo=melb), weekday=ExtractWeekDay('start_datetime'), weekday_melb=ExtractWeekDay('start_datetime', tzinfo=melb), isoweekday=ExtractIsoWeekDay('start_datetime'), isoweekday_melb=ExtractIsoWeekDay('start_datetime', tzinfo=melb), quarter=ExtractQuarter('start_datetime', tzinfo=melb), hour=ExtractHour('start_datetime'), hour_melb=ExtractHour('start_datetime', tzinfo=melb), hour_with_delta_pos=ExtractHour('start_datetime', tzinfo=delta_tzinfo_pos), hour_with_delta_neg=ExtractHour('start_datetime', tzinfo=delta_tzinfo_neg), minute_with_delta_neg=ExtractMinute('start_datetime', tzinfo=delta_tzinfo_neg), ).order_by('start_datetime') utc_model = qs.get() self.assertEqual(utc_model.day, 15) self.assertEqual(utc_model.day_melb, 16) self.assertEqual(utc_model.week, 25) self.assertEqual(utc_model.isoyear, 2015) self.assertEqual(utc_model.weekday, 2) self.assertEqual(utc_model.weekday_melb, 3) self.assertEqual(utc_model.isoweekday, 1) self.assertEqual(utc_model.isoweekday_melb, 2) self.assertEqual(utc_model.quarter, 2) self.assertEqual(utc_model.hour, 23) self.assertEqual(utc_model.hour_melb, 9) self.assertEqual(utc_model.hour_with_delta_pos, 4) self.assertEqual(utc_model.hour_with_delta_neg, 18) self.assertEqual(utc_model.minute_with_delta_neg, 47) with timezone.override(melb): melb_model = qs.get() self.assertEqual(melb_model.day, 16) self.assertEqual(melb_model.day_melb, 16) self.assertEqual(melb_model.week, 25) self.assertEqual(melb_model.isoyear, 2015) self.assertEqual(melb_model.weekday, 3) self.assertEqual(melb_model.isoweekday, 2) self.assertEqual(melb_model.quarter, 2) self.assertEqual(melb_model.weekday_melb, 3) self.assertEqual(melb_model.isoweekday_melb, 2) self.assertEqual(melb_model.hour, 9) self.assertEqual(melb_model.hour_melb, 9) def test_extract_func_explicit_timezone_priority(self): start_datetime = datetime(2015, 6, 15, 23, 30, 1, 321) end_datetime = datetime(2015, 6, 16, 13, 11, 27, 123) start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) melb = pytz.timezone('Australia/Melbourne') with timezone.override(melb): model = DTModel.objects.annotate( day_melb=Extract('start_datetime', 'day'), day_utc=Extract('start_datetime', 'day', tzinfo=timezone.utc), ).order_by('start_datetime').get() self.assertEqual(model.day_melb, 16) self.assertEqual(model.day_utc, 15) def test_trunc_timezone_applied_before_truncation(self): start_datetime = datetime(2016, 1, 1, 1, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) melb = pytz.timezone('Australia/Melbourne') pacific = pytz.timezone('US/Pacific') model = DTModel.objects.annotate( melb_year=TruncYear('start_datetime', tzinfo=melb), pacific_year=TruncYear('start_datetime', tzinfo=pacific), ).order_by('start_datetime').get() self.assertEqual(model.start_datetime, start_datetime) self.assertEqual(model.melb_year, truncate_to(start_datetime, 'year', melb)) self.assertEqual(model.pacific_year, truncate_to(start_datetime, 'year', pacific)) self.assertEqual(model.start_datetime.year, 2016) self.assertEqual(model.melb_year.year, 2016) self.assertEqual(model.pacific_year.year, 2015) def test_trunc_ambiguous_and_invalid_times(self): sao = pytz.timezone('America/Sao_Paulo') utc = pytz.timezone('UTC') start_datetime = utc.localize(datetime(2016, 10, 16, 13)) end_datetime = utc.localize(datetime(2016, 2, 21, 1)) self.create_model(start_datetime, end_datetime) with timezone.override(sao): with self.assertRaisesMessage(pytz.NonExistentTimeError, '2016-10-16 00:00:00'): model = DTModel.objects.annotate(truncated_start=TruncDay('start_datetime')).get() with self.assertRaisesMessage(pytz.AmbiguousTimeError, '2016-02-20 23:00:00'): model = DTModel.objects.annotate(truncated_end=TruncHour('end_datetime')).get() model = DTModel.objects.annotate( truncated_start=TruncDay('start_datetime', is_dst=False), truncated_end=TruncHour('end_datetime', is_dst=False), ).get() self.assertEqual(model.truncated_start.dst(), timedelta(0)) self.assertEqual(model.truncated_end.dst(), timedelta(0)) model = DTModel.objects.annotate( truncated_start=TruncDay('start_datetime', is_dst=True), truncated_end=TruncHour('end_datetime', is_dst=True), ).get() self.assertEqual(model.truncated_start.dst(), timedelta(0, 3600)) self.assertEqual(model.truncated_end.dst(), timedelta(0, 3600)) def test_trunc_func_with_timezone(self): """ If the truncated datetime transitions to a different offset (daylight saving) then the returned value will have that new timezone/offset. """ start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) melb = pytz.timezone('Australia/Melbourne') def test_datetime_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc('start_datetime', kind, output_field=DateTimeField(), tzinfo=melb) ).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.astimezone(melb), kind, melb)), (end_datetime, truncate_to(end_datetime.astimezone(melb), kind, melb)) ], lambda m: (m.start_datetime, m.truncated) ) def test_date_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc('start_date', kind, output_field=DateField(), tzinfo=melb) ).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.date(), kind)), (end_datetime, truncate_to(end_datetime.date(), kind)) ], lambda m: (m.start_datetime, m.truncated) ) def test_time_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc('start_time', kind, output_field=TimeField(), tzinfo=melb) ).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.time(), kind)), (end_datetime, truncate_to(end_datetime.time(), kind)) ], lambda m: (m.start_datetime, m.truncated) ) test_date_kind('year') test_date_kind('quarter') test_date_kind('month') test_date_kind('week') test_date_kind('day') test_time_kind('hour') test_time_kind('minute') test_time_kind('second') test_datetime_kind('year') test_datetime_kind('quarter') test_datetime_kind('month') test_datetime_kind('week') test_datetime_kind('day') test_datetime_kind('hour') test_datetime_kind('minute') test_datetime_kind('second') qs = DTModel.objects.filter(start_datetime__date=Trunc('start_datetime', 'day', output_field=DateField())) self.assertEqual(qs.count(), 2)
aa3526d554884545bfbb615912797cd64b2e0f518b748d3ed988b67f4ba3cb83
import datetime import decimal import unittest from django.db import connection, models from django.db.models import Avg from django.db.models.expressions import Value from django.db.models.functions import Cast from django.test import ( TestCase, ignore_warnings, override_settings, skipUnlessDBFeature, ) from ..models import Author, DTModel, Fan, FloatModel class CastTests(TestCase): @classmethod def setUpTestData(self): Author.objects.create(name='Bob', age=1, alias='1') def test_cast_from_value(self): numbers = Author.objects.annotate(cast_integer=Cast(Value('0'), models.IntegerField())) self.assertEqual(numbers.get().cast_integer, 0) def test_cast_from_field(self): numbers = Author.objects.annotate(cast_string=Cast('age', models.CharField(max_length=255)),) self.assertEqual(numbers.get().cast_string, '1') def test_cast_to_char_field_without_max_length(self): numbers = Author.objects.annotate(cast_string=Cast('age', models.CharField())) self.assertEqual(numbers.get().cast_string, '1') # Silence "Truncated incorrect CHAR(1) value: 'Bob'". @ignore_warnings(module='django.db.backends.mysql.base') @skipUnlessDBFeature('supports_cast_with_precision') def test_cast_to_char_field_with_max_length(self): names = Author.objects.annotate(cast_string=Cast('name', models.CharField(max_length=1))) self.assertEqual(names.get().cast_string, 'B') @skipUnlessDBFeature('supports_cast_with_precision') def test_cast_to_decimal_field(self): FloatModel.objects.create(f1=-1.934, f2=3.467) float_obj = FloatModel.objects.annotate( cast_f1_decimal=Cast('f1', models.DecimalField(max_digits=8, decimal_places=2)), cast_f2_decimal=Cast('f2', models.DecimalField(max_digits=8, decimal_places=1)), ).get() self.assertEqual(float_obj.cast_f1_decimal, decimal.Decimal('-1.93')) self.assertEqual(float_obj.cast_f2_decimal, decimal.Decimal('3.5')) author_obj = Author.objects.annotate( cast_alias_decimal=Cast('alias', models.DecimalField(max_digits=8, decimal_places=2)), ).get() self.assertEqual(author_obj.cast_alias_decimal, decimal.Decimal('1')) def test_cast_to_integer(self): for field_class in ( models.AutoField, models.BigAutoField, models.SmallAutoField, models.IntegerField, models.BigIntegerField, models.SmallIntegerField, models.PositiveIntegerField, models.PositiveSmallIntegerField, ): with self.subTest(field_class=field_class): numbers = Author.objects.annotate(cast_int=Cast('alias', field_class())) self.assertEqual(numbers.get().cast_int, 1) def test_cast_from_db_datetime_to_date(self): dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567) DTModel.objects.create(start_datetime=dt_value) dtm = DTModel.objects.annotate( start_datetime_as_date=Cast('start_datetime', models.DateField()) ).first() self.assertEqual(dtm.start_datetime_as_date, datetime.date(2018, 9, 28)) def test_cast_from_db_datetime_to_time(self): dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567) DTModel.objects.create(start_datetime=dt_value) dtm = DTModel.objects.annotate( start_datetime_as_time=Cast('start_datetime', models.TimeField()) ).first() rounded_ms = int(round(.234567, connection.features.time_cast_precision) * 10**6) self.assertEqual(dtm.start_datetime_as_time, datetime.time(12, 42, 10, rounded_ms)) def test_cast_from_db_date_to_datetime(self): dt_value = datetime.date(2018, 9, 28) DTModel.objects.create(start_date=dt_value) dtm = DTModel.objects.annotate(start_as_datetime=Cast('start_date', models.DateTimeField())).first() self.assertEqual(dtm.start_as_datetime, datetime.datetime(2018, 9, 28, 0, 0, 0, 0)) def test_cast_from_db_datetime_to_date_group_by(self): author = Author.objects.create(name='John Smith', age=45) dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567) Fan.objects.create(name='Margaret', age=50, author=author, fan_since=dt_value) fans = Fan.objects.values('author').annotate( fan_for_day=Cast('fan_since', models.DateField()), fans=models.Count('*') ).values() self.assertEqual(fans[0]['fan_for_day'], datetime.date(2018, 9, 28)) self.assertEqual(fans[0]['fans'], 1) def test_cast_from_python_to_date(self): today = datetime.date.today() dates = Author.objects.annotate(cast_date=Cast(today, models.DateField())) self.assertEqual(dates.get().cast_date, today) def test_cast_from_python_to_datetime(self): now = datetime.datetime.now() dates = Author.objects.annotate(cast_datetime=Cast(now, models.DateTimeField())) time_precision = datetime.timedelta( microseconds=10**(6 - connection.features.time_cast_precision) ) self.assertAlmostEqual(dates.get().cast_datetime, now, delta=time_precision) def test_cast_from_python(self): numbers = Author.objects.annotate(cast_float=Cast(decimal.Decimal(0.125), models.FloatField())) cast_float = numbers.get().cast_float self.assertIsInstance(cast_float, float) self.assertEqual(cast_float, 0.125) @unittest.skipUnless(connection.vendor == 'postgresql', 'PostgreSQL test') @override_settings(DEBUG=True) def test_expression_wrapped_with_parentheses_on_postgresql(self): """ The SQL for the Cast expression is wrapped with parentheses in case it's a complex expression. """ list(Author.objects.annotate(cast_float=Cast(Avg('age'), models.FloatField()))) self.assertIn('(AVG("db_functions_author"."age"))::double precision', connection.queries[-1]['sql']) def test_cast_to_text_field(self): self.assertEqual(Author.objects.values_list(Cast('age', models.TextField()), flat=True).get(), '1')
cbd0a61c84f2552d6391844d6824ba72d72771fd0fdf827ffd482365dbe5855a
import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponsePermanentRedirect from django.middleware.locale import LocaleMiddleware from django.template import Context, Template from django.test import SimpleTestCase, override_settings from django.test.client import RequestFactory from django.test.utils import override_script_prefix from django.urls import clear_url_caches, reverse, translate_url from django.utils import translation class PermanentRedirectLocaleMiddleWare(LocaleMiddleware): response_redirect_class = HttpResponsePermanentRedirect @override_settings( USE_I18N=True, LOCALE_PATHS=[ os.path.join(os.path.dirname(__file__), 'locale'), ], LANGUAGE_CODE='en-us', LANGUAGES=[ ('nl', 'Dutch'), ('en', 'English'), ('pt-br', 'Brazilian Portuguese'), ], MIDDLEWARE=[ 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ], ROOT_URLCONF='i18n.patterns.urls.default', TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.dirname(__file__), 'templates')], 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.i18n', ], }, }], ) class URLTestCaseBase(SimpleTestCase): """ TestCase base-class for the URL tests. """ def setUp(self): # Make sure the cache is empty before we are doing our tests. clear_url_caches() def tearDown(self): # Make sure we will leave an empty cache for other testcases. clear_url_caches() class URLPrefixTests(URLTestCaseBase): """ Tests if the `i18n_patterns` is adding the prefix correctly. """ def test_not_prefixed(self): with translation.override('en'): self.assertEqual(reverse('not-prefixed'), '/not-prefixed/') self.assertEqual(reverse('not-prefixed-included-url'), '/not-prefixed-include/foo/') with translation.override('nl'): self.assertEqual(reverse('not-prefixed'), '/not-prefixed/') self.assertEqual(reverse('not-prefixed-included-url'), '/not-prefixed-include/foo/') def test_prefixed(self): with translation.override('en'): self.assertEqual(reverse('prefixed'), '/en/prefixed/') with translation.override('nl'): self.assertEqual(reverse('prefixed'), '/nl/prefixed/') with translation.override(None): self.assertEqual(reverse('prefixed'), '/%s/prefixed/' % settings.LANGUAGE_CODE) @override_settings(ROOT_URLCONF='i18n.patterns.urls.wrong') def test_invalid_prefix_use(self): msg = 'Using i18n_patterns in an included URLconf is not allowed.' with self.assertRaisesMessage(ImproperlyConfigured, msg): reverse('account:register') @override_settings(ROOT_URLCONF='i18n.patterns.urls.disabled') class URLDisabledTests(URLTestCaseBase): @override_settings(USE_I18N=False) def test_prefixed_i18n_disabled(self): with translation.override('en'): self.assertEqual(reverse('prefixed'), '/prefixed/') with translation.override('nl'): self.assertEqual(reverse('prefixed'), '/prefixed/') class RequestURLConfTests(SimpleTestCase): @override_settings(ROOT_URLCONF='i18n.patterns.urls.path_unused') def test_request_urlconf_considered(self): request = RequestFactory().get('/nl/') request.urlconf = 'i18n.patterns.urls.default' middleware = LocaleMiddleware() with translation.override('nl'): middleware.process_request(request) self.assertEqual(request.LANGUAGE_CODE, 'nl') @override_settings(ROOT_URLCONF='i18n.patterns.urls.path_unused') class PathUnusedTests(URLTestCaseBase): """ If no i18n_patterns is used in root URLconfs, then no language activation activation happens based on url prefix. """ def test_no_lang_activate(self): response = self.client.get('/nl/foo/') self.assertEqual(response.status_code, 200) self.assertEqual(response['content-language'], 'en') self.assertEqual(response.context['LANGUAGE_CODE'], 'en') class URLTranslationTests(URLTestCaseBase): """ Tests if the pattern-strings are translated correctly (within the `i18n_patterns` and the normal `patterns` function). """ def test_no_prefix_translated(self): with translation.override('en'): self.assertEqual(reverse('no-prefix-translated'), '/translated/') self.assertEqual(reverse('no-prefix-translated-slug', kwargs={'slug': 'yeah'}), '/translated/yeah/') with translation.override('nl'): self.assertEqual(reverse('no-prefix-translated'), '/vertaald/') self.assertEqual(reverse('no-prefix-translated-slug', kwargs={'slug': 'yeah'}), '/vertaald/yeah/') with translation.override('pt-br'): self.assertEqual(reverse('no-prefix-translated'), '/traduzidos/') self.assertEqual(reverse('no-prefix-translated-slug', kwargs={'slug': 'yeah'}), '/traduzidos/yeah/') def test_users_url(self): with translation.override('en'): self.assertEqual(reverse('users'), '/en/users/') with translation.override('nl'): self.assertEqual(reverse('users'), '/nl/gebruikers/') self.assertEqual(reverse('prefixed_xml'), '/nl/prefixed.xml') with translation.override('pt-br'): self.assertEqual(reverse('users'), '/pt-br/usuarios/') def test_translate_url_utility(self): with translation.override('en'): self.assertEqual(translate_url('/en/nonexistent/', 'nl'), '/en/nonexistent/') self.assertEqual(translate_url('/en/users/', 'nl'), '/nl/gebruikers/') # Namespaced URL self.assertEqual(translate_url('/en/account/register/', 'nl'), '/nl/profiel/registreren/') # path() URL pattern self.assertEqual(translate_url('/en/account/register-as-path/', 'nl'), '/nl/profiel/registreren-als-pad/') self.assertEqual(translation.get_language(), 'en') # URL with parameters. self.assertEqual( translate_url('/en/with-arguments/regular-argument/', 'nl'), '/nl/with-arguments/regular-argument/', ) self.assertEqual( translate_url('/en/with-arguments/regular-argument/optional.html', 'nl'), '/nl/with-arguments/regular-argument/optional.html', ) with translation.override('nl'): self.assertEqual(translate_url('/nl/gebruikers/', 'en'), '/en/users/') self.assertEqual(translation.get_language(), 'nl') class URLNamespaceTests(URLTestCaseBase): """ Tests if the translations are still working within namespaces. """ def test_account_register(self): with translation.override('en'): self.assertEqual(reverse('account:register'), '/en/account/register/') self.assertEqual(reverse('account:register-as-path'), '/en/account/register-as-path/') with translation.override('nl'): self.assertEqual(reverse('account:register'), '/nl/profiel/registreren/') self.assertEqual(reverse('account:register-as-path'), '/nl/profiel/registreren-als-pad/') class URLRedirectTests(URLTestCaseBase): """ Tests if the user gets redirected to the right URL when there is no language-prefix in the request URL. """ def test_no_prefix_response(self): response = self.client.get('/not-prefixed/') self.assertEqual(response.status_code, 200) def test_en_redirect(self): response = self.client.get('/account/register/', HTTP_ACCEPT_LANGUAGE='en') self.assertRedirects(response, '/en/account/register/') response = self.client.get(response['location']) self.assertEqual(response.status_code, 200) def test_en_redirect_wrong_url(self): response = self.client.get('/profiel/registreren/', HTTP_ACCEPT_LANGUAGE='en') self.assertEqual(response.status_code, 404) def test_nl_redirect(self): response = self.client.get('/profiel/registreren/', HTTP_ACCEPT_LANGUAGE='nl') self.assertRedirects(response, '/nl/profiel/registreren/') response = self.client.get(response['location']) self.assertEqual(response.status_code, 200) def test_nl_redirect_wrong_url(self): response = self.client.get('/account/register/', HTTP_ACCEPT_LANGUAGE='nl') self.assertEqual(response.status_code, 404) def test_pt_br_redirect(self): response = self.client.get('/conta/registre-se/', HTTP_ACCEPT_LANGUAGE='pt-br') self.assertRedirects(response, '/pt-br/conta/registre-se/') response = self.client.get(response['location']) self.assertEqual(response.status_code, 200) def test_pl_pl_redirect(self): # language from outside of the supported LANGUAGES list response = self.client.get('/account/register/', HTTP_ACCEPT_LANGUAGE='pl-pl') self.assertRedirects(response, '/en/account/register/') response = self.client.get(response['location']) self.assertEqual(response.status_code, 200) @override_settings( MIDDLEWARE=[ 'i18n.patterns.tests.PermanentRedirectLocaleMiddleWare', 'django.middleware.common.CommonMiddleware', ], ) def test_custom_redirect_class(self): response = self.client.get('/account/register/', HTTP_ACCEPT_LANGUAGE='en') self.assertRedirects(response, '/en/account/register/', 301) class URLVaryAcceptLanguageTests(URLTestCaseBase): """ 'Accept-Language' is not added to the Vary header when using prefixed URLs. """ def test_no_prefix_response(self): response = self.client.get('/not-prefixed/') self.assertEqual(response.status_code, 200) self.assertEqual(response.get('Vary'), 'Accept-Language') def test_en_redirect(self): response = self.client.get('/account/register/', HTTP_ACCEPT_LANGUAGE='en') self.assertRedirects(response, '/en/account/register/') self.assertFalse(response.get('Vary')) response = self.client.get(response['location']) self.assertEqual(response.status_code, 200) self.assertFalse(response.get('Vary')) class URLRedirectWithoutTrailingSlashTests(URLTestCaseBase): """ Tests the redirect when the requested URL doesn't end with a slash (`settings.APPEND_SLASH=True`). """ def test_not_prefixed_redirect(self): response = self.client.get('/not-prefixed', HTTP_ACCEPT_LANGUAGE='en') self.assertRedirects(response, '/not-prefixed/', 301) def test_en_redirect(self): response = self.client.get('/account/register', HTTP_ACCEPT_LANGUAGE='en', follow=True) # We only want one redirect, bypassing CommonMiddleware self.assertEqual(response.redirect_chain, [('/en/account/register/', 302)]) self.assertRedirects(response, '/en/account/register/', 302) response = self.client.get('/prefixed.xml', HTTP_ACCEPT_LANGUAGE='en', follow=True) self.assertRedirects(response, '/en/prefixed.xml', 302) class URLRedirectWithoutTrailingSlashSettingTests(URLTestCaseBase): """ Tests the redirect when the requested URL doesn't end with a slash (`settings.APPEND_SLASH=False`). """ @override_settings(APPEND_SLASH=False) def test_not_prefixed_redirect(self): response = self.client.get('/not-prefixed', HTTP_ACCEPT_LANGUAGE='en') self.assertEqual(response.status_code, 404) @override_settings(APPEND_SLASH=False) def test_en_redirect(self): response = self.client.get('/account/register-without-slash', HTTP_ACCEPT_LANGUAGE='en') self.assertRedirects(response, '/en/account/register-without-slash', 302) response = self.client.get(response['location']) self.assertEqual(response.status_code, 200) class URLResponseTests(URLTestCaseBase): """Tests if the response has the correct language code.""" def test_not_prefixed_with_prefix(self): response = self.client.get('/en/not-prefixed/') self.assertEqual(response.status_code, 404) def test_en_url(self): response = self.client.get('/en/account/register/') self.assertEqual(response.status_code, 200) self.assertEqual(response['content-language'], 'en') self.assertEqual(response.context['LANGUAGE_CODE'], 'en') def test_nl_url(self): response = self.client.get('/nl/profiel/registreren/') self.assertEqual(response.status_code, 200) self.assertEqual(response['content-language'], 'nl') self.assertEqual(response.context['LANGUAGE_CODE'], 'nl') def test_wrong_en_prefix(self): response = self.client.get('/en/profiel/registreren/') self.assertEqual(response.status_code, 404) def test_wrong_nl_prefix(self): response = self.client.get('/nl/account/register/') self.assertEqual(response.status_code, 404) def test_pt_br_url(self): response = self.client.get('/pt-br/conta/registre-se/') self.assertEqual(response.status_code, 200) self.assertEqual(response['content-language'], 'pt-br') self.assertEqual(response.context['LANGUAGE_CODE'], 'pt-br') def test_en_path(self): response = self.client.get('/en/account/register-as-path/') self.assertEqual(response.status_code, 200) self.assertEqual(response['content-language'], 'en') self.assertEqual(response.context['LANGUAGE_CODE'], 'en') def test_nl_path(self): response = self.client.get('/nl/profiel/registreren-als-pad/') self.assertEqual(response.status_code, 200) self.assertEqual(response['content-language'], 'nl') self.assertEqual(response.context['LANGUAGE_CODE'], 'nl') class URLRedirectWithScriptAliasTests(URLTestCaseBase): """ #21579 - LocaleMiddleware should respect the script prefix. """ def test_language_prefix_with_script_prefix(self): prefix = '/script_prefix' with override_script_prefix(prefix): response = self.client.get('/prefixed/', HTTP_ACCEPT_LANGUAGE='en', SCRIPT_NAME=prefix) self.assertRedirects(response, '%s/en/prefixed/' % prefix, target_status_code=404) class URLTagTests(URLTestCaseBase): """ Test if the language tag works. """ def test_strings_only(self): t = Template("""{% load i18n %} {% language 'nl' %}{% url 'no-prefix-translated' %}{% endlanguage %} {% language 'pt-br' %}{% url 'no-prefix-translated' %}{% endlanguage %}""") self.assertEqual(t.render(Context({})).strip().split(), ['/vertaald/', '/traduzidos/']) def test_context(self): ctx = Context({'lang1': 'nl', 'lang2': 'pt-br'}) tpl = Template("""{% load i18n %} {% language lang1 %}{% url 'no-prefix-translated' %}{% endlanguage %} {% language lang2 %}{% url 'no-prefix-translated' %}{% endlanguage %}""") self.assertEqual(tpl.render(ctx).strip().split(), ['/vertaald/', '/traduzidos/']) def test_args(self): tpl = Template("""{% load i18n %} {% language 'nl' %}{% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %} {% language 'pt-br' %}{% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %}""") self.assertEqual(tpl.render(Context({})).strip().split(), ['/vertaald/apo/', '/traduzidos/apo/']) def test_kwargs(self): tpl = Template("""{% load i18n %} {% language 'nl' %}{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %} {% language 'pt-br' %}{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}""") self.assertEqual(tpl.render(Context({})).strip().split(), ['/vertaald/apo/', '/traduzidos/apo/'])