PageRenderTime 52ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/regressiontests/admin_widgets/tests.py

https://code.google.com/p/mango-py/
Python | 327 lines | 241 code | 64 blank | 22 comment | 6 complexity | 147462aae275009bc59f32a44edd5f29 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. # encoding: utf-8
  2. from datetime import datetime
  3. from django import forms
  4. from django.conf import settings
  5. from django.contrib import admin
  6. from django.contrib.admin import widgets
  7. from django.contrib.admin.widgets import (FilteredSelectMultiple,
  8. AdminSplitDateTime, AdminFileWidget, ForeignKeyRawIdWidget, AdminRadioSelect,
  9. RelatedFieldWidgetWrapper, ManyToManyRawIdWidget)
  10. from django.core.files.storage import default_storage
  11. from django.core.files.uploadedfile import SimpleUploadedFile
  12. from django.db.models import DateField
  13. from django.test import TestCase as DjangoTestCase
  14. from django.utils.html import conditional_escape
  15. from django.utils.translation import activate, deactivate
  16. from django.utils.unittest import TestCase
  17. import models
  18. class AdminFormfieldForDBFieldTests(TestCase):
  19. """
  20. Tests for correct behavior of ModelAdmin.formfield_for_dbfield
  21. """
  22. def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides):
  23. """
  24. Helper to call formfield_for_dbfield for a given model and field name
  25. and verify that the returned formfield is appropriate.
  26. """
  27. # Override any settings on the model admin
  28. class MyModelAdmin(admin.ModelAdmin):
  29. pass
  30. for k in admin_overrides:
  31. setattr(MyModelAdmin, k, admin_overrides[k])
  32. # Construct the admin, and ask it for a formfield
  33. ma = MyModelAdmin(model, admin.site)
  34. ff = ma.formfield_for_dbfield(model._meta.get_field(fieldname), request=None)
  35. # "unwrap" the widget wrapper, if needed
  36. if isinstance(ff.widget, widgets.RelatedFieldWidgetWrapper):
  37. widget = ff.widget.widget
  38. else:
  39. widget = ff.widget
  40. # Check that we got a field of the right type
  41. self.assertTrue(
  42. isinstance(widget, widgetclass),
  43. "Wrong widget for %s.%s: expected %s, got %s" % \
  44. (model.__class__.__name__, fieldname, widgetclass, type(widget))
  45. )
  46. # Return the formfield so that other tests can continue
  47. return ff
  48. def testDateField(self):
  49. self.assertFormfield(models.Event, 'start_date', widgets.AdminDateWidget)
  50. def testDateTimeField(self):
  51. self.assertFormfield(models.Member, 'birthdate', widgets.AdminSplitDateTime)
  52. def testTimeField(self):
  53. self.assertFormfield(models.Event, 'start_time', widgets.AdminTimeWidget)
  54. def testTextField(self):
  55. self.assertFormfield(models.Event, 'description', widgets.AdminTextareaWidget)
  56. def testURLField(self):
  57. self.assertFormfield(models.Event, 'link', widgets.AdminURLFieldWidget)
  58. def testIntegerField(self):
  59. self.assertFormfield(models.Event, 'min_age', widgets.AdminIntegerFieldWidget)
  60. def testCharField(self):
  61. self.assertFormfield(models.Member, 'name', widgets.AdminTextInputWidget)
  62. def testFileField(self):
  63. self.assertFormfield(models.Album, 'cover_art', widgets.AdminFileWidget)
  64. def testForeignKey(self):
  65. self.assertFormfield(models.Event, 'band', forms.Select)
  66. def testRawIDForeignKey(self):
  67. self.assertFormfield(models.Event, 'band', widgets.ForeignKeyRawIdWidget,
  68. raw_id_fields=['band'])
  69. def testRadioFieldsForeignKey(self):
  70. ff = self.assertFormfield(models.Event, 'band', widgets.AdminRadioSelect,
  71. radio_fields={'band':admin.VERTICAL})
  72. self.assertEqual(ff.empty_label, None)
  73. def testManyToMany(self):
  74. self.assertFormfield(models.Band, 'members', forms.SelectMultiple)
  75. def testRawIDManyTOMany(self):
  76. self.assertFormfield(models.Band, 'members', widgets.ManyToManyRawIdWidget,
  77. raw_id_fields=['members'])
  78. def testFilteredManyToMany(self):
  79. self.assertFormfield(models.Band, 'members', widgets.FilteredSelectMultiple,
  80. filter_vertical=['members'])
  81. def testFormfieldOverrides(self):
  82. self.assertFormfield(models.Event, 'start_date', forms.TextInput,
  83. formfield_overrides={DateField: {'widget': forms.TextInput}})
  84. def testFieldWithChoices(self):
  85. self.assertFormfield(models.Member, 'gender', forms.Select)
  86. def testChoicesWithRadioFields(self):
  87. self.assertFormfield(models.Member, 'gender', widgets.AdminRadioSelect,
  88. radio_fields={'gender':admin.VERTICAL})
  89. def testInheritance(self):
  90. self.assertFormfield(models.Album, 'backside_art', widgets.AdminFileWidget)
  91. class AdminFormfieldForDBFieldWithRequestTests(DjangoTestCase):
  92. fixtures = ["admin-widgets-users.xml"]
  93. def testFilterChoicesByRequestUser(self):
  94. """
  95. Ensure the user can only see their own cars in the foreign key dropdown.
  96. """
  97. self.client.login(username="super", password="secret")
  98. response = self.client.get("/widget_admin/admin_widgets/cartire/add/")
  99. self.assertTrue("BMW M3" not in response.content)
  100. self.assertTrue("Volkswagon Passat" in response.content)
  101. class AdminForeignKeyWidgetChangeList(DjangoTestCase):
  102. fixtures = ["admin-widgets-users.xml"]
  103. admin_root = '/widget_admin'
  104. def setUp(self):
  105. self.client.login(username="super", password="secret")
  106. def tearDown(self):
  107. self.client.logout()
  108. def test_changelist_foreignkey(self):
  109. response = self.client.get('%s/admin_widgets/car/' % self.admin_root)
  110. self.assertTrue('%s/auth/user/add/' % self.admin_root in response.content)
  111. class AdminForeignKeyRawIdWidget(DjangoTestCase):
  112. fixtures = ["admin-widgets-users.xml"]
  113. admin_root = '/widget_admin'
  114. def setUp(self):
  115. self.client.login(username="super", password="secret")
  116. def tearDown(self):
  117. self.client.logout()
  118. def test_nonexistent_target_id(self):
  119. band = models.Band.objects.create(name='Bogey Blues')
  120. pk = band.pk
  121. band.delete()
  122. post_data = {
  123. "band": u'%s' % pk,
  124. }
  125. # Try posting with a non-existent pk in a raw id field: this
  126. # should result in an error message, not a server exception.
  127. response = self.client.post('%s/admin_widgets/event/add/' % self.admin_root,
  128. post_data)
  129. self.assertContains(response,
  130. 'Select a valid choice. That choice is not one of the available choices.')
  131. def test_invalid_target_id(self):
  132. for test_str in ('Ińtërnâtiônŕlizćtiřn', "1234'", -1234):
  133. # This should result in an error message, not a server exception.
  134. response = self.client.post('%s/admin_widgets/event/add/' % self.admin_root,
  135. {"band": test_str})
  136. self.assertContains(response,
  137. 'Select a valid choice. That choice is not one of the available choices.')
  138. class FilteredSelectMultipleWidgetTest(TestCase):
  139. def test_render(self):
  140. w = FilteredSelectMultiple('test', False)
  141. self.assertEqual(
  142. conditional_escape(w.render('test', 'test')),
  143. '<select multiple="multiple" name="test" class="selectfilter">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 0, "%(ADMIN_MEDIA_PREFIX)s"); });</script>\n' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX}
  144. )
  145. def test_stacked_render(self):
  146. w = FilteredSelectMultiple('test', True)
  147. self.assertEqual(
  148. conditional_escape(w.render('test', 'test')),
  149. '<select multiple="multiple" name="test" class="selectfilterstacked">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 1, "%(ADMIN_MEDIA_PREFIX)s"); });</script>\n' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX}
  150. )
  151. class AdminSplitDateTimeWidgetTest(TestCase):
  152. def test_render(self):
  153. w = AdminSplitDateTime()
  154. self.assertEqual(
  155. conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))),
  156. '<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>',
  157. )
  158. def test_localization(self):
  159. w = AdminSplitDateTime()
  160. activate('de-at')
  161. old_USE_L10N = settings.USE_L10N
  162. try:
  163. settings.USE_L10N = True
  164. w.is_localized = True
  165. self.assertEqual(
  166. conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))),
  167. '<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>',
  168. )
  169. finally:
  170. deactivate()
  171. settings.USE_L10N = old_USE_L10N
  172. class AdminFileWidgetTest(DjangoTestCase):
  173. def test_render(self):
  174. band = models.Band.objects.create(name='Linkin Park')
  175. album = band.album_set.create(
  176. name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
  177. )
  178. w = AdminFileWidget()
  179. self.assertEqual(
  180. conditional_escape(w.render('test', album.cover_art)),
  181. '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/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('') },
  182. )
  183. self.assertEqual(
  184. conditional_escape(w.render('test', SimpleUploadedFile('test', 'content'))),
  185. '<input type="file" name="test" />',
  186. )
  187. class ForeignKeyRawIdWidgetTest(DjangoTestCase):
  188. def test_render(self):
  189. band = models.Band.objects.create(name='Linkin Park')
  190. band.album_set.create(
  191. name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
  192. )
  193. rel = models.Album._meta.get_field('band').rel
  194. w = ForeignKeyRawIdWidget(rel)
  195. self.assertEqual(
  196. conditional_escape(w.render('test', band.pk, attrs={})),
  197. '<input type="text" name="test" value="%(bandpk)s" class="vForeignKeyRawIdAdminField" /><a href="../../../admin_widgets/band/?t=id" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_MEDIA_PREFIX)simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Linkin Park</strong>' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX, "bandpk": band.pk},
  198. )
  199. def test_relations_to_non_primary_key(self):
  200. # Check that ForeignKeyRawIdWidget works with fields which aren't
  201. # related to the model's primary key.
  202. apple = models.Inventory.objects.create(barcode=86, name='Apple')
  203. models.Inventory.objects.create(barcode=22, name='Pear')
  204. core = models.Inventory.objects.create(
  205. barcode=87, name='Core', parent=apple
  206. )
  207. rel = models.Inventory._meta.get_field('parent').rel
  208. w = ForeignKeyRawIdWidget(rel)
  209. self.assertEqual(
  210. w.render('test', core.parent_id, attrs={}),
  211. '<input type="text" name="test" value="86" class="vForeignKeyRawIdAdminField" /><a href="../../../admin_widgets/inventory/?t=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_MEDIA_PREFIX)simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Apple</strong>' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX},
  212. )
  213. def test_proper_manager_for_label_lookup(self):
  214. # see #9258
  215. rel = models.Inventory._meta.get_field('parent').rel
  216. w = ForeignKeyRawIdWidget(rel)
  217. hidden = models.Inventory.objects.create(
  218. barcode=93, name='Hidden', hidden=True
  219. )
  220. child_of_hidden = models.Inventory.objects.create(
  221. barcode=94, name='Child of hidden', parent=hidden
  222. )
  223. self.assertEqual(
  224. w.render('test', child_of_hidden.parent_id, attrs={}),
  225. '<input type="text" name="test" value="93" class="vForeignKeyRawIdAdminField" /><a href="../../../admin_widgets/inventory/?t=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_MEDIA_PREFIX)simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Hidden</strong>' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX},
  226. )
  227. class ManyToManyRawIdWidgetTest(DjangoTestCase):
  228. def test_render(self):
  229. band = models.Band.objects.create(name='Linkin Park')
  230. band.album_set.create(
  231. name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
  232. )
  233. m1 = models.Member.objects.create(name='Chester')
  234. m2 = models.Member.objects.create(name='Mike')
  235. band.members.add(m1, m2)
  236. rel = models.Band._meta.get_field('members').rel
  237. w = ManyToManyRawIdWidget(rel)
  238. self.assertEqual(
  239. conditional_escape(w.render('test', [m1.pk, m2.pk], attrs={})),
  240. '<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" /><a href="../../../admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_MEDIA_PREFIX)simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX, "m1pk": m1.pk, "m2pk": m2.pk},
  241. )
  242. self.assertEqual(
  243. conditional_escape(w.render('test', [m1.pk])),
  244. '<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField" /><a href="../../../admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_MEDIA_PREFIX)simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX, "m1pk": m1.pk},
  245. )
  246. self.assertEqual(w._has_changed(None, None), False)
  247. self.assertEqual(w._has_changed([], None), False)
  248. self.assertEqual(w._has_changed(None, [u'1']), True)
  249. self.assertEqual(w._has_changed([1, 2], [u'1', u'2']), False)
  250. self.assertEqual(w._has_changed([1, 2], [u'1']), True)
  251. self.assertEqual(w._has_changed([1, 2], [u'1', u'3']), True)
  252. class RelatedFieldWidgetWrapperTests(DjangoTestCase):
  253. def test_no_can_add_related(self):
  254. rel = models.Inventory._meta.get_field('parent').rel
  255. w = AdminRadioSelect()
  256. # Used to fail with a name error.
  257. w = RelatedFieldWidgetWrapper(w, rel, admin.site)
  258. self.assertFalse(w.can_add_related)