test_forms.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  1. import copy
  2. import warnings
  3. from types import SimpleNamespace
  4. from django import forms
  5. from django.contrib.contenttypes.models import ContentType
  6. from django.test import TestCase, override_settings
  7. from django.utils.html import escape
  8. from dcim.models import Rack, Site
  9. from netbox.choices import ImportFormatChoices
  10. from utilities.choices import Choice, ChoiceSet
  11. from utilities.forms.bulk_import import BulkImportForm
  12. from utilities.forms.fields import ChoiceField, MultipleChoiceField, TypedChoiceField
  13. from utilities.forms.fields.csv import CSVSelectWidget
  14. from utilities.forms.fields.dynamic import (
  15. DynamicChoiceField,
  16. DynamicModelChoiceField,
  17. DynamicModelMultipleChoiceField,
  18. DynamicMultipleChoiceField,
  19. )
  20. from utilities.forms.fields.generic import GenericObjectChoiceField
  21. from utilities.forms.forms import BulkRenameForm
  22. from utilities.forms.mixins import GenericObjectFormMixin
  23. from utilities.forms.rendering import FieldSet
  24. from utilities.forms.utils import (
  25. add_blank_choice,
  26. expand_alphanumeric_pattern,
  27. expand_ipnetwork_pattern,
  28. get_capacity_unit_label,
  29. get_field_value,
  30. parse_numeric_range,
  31. )
  32. from utilities.forms.widgets.select import AvailableOptions, HTMXSelect, Select, SelectedOptions
  33. class ExpandIPNetworkTestCase(TestCase):
  34. """
  35. Validate the operation of expand_ipnetwork_pattern().
  36. """
  37. def test_ipv4_range(self):
  38. input = '1.2.3.[9-10]/32'
  39. output = sorted([
  40. '1.2.3.9/32',
  41. '1.2.3.10/32',
  42. ])
  43. self.assertEqual(sorted(expand_ipnetwork_pattern(input, 4)), output)
  44. def test_ipv4_set(self):
  45. input = '1.2.3.[4,44]/32'
  46. output = sorted([
  47. '1.2.3.4/32',
  48. '1.2.3.44/32',
  49. ])
  50. self.assertEqual(sorted(expand_ipnetwork_pattern(input, 4)), output)
  51. def test_ipv4_multiple_ranges(self):
  52. input = '1.[9-10].3.[9-11]/32'
  53. output = sorted([
  54. '1.9.3.9/32',
  55. '1.9.3.10/32',
  56. '1.9.3.11/32',
  57. '1.10.3.9/32',
  58. '1.10.3.10/32',
  59. '1.10.3.11/32',
  60. ])
  61. self.assertEqual(sorted(expand_ipnetwork_pattern(input, 4)), output)
  62. def test_ipv4_multiple_sets(self):
  63. input = '1.[2,22].3.[4,44]/32'
  64. output = sorted([
  65. '1.2.3.4/32',
  66. '1.2.3.44/32',
  67. '1.22.3.4/32',
  68. '1.22.3.44/32',
  69. ])
  70. self.assertEqual(sorted(expand_ipnetwork_pattern(input, 4)), output)
  71. def test_ipv4_set_and_range(self):
  72. input = '1.[2,22].3.[9-11]/32'
  73. output = sorted([
  74. '1.2.3.9/32',
  75. '1.2.3.10/32',
  76. '1.2.3.11/32',
  77. '1.22.3.9/32',
  78. '1.22.3.10/32',
  79. '1.22.3.11/32',
  80. ])
  81. self.assertEqual(sorted(expand_ipnetwork_pattern(input, 4)), output)
  82. def test_ipv6_range(self):
  83. input = 'fec::abcd:[9-b]/64'
  84. output = sorted([
  85. 'fec::abcd:9/64',
  86. 'fec::abcd:a/64',
  87. 'fec::abcd:b/64',
  88. ])
  89. self.assertEqual(sorted(expand_ipnetwork_pattern(input, 6)), output)
  90. def test_ipv6_range_multichar_field(self):
  91. input = 'fec::abcd:[f-11]/64'
  92. output = sorted([
  93. 'fec::abcd:f/64',
  94. 'fec::abcd:10/64',
  95. 'fec::abcd:11/64',
  96. ])
  97. self.assertEqual(sorted(expand_ipnetwork_pattern(input, 6)), output)
  98. def test_ipv6_set(self):
  99. input = 'fec::abcd:[9,ab]/64'
  100. output = sorted([
  101. 'fec::abcd:9/64',
  102. 'fec::abcd:ab/64',
  103. ])
  104. self.assertEqual(sorted(expand_ipnetwork_pattern(input, 6)), output)
  105. def test_ipv6_multiple_ranges(self):
  106. input = 'fec::[1-2]bcd:[9-b]/64'
  107. output = sorted([
  108. 'fec::1bcd:9/64',
  109. 'fec::1bcd:a/64',
  110. 'fec::1bcd:b/64',
  111. 'fec::2bcd:9/64',
  112. 'fec::2bcd:a/64',
  113. 'fec::2bcd:b/64',
  114. ])
  115. self.assertEqual(sorted(expand_ipnetwork_pattern(input, 6)), output)
  116. def test_ipv6_multiple_sets(self):
  117. input = 'fec::[a,f]bcd:[9,ab]/64'
  118. output = sorted([
  119. 'fec::abcd:9/64',
  120. 'fec::abcd:ab/64',
  121. 'fec::fbcd:9/64',
  122. 'fec::fbcd:ab/64',
  123. ])
  124. self.assertEqual(sorted(expand_ipnetwork_pattern(input, 6)), output)
  125. def test_ipv6_set_and_range(self):
  126. input = 'fec::[dead,beaf]:[9-b]/64'
  127. output = sorted([
  128. 'fec::dead:9/64',
  129. 'fec::dead:a/64',
  130. 'fec::dead:b/64',
  131. 'fec::beaf:9/64',
  132. 'fec::beaf:a/64',
  133. 'fec::beaf:b/64',
  134. ])
  135. self.assertEqual(sorted(expand_ipnetwork_pattern(input, 6)), output)
  136. def test_invalid_address_family(self):
  137. with self.assertRaisesRegex(Exception, 'Invalid IP address family: 5'):
  138. sorted(expand_ipnetwork_pattern(None, 5))
  139. def test_invalid_non_pattern(self):
  140. with self.assertRaises(ValueError):
  141. sorted(expand_ipnetwork_pattern('1.2.3.4/32', 4))
  142. def test_invalid_range(self):
  143. with self.assertRaises(ValueError):
  144. sorted(expand_ipnetwork_pattern('1.2.3.[4-]/32', 4))
  145. with self.assertRaises(ValueError):
  146. sorted(expand_ipnetwork_pattern('1.2.3.[-4]/32', 4))
  147. with self.assertRaises(ValueError):
  148. sorted(expand_ipnetwork_pattern('1.2.3.[4--5]/32', 4))
  149. def test_invalid_range_bounds(self):
  150. self.assertEqual(sorted(expand_ipnetwork_pattern('1.2.3.[4-3]/32', 6)), [])
  151. def test_invalid_set(self):
  152. with self.assertRaises(ValueError):
  153. sorted(expand_ipnetwork_pattern('1.2.3.[4]/32', 4))
  154. with self.assertRaises(ValueError):
  155. sorted(expand_ipnetwork_pattern('1.2.3.[4,]/32', 4))
  156. with self.assertRaises(ValueError):
  157. sorted(expand_ipnetwork_pattern('1.2.3.[,4]/32', 4))
  158. with self.assertRaises(ValueError):
  159. sorted(expand_ipnetwork_pattern('1.2.3.[4,,5]/32', 4))
  160. class ExpandAlphanumericTestCase(TestCase):
  161. """
  162. Validate the operation of expand_alphanumeric_pattern().
  163. """
  164. def test_range_numberic(self):
  165. input = 'r[9-11]a'
  166. output = sorted([
  167. 'r9a',
  168. 'r10a',
  169. 'r11a',
  170. ])
  171. self.assertEqual(sorted(expand_alphanumeric_pattern(input)), output)
  172. def test_range_alpha(self):
  173. input = '[r-t]1a'
  174. output = sorted([
  175. 'r1a',
  176. 's1a',
  177. 't1a',
  178. ])
  179. self.assertEqual(sorted(expand_alphanumeric_pattern(input)), output)
  180. def test_set_numeric(self):
  181. input = 'r[1,2]a'
  182. output = sorted([
  183. 'r1a',
  184. 'r2a',
  185. ])
  186. self.assertEqual(sorted(expand_alphanumeric_pattern(input)), output)
  187. def test_set_alpha(self):
  188. input = '[r,t]1a'
  189. output = sorted([
  190. 'r1a',
  191. 't1a',
  192. ])
  193. self.assertEqual(sorted(expand_alphanumeric_pattern(input)), output)
  194. def test_set_multichar(self):
  195. input = '[ra,tb]1a'
  196. output = sorted([
  197. 'ra1a',
  198. 'tb1a',
  199. ])
  200. self.assertEqual(sorted(expand_alphanumeric_pattern(input)), output)
  201. def test_multiple_ranges(self):
  202. input = '[r-t]1[a-b]'
  203. output = sorted([
  204. 'r1a',
  205. 'r1b',
  206. 's1a',
  207. 's1b',
  208. 't1a',
  209. 't1b',
  210. ])
  211. self.assertEqual(sorted(expand_alphanumeric_pattern(input)), output)
  212. def test_multiple_sets(self):
  213. input = '[ra,tb]1[ax,by]'
  214. output = sorted([
  215. 'ra1ax',
  216. 'ra1by',
  217. 'tb1ax',
  218. 'tb1by',
  219. ])
  220. self.assertEqual(sorted(expand_alphanumeric_pattern(input)), output)
  221. def test_set_and_range(self):
  222. input = '[ra,tb]1[a-c]'
  223. output = sorted([
  224. 'ra1a',
  225. 'ra1b',
  226. 'ra1c',
  227. 'tb1a',
  228. 'tb1b',
  229. 'tb1c',
  230. ])
  231. self.assertEqual(sorted(expand_alphanumeric_pattern(input)), output)
  232. def test_invalid_non_pattern(self):
  233. with self.assertRaises(ValueError):
  234. sorted(expand_alphanumeric_pattern('r9a'))
  235. def test_invalid_range(self):
  236. with self.assertRaises(ValueError):
  237. sorted(expand_alphanumeric_pattern('r[8-]a'))
  238. with self.assertRaises(ValueError):
  239. sorted(expand_alphanumeric_pattern('r[-8]a'))
  240. with self.assertRaises(ValueError):
  241. sorted(expand_alphanumeric_pattern('r[8--9]a'))
  242. def test_invalid_range_alphanumeric(self):
  243. self.assertEqual(sorted(expand_alphanumeric_pattern('r[9-a]a')), [])
  244. self.assertEqual(sorted(expand_alphanumeric_pattern('r[a-9]a')), [])
  245. def test_invalid_range_bounds(self):
  246. with self.assertRaises(forms.ValidationError):
  247. sorted(expand_alphanumeric_pattern('r[9-8]a'))
  248. sorted(expand_alphanumeric_pattern('r[b-a]a'))
  249. def test_invalid_range_len(self):
  250. with self.assertRaises(forms.ValidationError):
  251. sorted(expand_alphanumeric_pattern('r[a-bb]a'))
  252. def test_invalid_set(self):
  253. with self.assertRaises(ValueError):
  254. sorted(expand_alphanumeric_pattern('r[a]a'))
  255. with self.assertRaises(ValueError):
  256. sorted(expand_alphanumeric_pattern('r[a,]a'))
  257. with self.assertRaises(ValueError):
  258. sorted(expand_alphanumeric_pattern('r[,a]a'))
  259. with self.assertRaises(ValueError):
  260. sorted(expand_alphanumeric_pattern('r[a,,b]a'))
  261. class ParseNumericRangeTestCase(TestCase):
  262. """
  263. Validate the operation of parse_numeric_range(), in particular its optional min_value/max_value
  264. bounds checking.
  265. """
  266. def test_unbounded(self):
  267. self.assertEqual(parse_numeric_range('0-3,5'), [0, 1, 2, 3, 5])
  268. self.assertEqual(parse_numeric_range('2,8-b,d,f', base=16), [2, 8, 9, 10, 11, 13, 15])
  269. def test_unbounded_reversed_range_yields_nothing(self):
  270. # Without bounds a reversed range expands to an empty list, as it always has. Callers which can't
  271. # tolerate that (e.g. port mappings) pass bounds to get an error instead.
  272. self.assertEqual(parse_numeric_range('9-5'), [])
  273. self.assertEqual(parse_numeric_range('1,9-5'), [1])
  274. def test_bounded_within_range(self):
  275. self.assertEqual(parse_numeric_range('80,443,8000-8002', min_value=1, max_value=65535),
  276. [80, 443, 8000, 8001, 8002])
  277. # The bounds are inclusive at both ends
  278. self.assertEqual(parse_numeric_range('1,65535', min_value=1, max_value=65535), [1, 65535])
  279. self.assertEqual(parse_numeric_range('1-3', min_value=1, max_value=3), [1, 2, 3])
  280. def test_bounded_below_min(self):
  281. with self.assertRaises(forms.ValidationError):
  282. parse_numeric_range('0', min_value=1, max_value=65535)
  283. with self.assertRaises(forms.ValidationError):
  284. parse_numeric_range('0-80', min_value=1, max_value=65535)
  285. def test_bounded_above_max(self):
  286. with self.assertRaises(forms.ValidationError):
  287. parse_numeric_range('70000', min_value=1, max_value=65535)
  288. with self.assertRaises(forms.ValidationError):
  289. parse_numeric_range('80-70000', min_value=1, max_value=65535)
  290. def test_bounded_rejects_before_expanding(self):
  291. # A pathological range must be rejected on its endpoints rather than materialized first
  292. with self.assertRaises(forms.ValidationError):
  293. parse_numeric_range('1-9999999999', min_value=1, max_value=65535)
  294. def test_bounded_reversed_range_raises(self):
  295. # With bounds, a reversed range is an error rather than a silent empty expansion — otherwise it
  296. # would be swallowed when combined with a valid range (e.g. '80,9000-53')
  297. with self.assertRaises(forms.ValidationError):
  298. parse_numeric_range('9000-53', min_value=1, max_value=65535)
  299. with self.assertRaises(forms.ValidationError):
  300. parse_numeric_range('80,9000-53', min_value=1, max_value=65535)
  301. def test_bounded_invalid_value(self):
  302. with self.assertRaises(forms.ValidationError):
  303. parse_numeric_range('80,abc', min_value=1, max_value=65535)
  304. def test_bounds_are_all_or_nothing(self):
  305. # Supplying only one bound would opt into a lower bound while leaving the expansion size uncapped
  306. with self.assertRaises(ValueError):
  307. parse_numeric_range('80', min_value=1)
  308. with self.assertRaises(ValueError):
  309. parse_numeric_range('80', max_value=65535)
  310. class ImportFormTestCase(TestCase):
  311. def test_format_detection(self):
  312. form = BulkImportForm()
  313. data = (
  314. "a,b,c\n"
  315. "1,2,3\n"
  316. "4,5,6\n"
  317. )
  318. self.assertEqual(form._detect_format(data), ImportFormatChoices.CSV)
  319. data = '{"a": 1, "b": 2, "c": 3"}'
  320. self.assertEqual(form._detect_format(data), ImportFormatChoices.JSON)
  321. data = '[{"a": 1, "b": 2, "c": 3"}, {"a": 4, "b": 5, "c": 6"}]'
  322. self.assertEqual(form._detect_format(data), ImportFormatChoices.JSON)
  323. data = (
  324. "- a: 1\n"
  325. " b: 2\n"
  326. " c: 3\n"
  327. "- a: 4\n"
  328. " b: 5\n"
  329. " c: 6\n"
  330. )
  331. self.assertEqual(form._detect_format(data), ImportFormatChoices.YAML)
  332. data = (
  333. "---\n"
  334. "a: 1\n"
  335. "b: 2\n"
  336. "c: 3\n"
  337. "---\n"
  338. "a: 4\n"
  339. "b: 5\n"
  340. "c: 6\n"
  341. )
  342. self.assertEqual(form._detect_format(data), ImportFormatChoices.YAML)
  343. # Invalid data
  344. with self.assertRaises(forms.ValidationError):
  345. form._detect_format('')
  346. with self.assertRaises(forms.ValidationError):
  347. form._detect_format('?')
  348. def test_csv_delimiters(self):
  349. form = BulkImportForm()
  350. data = (
  351. "a,b,c\n"
  352. "1,2,3\n"
  353. "4,5,6\n"
  354. )
  355. self.assertEqual(form._clean_csv(data, delimiter=','), [
  356. {'a': '1', 'b': '2', 'c': '3'},
  357. {'a': '4', 'b': '5', 'c': '6'},
  358. ])
  359. data = (
  360. "a;b;c\n"
  361. "1;2;3\n"
  362. "4;5;6\n"
  363. )
  364. self.assertEqual(form._clean_csv(data, delimiter=';'), [
  365. {'a': '1', 'b': '2', 'c': '3'},
  366. {'a': '4', 'b': '5', 'c': '6'},
  367. ])
  368. data = (
  369. "a\tb\tc\n"
  370. "1\t2\t3\n"
  371. "4\t5\t6\n"
  372. )
  373. self.assertEqual(form._clean_csv(data, delimiter='\t'), [
  374. {'a': '1', 'b': '2', 'c': '3'},
  375. {'a': '4', 'b': '5', 'c': '6'},
  376. ])
  377. class BulkRenameFormTestCase(TestCase):
  378. def test_no_strip_whitespace(self):
  379. # Tests to make sure Bulk Rename Form isn't stripping whitespaces
  380. # See: https://github.com/netbox-community/netbox/issues/13791
  381. form = BulkRenameForm(data={
  382. "find": " hello ",
  383. "replace": " world "
  384. })
  385. self.assertTrue(form.is_valid())
  386. self.assertEqual(form.cleaned_data["find"], " hello ")
  387. self.assertEqual(form.cleaned_data["replace"], " world ")
  388. class GetFieldValueTestCase(TestCase):
  389. @classmethod
  390. def setUpTestData(cls):
  391. class TestForm(forms.Form):
  392. site = forms.ModelChoiceField(
  393. queryset=Site.objects.all(),
  394. required=False
  395. )
  396. cls.form_class = TestForm
  397. cls.sites = (
  398. Site(name='Test Site 1', slug='test-site-1'),
  399. Site(name='Test Site 2', slug='test-site-2'),
  400. )
  401. Site.objects.bulk_create(cls.sites)
  402. def test_unbound_without_initial(self):
  403. form = self.form_class()
  404. self.assertEqual(
  405. get_field_value(form, 'site'),
  406. None
  407. )
  408. def test_unbound_with_initial(self):
  409. form = self.form_class(initial={'site': self.sites[0].pk})
  410. self.assertEqual(
  411. get_field_value(form, 'site'),
  412. self.sites[0].pk
  413. )
  414. def test_bound_value_without_initial(self):
  415. form = self.form_class({'site': self.sites[0].pk})
  416. self.assertEqual(
  417. get_field_value(form, 'site'),
  418. self.sites[0].pk
  419. )
  420. def test_bound_value_with_initial(self):
  421. form = self.form_class({'site': self.sites[0].pk}, initial={'site': self.sites[1].pk})
  422. self.assertEqual(
  423. get_field_value(form, 'site'),
  424. self.sites[0].pk
  425. )
  426. def test_bound_null_without_initial(self):
  427. form = self.form_class({'site': None})
  428. self.assertEqual(
  429. get_field_value(form, 'site'),
  430. None
  431. )
  432. def test_bound_null_with_initial(self):
  433. form = self.form_class({'site': None}, initial={'site': self.sites[1].pk})
  434. self.assertEqual(
  435. get_field_value(form, 'site'),
  436. None
  437. )
  438. class CSVSelectWidgetTestCase(TestCase):
  439. """
  440. Validate that CSVSelectWidget treats blank values as omitted.
  441. This allows model defaults to be applied when CSV fields are present but empty.
  442. Related to issue #20645.
  443. """
  444. def test_blank_value_treated_as_omitted(self):
  445. """Test that blank string values are treated as omitted"""
  446. widget = CSVSelectWidget()
  447. data = {'test_field': ''}
  448. self.assertTrue(widget.value_omitted_from_data(data, {}, 'test_field'))
  449. def test_none_value_treated_as_omitted(self):
  450. """Test that None values are treated as omitted"""
  451. widget = CSVSelectWidget()
  452. data = {'test_field': None}
  453. self.assertTrue(widget.value_omitted_from_data(data, {}, 'test_field'))
  454. def test_missing_field_treated_as_omitted(self):
  455. """Test that missing fields are treated as omitted"""
  456. widget = CSVSelectWidget()
  457. data = {}
  458. self.assertTrue(widget.value_omitted_from_data(data, {}, 'test_field'))
  459. def test_valid_value_not_omitted(self):
  460. """Test that valid values are not treated as omitted"""
  461. widget = CSVSelectWidget()
  462. data = {'test_field': 'valid_value'}
  463. self.assertFalse(widget.value_omitted_from_data(data, {}, 'test_field'))
  464. class SelectMultipleWidgetTestCase(TestCase):
  465. """
  466. Validate filtering behavior of AvailableOptions and SelectedOptions widgets.
  467. """
  468. def test_available_options_flat_choices(self):
  469. """AvailableOptions should exclude selected values from flat choices"""
  470. widget = AvailableOptions(choices=[
  471. (1, 'Option 1'),
  472. (2, 'Option 2'),
  473. (3, 'Option 3'),
  474. ])
  475. widget.optgroups('test', ['2'], None)
  476. self.assertEqual(len(widget.choices), 2)
  477. self.assertEqual(widget.choices[0], (1, 'Option 1'))
  478. self.assertEqual(widget.choices[1], (3, 'Option 3'))
  479. def test_available_options_optgroups(self):
  480. """AvailableOptions should exclude selected values from optgroups"""
  481. widget = AvailableOptions(choices=[
  482. ('Group A', [(1, 'Option 1'), (2, 'Option 2')]),
  483. ('Group B', [(3, 'Option 3'), (4, 'Option 4')]),
  484. ])
  485. # Select options 2 and 3
  486. widget.optgroups('test', ['2', '3'], None)
  487. # Should have 2 groups with filtered choices
  488. self.assertEqual(len(widget.choices), 2)
  489. self.assertEqual(widget.choices[0][0], 'Group A')
  490. self.assertEqual(widget.choices[0][1], [(1, 'Option 1')])
  491. self.assertEqual(widget.choices[1][0], 'Group B')
  492. self.assertEqual(widget.choices[1][1], [(4, 'Option 4')])
  493. def test_selected_options_flat_choices(self):
  494. """SelectedOptions should include only selected values from flat choices"""
  495. widget = SelectedOptions(choices=[
  496. (1, 'Option 1'),
  497. (2, 'Option 2'),
  498. (3, 'Option 3'),
  499. ])
  500. # Select option 2
  501. widget.optgroups('test', ['2'], None)
  502. # Should only have option 2
  503. self.assertEqual(len(widget.choices), 1)
  504. self.assertEqual(widget.choices[0], (2, 'Option 2'))
  505. def test_selected_options_optgroups(self):
  506. """SelectedOptions should include only selected values from optgroups"""
  507. widget = SelectedOptions(choices=[
  508. ('Group A', [(1, 'Option 1'), (2, 'Option 2')]),
  509. ('Group B', [(3, 'Option 3'), (4, 'Option 4')]),
  510. ])
  511. # Select options 2 and 3
  512. widget.optgroups('test', ['2', '3'], None)
  513. # Should have 2 groups with only selected choices
  514. self.assertEqual(len(widget.choices), 2)
  515. self.assertEqual(widget.choices[0][0], 'Group A')
  516. self.assertEqual(widget.choices[0][1], [(2, 'Option 2')])
  517. self.assertEqual(widget.choices[1][0], 'Group B')
  518. self.assertEqual(widget.choices[1][1], [(3, 'Option 3')])
  519. class DynamicChoiceFieldTestCase(TestCase):
  520. """
  521. Validate that DynamicChoiceField.get_bound_field() limits choices to the current
  522. selection and clears them when nothing is selected.
  523. """
  524. CHOICES = [('a', 'Option A'), ('b', 'Option B'), ('c', 'Option C')]
  525. def _make_form(self, data=None):
  526. class TestForm(forms.Form):
  527. field = DynamicChoiceField(choices=self.CHOICES, required=False)
  528. return TestForm(data=data)
  529. def test_unbound_clears_choices(self):
  530. form = self._make_form()
  531. form.fields['field'].get_bound_field(form, 'field')
  532. self.assertEqual(form.fields['field'].choices, [])
  533. def test_bound_with_value_filters_to_selection(self):
  534. form = self._make_form(data={'field': 'b'})
  535. form.fields['field'].get_bound_field(form, 'field')
  536. self.assertEqual(form.fields['field'].choices, [('b', 'Option B')])
  537. def test_bound_with_no_value_clears_choices(self):
  538. form = self._make_form(data={})
  539. form.fields['field'].get_bound_field(form, 'field')
  540. self.assertEqual(form.fields['field'].choices, [])
  541. class DynamicMultipleChoiceFieldTestCase(TestCase):
  542. """
  543. Validate that DynamicMultipleChoiceField.get_bound_field() limits choices to
  544. the current selection and clears them when nothing is selected.
  545. """
  546. CHOICES = [('a', 'Option A'), ('b', 'Option B'), ('c', 'Option C')]
  547. def _make_form(self, data=None):
  548. class TestForm(forms.Form):
  549. field = DynamicMultipleChoiceField(choices=self.CHOICES, required=False)
  550. return TestForm(data=data)
  551. def test_unbound_clears_choices(self):
  552. """Regression test for #22328: unbound form must not retain the full choices list."""
  553. form = self._make_form()
  554. form.fields['field'].get_bound_field(form, 'field')
  555. self.assertEqual(form.fields['field'].choices, [])
  556. def test_bound_with_values_filters_to_selection(self):
  557. form = self._make_form(data={'field': ['a', 'c']})
  558. form.fields['field'].get_bound_field(form, 'field')
  559. self.assertEqual(form.fields['field'].choices, [('a', 'Option A'), ('c', 'Option C')])
  560. def test_bound_with_no_values_clears_choices(self):
  561. form = self._make_form(data={})
  562. form.fields['field'].get_bound_field(form, 'field')
  563. self.assertEqual(form.fields['field'].choices, [])
  564. class DynamicModelChoiceFieldTestCase(TestCase):
  565. """Validate how dynamic model choice fields seed their initial value and render their options."""
  566. @classmethod
  567. def setUpTestData(cls):
  568. # The quote in Site 2's name proves that a rendered parent name is escaped
  569. cls.sites = (
  570. Site(name='Site 1', slug='site-1'),
  571. Site(name='Site "2"', slug='site-2'),
  572. )
  573. Site.objects.bulk_create(cls.sites)
  574. # Rack 2 and Rack 3 share Site 2, so the reverse lookup returns it twice
  575. cls.racks = (
  576. Rack(name='Rack 1', site=cls.sites[0]),
  577. Rack(name='Rack 2', site=cls.sites[1]),
  578. Rack(name='Rack 3', site=cls.sites[1]),
  579. )
  580. Rack.objects.bulk_create(cls.racks)
  581. def _make_form(self, site_field_class, data=None, rack_context=None):
  582. class TestForm(forms.Form):
  583. rack = DynamicModelMultipleChoiceField(queryset=Rack.objects.all(), required=False, context=rack_context)
  584. site = site_field_class(
  585. queryset=Site.objects.all(),
  586. required=False,
  587. initial_params={'racks__in': '$rack'},
  588. )
  589. return TestForm(data=data, initial={'rack': [rack.pk for rack in self.racks]})
  590. def test_multiple_choice_field_selects_every_matching_object(self):
  591. """A multiple-choice parent field selects every distinct object matched by initial_params."""
  592. field = self._make_form(DynamicModelMultipleChoiceField)['site'].field
  593. self.assertCountEqual([site.pk for site in field.queryset], [site.pk for site in self.sites])
  594. # The queryset filter deduplicates, so only initial reveals a repeated parent
  595. self.assertCountEqual(field.initial, self.sites)
  596. def test_multiple_choice_field_supports_changed_data(self):
  597. """An unchanged submission of a multiple-choice parent field is absent from changed_data."""
  598. data = {
  599. 'rack': [rack.pk for rack in self.racks],
  600. 'site': [site.pk for site in self.sites],
  601. }
  602. form = self._make_form(DynamicModelMultipleChoiceField, data=data)
  603. self.assertEqual(form.changed_data, [])
  604. def test_single_choice_field_selects_one_matching_object(self):
  605. """A single-choice parent field still selects one object matched by initial_params."""
  606. field = self._make_form(DynamicModelChoiceField)['site'].field
  607. self.assertIn(field.initial, self.sites)
  608. self.assertEqual(field.queryset.count(), 1)
  609. def test_options_name_their_parent(self):
  610. """Each rendered option names its parent object."""
  611. html = str(self._make_form(DynamicModelMultipleChoiceField, rack_context={'parent': 'site'})['rack'])
  612. for rack in self.racks:
  613. self.assertInHTML(
  614. f'<option value="{rack.pk}" data-parent="{escape(rack.site)}" selected>{rack}</option>', html
  615. )
  616. def test_options_omit_a_missing_parent(self):
  617. """Options carry no parent when the context names an unset relation or no model attribute."""
  618. unset_parent = self._make_form(DynamicModelMultipleChoiceField, rack_context={'parent': 'location'})
  619. unknown_parent = self._make_form(DynamicModelMultipleChoiceField, rack_context={'parent': 'region'})
  620. self.assertNotIn('data-parent', str(unset_parent['rack']))
  621. self.assertNotIn('data-parent', str(unknown_parent['rack']))
  622. class GenericObjectChoiceFieldTestCase(TestCase):
  623. """Validate generic foreign key object selection via a content type plus an API-backed object selector."""
  624. @classmethod
  625. def setUpTestData(cls):
  626. cls.site = Site.objects.create(name='Test Site 1', slug='test-site-1')
  627. cls.site_type = ContentType.objects.get_for_model(Site)
  628. cls.invalid_type = ContentType.objects.get_for_model(ContentType)
  629. def _make_form(self, data=None, initial=None, required=False):
  630. site_type = self.site_type
  631. class TestForm(forms.Form):
  632. obj = GenericObjectChoiceField(
  633. content_type_queryset=ContentType.objects.filter(pk=site_type.pk),
  634. required=required,
  635. selector=True,
  636. )
  637. return TestForm(data=data, initial=initial)
  638. def test_valid_value_returns_selected_object(self):
  639. form = self._make_form(
  640. data={'obj_content_type': str(self.site_type.pk), 'obj_object_id': str(self.site.pk)},
  641. required=True,
  642. )
  643. self.assertTrue(form.is_valid(), form.errors)
  644. self.assertEqual(form.cleaned_data['obj'], self.site)
  645. def test_optional_empty_value_returns_none(self):
  646. form = self._make_form(data={'obj_content_type': '', 'obj_object_id': ''})
  647. self.assertTrue(form.is_valid(), form.errors)
  648. self.assertIsNone(form.cleaned_data['obj'])
  649. def test_required_empty_value_is_invalid(self):
  650. form = self._make_form(data={'obj_content_type': '', 'obj_object_id': ''}, required=True)
  651. self.assertFalse(form.is_valid())
  652. self.assertIn('obj', form.errors)
  653. def test_incomplete_value_is_invalid(self):
  654. for data in (
  655. {'obj_content_type': str(self.site_type.pk), 'obj_object_id': ''},
  656. {'obj_content_type': '', 'obj_object_id': str(self.site.pk)},
  657. ):
  658. form = self._make_form(data=data)
  659. self.assertFalse(form.is_valid())
  660. self.assertIn('obj', form.errors)
  661. def test_invalid_content_type_is_rejected(self):
  662. form = self._make_form(
  663. data={'obj_content_type': str(self.invalid_type.pk), 'obj_object_id': str(self.site.pk)}
  664. )
  665. self.assertFalse(form.is_valid())
  666. self.assertIn('obj', form.errors)
  667. def test_invalid_object_id_is_rejected(self):
  668. form = self._make_form(
  669. data={'obj_content_type': str(self.site_type.pk), 'obj_object_id': str(self.site.pk + 1000)}
  670. )
  671. self.assertFalse(form.is_valid())
  672. self.assertIn('obj', form.errors)
  673. def test_initial_object_configures_object_selector(self):
  674. form = self._make_form(initial={'obj': self.site})
  675. field = form.fields['obj']
  676. bound_field = field.get_bound_field(form, 'obj')
  677. self.assertEqual(field.selected_model, Site)
  678. self.assertEqual(list(field.object_field.queryset), [self.site])
  679. self.assertEqual(field.object_field.widget.attrs['selector'], Site._meta.label_lower)
  680. self.assertIn('data-url', field.object_field.widget.attrs)
  681. self.assertIn('obj_content_type', str(bound_field))
  682. self.assertIn('obj_object_id', str(bound_field))
  683. def test_unbound_htmx_rerender_preserves_selection(self):
  684. # Simulates an HTMX content-type change: the view passes the submitted subwidget values
  685. # via `initial` (form is unbound). The object selector must reconfigure for the new type.
  686. form = self._make_form(initial={
  687. 'obj_content_type': str(self.site_type.pk),
  688. 'obj_object_id': str(self.site.pk),
  689. })
  690. field = form.fields['obj']
  691. field.get_bound_field(form, 'obj')
  692. self.assertEqual(field.selected_model, Site)
  693. self.assertIn('data-url', field.object_field.widget.attrs)
  694. self.assertEqual(field.initial, [str(self.site_type.pk), str(self.site.pk)])
  695. def test_initial_content_type_is_selected_on_render(self):
  696. # The content-type subwidget must render its options and mark the current type selected on edit forms.
  697. form = self._make_form(initial={'obj': self.site})
  698. content_type_html = str(form['obj']).split('name="obj_object_id"')[0]
  699. self.assertRegex(content_type_html, rf'value="{self.site_type.pk}"\s+selected')
  700. def test_queryset_property_proxies_object_field(self):
  701. """The top-level queryset proxy reads and writes the nested object field's queryset."""
  702. form = self._make_form()
  703. field = form.fields['obj']
  704. self.assertIs(field.queryset, field.object_field.queryset)
  705. field.queryset = Site.objects.all()
  706. self.assertIs(field.object_field.queryset, field.queryset)
  707. self.assertEqual(list(field.queryset), list(Site.objects.all()))
  708. def test_queryset_setter_syncs_rendered_subwidget(self):
  709. """Assigning queryset (as restrict_form_fields does, pre-render) populates the rendered subwidget."""
  710. form = self._make_form()
  711. field = form.fields['obj']
  712. field.queryset = Site.objects.all()
  713. self.assertIs(field.object_field.widget, field.widget.widgets[1])
  714. rendered_values = [getattr(value, 'value', value) for value, label in field.object_field.widget.choices]
  715. self.assertIn(self.site.pk, rendered_values)
  716. def test_restricted_queryset_rejects_unviewable_object(self):
  717. """An object outside the restricted queryset is rejected, mirroring restrict_form_fields()."""
  718. form = self._make_form(
  719. data={'obj_content_type': str(self.site_type.pk), 'obj_object_id': str(self.site.pk)},
  720. required=True,
  721. )
  722. # restrict_form_fields() narrows the nested queryset via the top-level proxy before validation.
  723. form.fields['obj'].queryset = Site.objects.exclude(pk=self.site.pk)
  724. self.assertFalse(form.is_valid())
  725. self.assertIn('obj', form.errors)
  726. def test_restricted_queryset_allows_viewable_object(self):
  727. """An object within the restricted queryset still validates."""
  728. form = self._make_form(
  729. data={'obj_content_type': str(self.site_type.pk), 'obj_object_id': str(self.site.pk)},
  730. required=True,
  731. )
  732. form.fields['obj'].queryset = Site.objects.all()
  733. self.assertTrue(form.is_valid(), form.errors)
  734. self.assertEqual(form.cleaned_data['obj'], self.site)
  735. def test_incomplete_value_names_selected_type(self):
  736. """When a type is chosen but no object, the error names the selected type."""
  737. form = self._make_form(
  738. data={'obj_content_type': str(self.site_type.pk), 'obj_object_id': ''},
  739. )
  740. self.assertFalse(form.is_valid())
  741. self.assertIn('Please select a site.', form.errors['obj'])
  742. def test_content_type_change_clears_stale_object_id(self):
  743. """The content-type selector clears its paired object_id client-side on change (stale-PK guard)."""
  744. form = self._make_form(initial={'obj': self.site})
  745. field = form.fields['obj']
  746. field.get_bound_field(form, 'obj')
  747. attrs = field.content_type_field.widget.attrs
  748. self.assertEqual(attrs.get('data-htmx-clear-param'), 'obj_object_id')
  749. # The clearing is done by a listener in the static bundle, not by htmx runtime eval.
  750. self.assertNotIn('hx-on::config-request', attrs)
  751. def test_content_type_lookup_is_cached(self):
  752. """Repeated content-type resolution hits the database only once per field instance."""
  753. field = self._make_form().fields['obj']
  754. with self.assertNumQueries(1):
  755. first = field._get_content_type(str(self.site_type.pk))
  756. second = field._get_content_type(str(self.site_type.pk))
  757. self.assertEqual(first, self.site_type)
  758. self.assertEqual(second, self.site_type)
  759. def test_content_type_outside_queryset_returns_none(self):
  760. """A content type outside the allowed queryset still resolves to None (constraint preserved)."""
  761. field = self._make_form().fields['obj']
  762. self.assertIsNone(field._get_content_type(str(self.invalid_type.pk)))
  763. def test_compress_is_not_implemented(self):
  764. """compress() is intentionally unreachable and raises to signal clean() owns the conversion."""
  765. field = self._make_form().fields['obj']
  766. with self.assertRaises(NotImplementedError):
  767. field.compress([self.site_type, self.site])
  768. class GenericObjectFormMixinTestCase(TestCase):
  769. """Validate the DEBUG warning emitted when an HTMX target has no matching FieldSet."""
  770. @classmethod
  771. def setUpTestData(cls):
  772. cls.site = Site.objects.create(name='Mixin Test Site', slug='mixin-test-site')
  773. cls.site_type = ContentType.objects.get_for_model(Site)
  774. def _field(self):
  775. return GenericObjectChoiceField(
  776. content_type_queryset=ContentType.objects.filter(pk=self.site_type.pk),
  777. required=False,
  778. hx_target_id='scope',
  779. )
  780. @override_settings(DEBUG=True)
  781. def test_missing_htmx_fieldset_warns(self):
  782. field = self._field()
  783. class MissingFieldsetForm(GenericObjectFormMixin, forms.Form):
  784. obj = field
  785. with self.assertWarns(UserWarning):
  786. MissingFieldsetForm()
  787. @override_settings(DEBUG=True)
  788. def test_present_htmx_fieldset_does_not_warn(self):
  789. field = self._field()
  790. class PresentFieldsetForm(GenericObjectFormMixin, forms.Form):
  791. obj = field
  792. fieldsets = (FieldSet('obj', name='Scope', html_id='scope'),)
  793. with warnings.catch_warnings(record=True) as caught:
  794. warnings.simplefilter('always')
  795. PresentFieldsetForm()
  796. self.assertEqual([w for w in caught if 'html_id' in str(w.message)], [])
  797. def test_gfk_name_routes_assignment(self):
  798. """When gfk_name differs from the field name, the cleaned object is assigned to that attribute."""
  799. site_type = self.site_type
  800. class TargetForm(GenericObjectFormMixin, forms.Form):
  801. target = GenericObjectChoiceField(
  802. content_type_queryset=ContentType.objects.filter(pk=site_type.pk),
  803. required=False,
  804. gfk_name='assigned_object',
  805. )
  806. form = TargetForm(data={'target_content_type': str(site_type.pk), 'target_object_id': str(self.site.pk)})
  807. form.instance = SimpleNamespace()
  808. self.assertTrue(form.is_valid(), form.errors)
  809. self.assertEqual(form.instance.assigned_object, self.site)
  810. class GetCapacityUnitLabelTestCase(TestCase):
  811. """
  812. Test the get_capacity_unit_label function for correct base unit label.
  813. """
  814. def test_si_label(self):
  815. self.assertEqual(get_capacity_unit_label(1000), 'MB')
  816. def test_iec_label(self):
  817. self.assertEqual(get_capacity_unit_label(1024), 'MiB')
  818. class FieldSetTestCase(TestCase):
  819. def test_html_id_defaults_to_none(self):
  820. fs = FieldSet('field1', 'field2', name='Test')
  821. self.assertIsNone(fs.html_id)
  822. def test_html_id_stored(self):
  823. fs = FieldSet('field1', 'field2', name='Test', html_id='my-fieldset')
  824. self.assertEqual(fs.html_id, 'my-fieldset')
  825. @override_settings(DEBUG=True)
  826. def test_html_id_invalid_css_identifier_raises(self):
  827. with self.assertRaises(ValueError):
  828. FieldSet('field1', html_id='123-bad')
  829. @override_settings(DEBUG=False)
  830. def test_html_id_invalid_css_identifier_ignored_outside_debug(self):
  831. fs = FieldSet('field1', html_id='123-bad')
  832. self.assertEqual(fs.html_id, '123-bad')
  833. class HTMXSelectTestCase(TestCase):
  834. def test_default_targets_form_fields(self):
  835. widget = HTMXSelect()
  836. self.assertEqual(widget.attrs['hx-target'], '#form_fields')
  837. self.assertEqual(widget.attrs['hx-include'], '#form_fields')
  838. self.assertNotIn('hx-select', widget.attrs)
  839. self.assertNotIn('hx-swap', widget.attrs)
  840. def test_hx_target_id_sets_target_select_and_swap(self):
  841. widget = HTMXSelect(hx_target_id='my-fieldset')
  842. self.assertEqual(widget.attrs['hx-target'], '#my-fieldset')
  843. self.assertEqual(widget.attrs['hx-select'], '#my-fieldset')
  844. self.assertEqual(widget.attrs['hx-swap'], 'outerHTML')
  845. def test_hx_target_id_include_stays_on_form_fields(self):
  846. widget = HTMXSelect(hx_target_id='my-fieldset')
  847. self.assertEqual(widget.attrs['hx-include'], '#form_fields')
  848. class StaticSelectTestCase(TestCase):
  849. """
  850. Validate the rendering of option descriptions and images in static select fields.
  851. """
  852. class ExampleChoices(ChoiceSet):
  853. FOO = 'foo'
  854. BAR = 'bar'
  855. CHOICES = (
  856. Choice(FOO, 'Foo', description='Description of foo', image='foo.svg'),
  857. Choice(BAR, 'Bar'),
  858. )
  859. def test_choiceset_populates_widget(self):
  860. for field_class in (ChoiceField, MultipleChoiceField, TypedChoiceField):
  861. with self.subTest(field_class=field_class.__name__):
  862. field = field_class(choices=self.ExampleChoices)
  863. self.assertEqual(field.widget.descriptions, {self.ExampleChoices.FOO: 'Description of foo'})
  864. self.assertEqual(field.widget.images, {self.ExampleChoices.FOO: 'foo.svg'})
  865. def test_show_descriptions_false_suppresses_descriptions(self):
  866. field = ChoiceField(choices=self.ExampleChoices, show_descriptions=False)
  867. self.assertEqual(field.widget.descriptions, {})
  868. def test_add_blank_choice_preserves_attrs(self):
  869. field = ChoiceField(choices=add_blank_choice(self.ExampleChoices))
  870. self.assertEqual(field.widget.descriptions, {self.ExampleChoices.FOO: 'Description of foo'})
  871. self.assertEqual(field.widget.images, {self.ExampleChoices.FOO: 'foo.svg'})
  872. @override_settings(STATIC_URL='/static/')
  873. def test_data_attrs_rendered_on_option(self):
  874. field = ChoiceField(choices=self.ExampleChoices)
  875. html = field.widget.render('test', None)
  876. self.assertInHTML(
  877. '<option value="foo" data-description="Description of foo" data-image="/static/foo.svg">Foo</option>',
  878. html
  879. )
  880. # Options without a description or image should not receive the attributes
  881. self.assertInHTML('<option value="bar">Bar</option>', html)
  882. def test_choiceset_without_attrs(self):
  883. class NoAttrs(ChoiceSet):
  884. CHOICES = (('a', 'A'),)
  885. field = ChoiceField(choices=NoAttrs)
  886. self.assertEqual(field.widget.descriptions, {})
  887. self.assertEqual(field.widget.images, {})
  888. def test_attrs_refresh_when_choices_reassigned(self):
  889. """Reassigning a field's choices after construction should refresh the widget's description and image maps."""
  890. class OtherChoices(ChoiceSet):
  891. CHOICES = (
  892. Choice('baz', 'Baz', description='Description of baz', image='baz.svg'),
  893. )
  894. field = ChoiceField(choices=self.ExampleChoices)
  895. self.assertEqual(field.widget.descriptions, {self.ExampleChoices.FOO: 'Description of foo'})
  896. field.choices = OtherChoices
  897. self.assertEqual(field.widget.descriptions, {'baz': 'Description of baz'})
  898. self.assertEqual(field.widget.images, {'baz': 'baz.svg'})
  899. def test_show_descriptions_false_suppresses_on_reassignment(self):
  900. field = ChoiceField(choices=self.ExampleChoices, show_descriptions=False)
  901. field.choices = self.ExampleChoices
  902. self.assertEqual(field.widget.descriptions, {})
  903. def test_typedchoicefield_empty_value_defaults_to_none(self):
  904. """A blank selection on a TypedChoiceField resolves to None (for storage as NULL) rather than ''."""
  905. field = TypedChoiceField(choices=add_blank_choice(self.ExampleChoices), required=False)
  906. self.assertIsNone(field.empty_value)
  907. self.assertIsNone(field.clean(''))
  908. def test_explicit_descriptions_mapping(self):
  909. widget = Select(choices=[('x', 'X'), ('y', 'Y')], descriptions={'x': 'Description X'})
  910. html = widget.render('test', None)
  911. self.assertInHTML('<option value="x" data-description="Description X">X</option>', html)
  912. self.assertInHTML('<option value="y">Y</option>', html)
  913. def test_deepcopy_does_not_share_attrs(self):
  914. widget = Select(choices=[('x', 'X')], descriptions={'x': 'Description X'}, images={'x': 'x.svg'})
  915. clone = copy.deepcopy(widget)
  916. self.assertIsNot(widget.descriptions, clone.descriptions)
  917. self.assertIsNot(widget.images, clone.images)
  918. widget.descriptions['y'] = 'leaked'
  919. self.assertNotIn('y', clone.descriptions)
  920. def test_choices_setter_delegates_through_mro(self):
  921. """
  922. AttrChoiceMixin must delegate to the parent field's choices setter via the MRO, not a hardcoded base,
  923. so a setter override on an intermediate class is not bypassed.
  924. """
  925. from django import forms
  926. from utilities.forms.fields.choices import AttrChoiceMixin
  927. from utilities.forms.widgets import Select as DescriptionSelect
  928. calls = []
  929. class OverridingChoiceField(forms.ChoiceField):
  930. def _set_choices(self, value):
  931. calls.append(value)
  932. forms.ChoiceField.choices.fset(self, value)
  933. choices = property(forms.ChoiceField.choices.fget, _set_choices)
  934. class CustomField(AttrChoiceMixin, OverridingChoiceField):
  935. widget = DescriptionSelect
  936. field = CustomField(choices=self.ExampleChoices)
  937. # The intermediate class's setter must have been invoked (delegation not bypassed)
  938. self.assertTrue(calls)
  939. # And descriptions are still collected as normal
  940. self.assertEqual(field.widget.descriptions, {self.ExampleChoices.FOO: 'Description of foo'})