test_string.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. import unittest
  2. import string
  3. from string import Template
  4. class ModuleTest(unittest.TestCase):
  5. def test_attrs(self):
  6. # While the exact order of the items in these attributes is not
  7. # technically part of the "language spec", in practice there is almost
  8. # certainly user code that depends on the order, so de-facto it *is*
  9. # part of the spec.
  10. self.assertEqual(string.whitespace, ' \t\n\r\x0b\x0c')
  11. self.assertEqual(string.ascii_lowercase, 'abcdefghijklmnopqrstuvwxyz')
  12. self.assertEqual(string.ascii_uppercase, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
  13. self.assertEqual(string.ascii_letters, string.ascii_lowercase + string.ascii_uppercase)
  14. self.assertEqual(string.digits, '0123456789')
  15. self.assertEqual(string.hexdigits, string.digits + 'abcdefABCDEF')
  16. self.assertEqual(string.octdigits, '01234567')
  17. self.assertEqual(string.punctuation, '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
  18. self.assertEqual(string.printable, string.digits + string.ascii_lowercase + string.ascii_uppercase + string.punctuation + string.whitespace)
  19. def test_capwords(self):
  20. self.assertEqual(string.capwords('abc def ghi'), 'Abc Def Ghi')
  21. self.assertEqual(string.capwords('abc\tdef\nghi'), 'Abc Def Ghi')
  22. self.assertEqual(string.capwords('abc\t def \nghi'), 'Abc Def Ghi')
  23. self.assertEqual(string.capwords('ABC DEF GHI'), 'Abc Def Ghi')
  24. self.assertEqual(string.capwords('ABC-DEF-GHI', '-'), 'Abc-Def-Ghi')
  25. self.assertEqual(string.capwords('ABC-def DEF-ghi GHI'), 'Abc-def Def-ghi Ghi')
  26. self.assertEqual(string.capwords(' aBc DeF '), 'Abc Def')
  27. self.assertEqual(string.capwords('\taBc\tDeF\t'), 'Abc Def')
  28. self.assertEqual(string.capwords('\taBc\tDeF\t', '\t'), '\tAbc\tDef\t')
  29. def test_basic_formatter(self):
  30. fmt = string.Formatter()
  31. self.assertEqual(fmt.format("foo"), "foo")
  32. self.assertEqual(fmt.format("foo{0}", "bar"), "foobar")
  33. self.assertEqual(fmt.format("foo{1}{0}-{1}", "bar", 6), "foo6bar-6")
  34. self.assertRaises(TypeError, fmt.format)
  35. self.assertRaises(TypeError, string.Formatter.format)
  36. def test_format_keyword_arguments(self):
  37. fmt = string.Formatter()
  38. self.assertEqual(fmt.format("-{arg}-", arg='test'), '-test-')
  39. self.assertRaises(KeyError, fmt.format, "-{arg}-")
  40. self.assertEqual(fmt.format("-{self}-", self='test'), '-test-')
  41. self.assertRaises(KeyError, fmt.format, "-{self}-")
  42. self.assertEqual(fmt.format("-{format_string}-", format_string='test'),
  43. '-test-')
  44. self.assertRaises(KeyError, fmt.format, "-{format_string}-")
  45. with self.assertRaisesRegex(TypeError, "format_string"):
  46. fmt.format(format_string="-{arg}-", arg='test')
  47. def test_auto_numbering(self):
  48. fmt = string.Formatter()
  49. self.assertEqual(fmt.format('foo{}{}', 'bar', 6),
  50. 'foo{}{}'.format('bar', 6))
  51. self.assertEqual(fmt.format('foo{1}{num}{1}', None, 'bar', num=6),
  52. 'foo{1}{num}{1}'.format(None, 'bar', num=6))
  53. self.assertEqual(fmt.format('{:^{}}', 'bar', 6),
  54. '{:^{}}'.format('bar', 6))
  55. self.assertEqual(fmt.format('{:^{}} {}', 'bar', 6, 'X'),
  56. '{:^{}} {}'.format('bar', 6, 'X'))
  57. self.assertEqual(fmt.format('{:^{pad}}{}', 'foo', 'bar', pad=6),
  58. '{:^{pad}}{}'.format('foo', 'bar', pad=6))
  59. with self.assertRaises(ValueError):
  60. fmt.format('foo{1}{}', 'bar', 6)
  61. with self.assertRaises(ValueError):
  62. fmt.format('foo{}{1}', 'bar', 6)
  63. def test_conversion_specifiers(self):
  64. fmt = string.Formatter()
  65. self.assertEqual(fmt.format("-{arg!r}-", arg='test'), "-'test'-")
  66. self.assertEqual(fmt.format("{0!s}", 'test'), 'test')
  67. self.assertRaises(ValueError, fmt.format, "{0!h}", 'test')
  68. # issue13579
  69. self.assertEqual(fmt.format("{0!a}", 42), '42')
  70. self.assertEqual(fmt.format("{0!a}", string.ascii_letters),
  71. "'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'")
  72. self.assertEqual(fmt.format("{0!a}", chr(255)), "'\\xff'")
  73. self.assertEqual(fmt.format("{0!a}", chr(256)), "'\\u0100'")
  74. def test_name_lookup(self):
  75. fmt = string.Formatter()
  76. class AnyAttr:
  77. def __getattr__(self, attr):
  78. return attr
  79. x = AnyAttr()
  80. self.assertEqual(fmt.format("{0.lumber}{0.jack}", x), 'lumberjack')
  81. with self.assertRaises(AttributeError):
  82. fmt.format("{0.lumber}{0.jack}", '')
  83. def test_index_lookup(self):
  84. fmt = string.Formatter()
  85. lookup = ["eggs", "and", "spam"]
  86. self.assertEqual(fmt.format("{0[2]}{0[0]}", lookup), 'spameggs')
  87. with self.assertRaises(IndexError):
  88. fmt.format("{0[2]}{0[0]}", [])
  89. with self.assertRaises(KeyError):
  90. fmt.format("{0[2]}{0[0]}", {})
  91. def test_override_get_value(self):
  92. class NamespaceFormatter(string.Formatter):
  93. def __init__(self, namespace={}):
  94. string.Formatter.__init__(self)
  95. self.namespace = namespace
  96. def get_value(self, key, args, kwds):
  97. if isinstance(key, str):
  98. try:
  99. # Check explicitly passed arguments first
  100. return kwds[key]
  101. except KeyError:
  102. return self.namespace[key]
  103. else:
  104. string.Formatter.get_value(key, args, kwds)
  105. fmt = NamespaceFormatter({'greeting':'hello'})
  106. self.assertEqual(fmt.format("{greeting}, world!"), 'hello, world!')
  107. def test_override_format_field(self):
  108. class CallFormatter(string.Formatter):
  109. def format_field(self, value, format_spec):
  110. return format(value(), format_spec)
  111. fmt = CallFormatter()
  112. self.assertEqual(fmt.format('*{0}*', lambda : 'result'), '*result*')
  113. def test_override_convert_field(self):
  114. class XFormatter(string.Formatter):
  115. def convert_field(self, value, conversion):
  116. if conversion == 'x':
  117. return None
  118. return super().convert_field(value, conversion)
  119. fmt = XFormatter()
  120. self.assertEqual(fmt.format("{0!r}:{0!x}", 'foo', 'foo'), "'foo':None")
  121. def test_override_parse(self):
  122. class BarFormatter(string.Formatter):
  123. # returns an iterable that contains tuples of the form:
  124. # (literal_text, field_name, format_spec, conversion)
  125. def parse(self, format_string):
  126. for field in format_string.split('|'):
  127. if field[0] == '+':
  128. # it's markup
  129. field_name, _, format_spec = field[1:].partition(':')
  130. yield '', field_name, format_spec, None
  131. else:
  132. yield field, None, None, None
  133. fmt = BarFormatter()
  134. self.assertEqual(fmt.format('*|+0:^10s|*', 'foo'), '* foo *')
  135. def test_check_unused_args(self):
  136. class CheckAllUsedFormatter(string.Formatter):
  137. def check_unused_args(self, used_args, args, kwargs):
  138. # Track which arguments actually got used
  139. unused_args = set(kwargs.keys())
  140. unused_args.update(range(0, len(args)))
  141. for arg in used_args:
  142. unused_args.remove(arg)
  143. if unused_args:
  144. raise ValueError("unused arguments")
  145. fmt = CheckAllUsedFormatter()
  146. self.assertEqual(fmt.format("{0}", 10), "10")
  147. self.assertEqual(fmt.format("{0}{i}", 10, i=100), "10100")
  148. self.assertEqual(fmt.format("{0}{i}{1}", 10, 20, i=100), "1010020")
  149. self.assertRaises(ValueError, fmt.format, "{0}{i}{1}", 10, 20, i=100, j=0)
  150. self.assertRaises(ValueError, fmt.format, "{0}", 10, 20)
  151. self.assertRaises(ValueError, fmt.format, "{0}", 10, 20, i=100)
  152. self.assertRaises(ValueError, fmt.format, "{i}", 10, 20, i=100)
  153. def test_vformat_recursion_limit(self):
  154. fmt = string.Formatter()
  155. args = ()
  156. kwargs = dict(i=100)
  157. with self.assertRaises(ValueError) as err:
  158. fmt._vformat("{i}", args, kwargs, set(), -1)
  159. self.assertIn("recursion", str(err.exception))
  160. # Template tests (formerly housed in test_pep292.py)
  161. class Bag:
  162. pass
  163. class Mapping:
  164. def __getitem__(self, name):
  165. obj = self
  166. for part in name.split('.'):
  167. try:
  168. obj = getattr(obj, part)
  169. except AttributeError:
  170. raise KeyError(name)
  171. return obj
  172. class TestTemplate(unittest.TestCase):
  173. def test_regular_templates(self):
  174. s = Template('$who likes to eat a bag of $what worth $$100')
  175. self.assertEqual(s.substitute(dict(who='tim', what='ham')),
  176. 'tim likes to eat a bag of ham worth $100')
  177. self.assertRaises(KeyError, s.substitute, dict(who='tim'))
  178. self.assertRaises(TypeError, Template.substitute)
  179. def test_regular_templates_with_braces(self):
  180. s = Template('$who likes ${what} for ${meal}')
  181. d = dict(who='tim', what='ham', meal='dinner')
  182. self.assertEqual(s.substitute(d), 'tim likes ham for dinner')
  183. self.assertRaises(KeyError, s.substitute,
  184. dict(who='tim', what='ham'))
  185. def test_regular_templates_with_upper_case(self):
  186. s = Template('$WHO likes ${WHAT} for ${MEAL}')
  187. d = dict(WHO='tim', WHAT='ham', MEAL='dinner')
  188. self.assertEqual(s.substitute(d), 'tim likes ham for dinner')
  189. def test_regular_templates_with_non_letters(self):
  190. s = Template('$_wh0_ likes ${_w_h_a_t_} for ${mea1}')
  191. d = dict(_wh0_='tim', _w_h_a_t_='ham', mea1='dinner')
  192. self.assertEqual(s.substitute(d), 'tim likes ham for dinner')
  193. def test_escapes(self):
  194. eq = self.assertEqual
  195. s = Template('$who likes to eat a bag of $$what worth $$100')
  196. eq(s.substitute(dict(who='tim', what='ham')),
  197. 'tim likes to eat a bag of $what worth $100')
  198. s = Template('$who likes $$')
  199. eq(s.substitute(dict(who='tim', what='ham')), 'tim likes $')
  200. def test_percents(self):
  201. eq = self.assertEqual
  202. s = Template('%(foo)s $foo ${foo}')
  203. d = dict(foo='baz')
  204. eq(s.substitute(d), '%(foo)s baz baz')
  205. eq(s.safe_substitute(d), '%(foo)s baz baz')
  206. def test_stringification(self):
  207. eq = self.assertEqual
  208. s = Template('tim has eaten $count bags of ham today')
  209. d = dict(count=7)
  210. eq(s.substitute(d), 'tim has eaten 7 bags of ham today')
  211. eq(s.safe_substitute(d), 'tim has eaten 7 bags of ham today')
  212. s = Template('tim has eaten ${count} bags of ham today')
  213. eq(s.substitute(d), 'tim has eaten 7 bags of ham today')
  214. def test_tupleargs(self):
  215. eq = self.assertEqual
  216. s = Template('$who ate ${meal}')
  217. d = dict(who=('tim', 'fred'), meal=('ham', 'kung pao'))
  218. eq(s.substitute(d), "('tim', 'fred') ate ('ham', 'kung pao')")
  219. eq(s.safe_substitute(d), "('tim', 'fred') ate ('ham', 'kung pao')")
  220. def test_SafeTemplate(self):
  221. eq = self.assertEqual
  222. s = Template('$who likes ${what} for ${meal}')
  223. eq(s.safe_substitute(dict(who='tim')), 'tim likes ${what} for ${meal}')
  224. eq(s.safe_substitute(dict(what='ham')), '$who likes ham for ${meal}')
  225. eq(s.safe_substitute(dict(what='ham', meal='dinner')),
  226. '$who likes ham for dinner')
  227. eq(s.safe_substitute(dict(who='tim', what='ham')),
  228. 'tim likes ham for ${meal}')
  229. eq(s.safe_substitute(dict(who='tim', what='ham', meal='dinner')),
  230. 'tim likes ham for dinner')
  231. def test_invalid_placeholders(self):
  232. raises = self.assertRaises
  233. s = Template('$who likes $')
  234. raises(ValueError, s.substitute, dict(who='tim'))
  235. s = Template('$who likes ${what)')
  236. raises(ValueError, s.substitute, dict(who='tim'))
  237. s = Template('$who likes $100')
  238. raises(ValueError, s.substitute, dict(who='tim'))
  239. # Template.idpattern should match to only ASCII characters.
  240. # https://bugs.python.org/issue31672
  241. s = Template("$who likes $\u0131") # (DOTLESS I)
  242. raises(ValueError, s.substitute, dict(who='tim'))
  243. s = Template("$who likes $\u0130") # (LATIN CAPITAL LETTER I WITH DOT ABOVE)
  244. raises(ValueError, s.substitute, dict(who='tim'))
  245. def test_idpattern_override(self):
  246. class PathPattern(Template):
  247. idpattern = r'[_a-z][._a-z0-9]*'
  248. m = Mapping()
  249. m.bag = Bag()
  250. m.bag.foo = Bag()
  251. m.bag.foo.who = 'tim'
  252. m.bag.what = 'ham'
  253. s = PathPattern('$bag.foo.who likes to eat a bag of $bag.what')
  254. self.assertEqual(s.substitute(m), 'tim likes to eat a bag of ham')
  255. def test_flags_override(self):
  256. class MyPattern(Template):
  257. flags = 0
  258. s = MyPattern('$wHO likes ${WHAT} for ${meal}')
  259. d = dict(wHO='tim', WHAT='ham', meal='dinner', w='fred')
  260. self.assertRaises(ValueError, s.substitute, d)
  261. self.assertEqual(s.safe_substitute(d), 'fredHO likes ${WHAT} for dinner')
  262. def test_idpattern_override_inside_outside(self):
  263. # bpo-1198569: Allow the regexp inside and outside braces to be
  264. # different when deriving from Template.
  265. class MyPattern(Template):
  266. idpattern = r'[a-z]+'
  267. braceidpattern = r'[A-Z]+'
  268. flags = 0
  269. m = dict(foo='foo', BAR='BAR')
  270. s = MyPattern('$foo ${BAR}')
  271. self.assertEqual(s.substitute(m), 'foo BAR')
  272. def test_idpattern_override_inside_outside_invalid_unbraced(self):
  273. # bpo-1198569: Allow the regexp inside and outside braces to be
  274. # different when deriving from Template.
  275. class MyPattern(Template):
  276. idpattern = r'[a-z]+'
  277. braceidpattern = r'[A-Z]+'
  278. flags = 0
  279. m = dict(foo='foo', BAR='BAR')
  280. s = MyPattern('$FOO')
  281. self.assertRaises(ValueError, s.substitute, m)
  282. s = MyPattern('${bar}')
  283. self.assertRaises(ValueError, s.substitute, m)
  284. def test_pattern_override(self):
  285. class MyPattern(Template):
  286. pattern = r"""
  287. (?P<escaped>@{2}) |
  288. @(?P<named>[_a-z][._a-z0-9]*) |
  289. @{(?P<braced>[_a-z][._a-z0-9]*)} |
  290. (?P<invalid>@)
  291. """
  292. m = Mapping()
  293. m.bag = Bag()
  294. m.bag.foo = Bag()
  295. m.bag.foo.who = 'tim'
  296. m.bag.what = 'ham'
  297. s = MyPattern('@bag.foo.who likes to eat a bag of @bag.what')
  298. self.assertEqual(s.substitute(m), 'tim likes to eat a bag of ham')
  299. class BadPattern(Template):
  300. pattern = r"""
  301. (?P<badname>.*) |
  302. (?P<escaped>@{2}) |
  303. @(?P<named>[_a-z][._a-z0-9]*) |
  304. @{(?P<braced>[_a-z][._a-z0-9]*)} |
  305. (?P<invalid>@) |
  306. """
  307. s = BadPattern('@bag.foo.who likes to eat a bag of @bag.what')
  308. self.assertRaises(ValueError, s.substitute, {})
  309. self.assertRaises(ValueError, s.safe_substitute, {})
  310. def test_braced_override(self):
  311. class MyTemplate(Template):
  312. pattern = r"""
  313. \$(?:
  314. (?P<escaped>$) |
  315. (?P<named>[_a-z][_a-z0-9]*) |
  316. @@(?P<braced>[_a-z][_a-z0-9]*)@@ |
  317. (?P<invalid>) |
  318. )
  319. """
  320. tmpl = 'PyCon in $@@location@@'
  321. t = MyTemplate(tmpl)
  322. self.assertRaises(KeyError, t.substitute, {})
  323. val = t.substitute({'location': 'Cleveland'})
  324. self.assertEqual(val, 'PyCon in Cleveland')
  325. def test_braced_override_safe(self):
  326. class MyTemplate(Template):
  327. pattern = r"""
  328. \$(?:
  329. (?P<escaped>$) |
  330. (?P<named>[_a-z][_a-z0-9]*) |
  331. @@(?P<braced>[_a-z][_a-z0-9]*)@@ |
  332. (?P<invalid>) |
  333. )
  334. """
  335. tmpl = 'PyCon in $@@location@@'
  336. t = MyTemplate(tmpl)
  337. self.assertEqual(t.safe_substitute(), tmpl)
  338. val = t.safe_substitute({'location': 'Cleveland'})
  339. self.assertEqual(val, 'PyCon in Cleveland')
  340. def test_invalid_with_no_lines(self):
  341. # The error formatting for invalid templates
  342. # has a special case for no data that the default
  343. # pattern can't trigger (always has at least '$')
  344. # So we craft a pattern that is always invalid
  345. # with no leading data.
  346. class MyTemplate(Template):
  347. pattern = r"""
  348. (?P<invalid>) |
  349. unreachable(
  350. (?P<named>) |
  351. (?P<braced>) |
  352. (?P<escaped>)
  353. )
  354. """
  355. s = MyTemplate('')
  356. with self.assertRaises(ValueError) as err:
  357. s.substitute({})
  358. self.assertIn('line 1, col 1', str(err.exception))
  359. def test_unicode_values(self):
  360. s = Template('$who likes $what')
  361. d = dict(who='t\xffm', what='f\xfe\fed')
  362. self.assertEqual(s.substitute(d), 't\xffm likes f\xfe\x0ced')
  363. def test_keyword_arguments(self):
  364. eq = self.assertEqual
  365. s = Template('$who likes $what')
  366. eq(s.substitute(who='tim', what='ham'), 'tim likes ham')
  367. eq(s.substitute(dict(who='tim'), what='ham'), 'tim likes ham')
  368. eq(s.substitute(dict(who='fred', what='kung pao'),
  369. who='tim', what='ham'),
  370. 'tim likes ham')
  371. s = Template('the mapping is $mapping')
  372. eq(s.substitute(dict(foo='none'), mapping='bozo'),
  373. 'the mapping is bozo')
  374. eq(s.substitute(dict(mapping='one'), mapping='two'),
  375. 'the mapping is two')
  376. s = Template('the self is $self')
  377. eq(s.substitute(self='bozo'), 'the self is bozo')
  378. def test_keyword_arguments_safe(self):
  379. eq = self.assertEqual
  380. raises = self.assertRaises
  381. s = Template('$who likes $what')
  382. eq(s.safe_substitute(who='tim', what='ham'), 'tim likes ham')
  383. eq(s.safe_substitute(dict(who='tim'), what='ham'), 'tim likes ham')
  384. eq(s.safe_substitute(dict(who='fred', what='kung pao'),
  385. who='tim', what='ham'),
  386. 'tim likes ham')
  387. s = Template('the mapping is $mapping')
  388. eq(s.safe_substitute(dict(foo='none'), mapping='bozo'),
  389. 'the mapping is bozo')
  390. eq(s.safe_substitute(dict(mapping='one'), mapping='two'),
  391. 'the mapping is two')
  392. d = dict(mapping='one')
  393. raises(TypeError, s.substitute, d, {})
  394. raises(TypeError, s.safe_substitute, d, {})
  395. s = Template('the self is $self')
  396. eq(s.safe_substitute(self='bozo'), 'the self is bozo')
  397. def test_delimiter_override(self):
  398. eq = self.assertEqual
  399. raises = self.assertRaises
  400. class AmpersandTemplate(Template):
  401. delimiter = '&'
  402. s = AmpersandTemplate('this &gift is for &{who} &&')
  403. eq(s.substitute(gift='bud', who='you'), 'this bud is for you &')
  404. raises(KeyError, s.substitute)
  405. eq(s.safe_substitute(gift='bud', who='you'), 'this bud is for you &')
  406. eq(s.safe_substitute(), 'this &gift is for &{who} &')
  407. s = AmpersandTemplate('this &gift is for &{who} &')
  408. raises(ValueError, s.substitute, dict(gift='bud', who='you'))
  409. eq(s.safe_substitute(), 'this &gift is for &{who} &')
  410. class PieDelims(Template):
  411. delimiter = '@'
  412. s = PieDelims('@who likes to eat a bag of @{what} worth $100')
  413. self.assertEqual(s.substitute(dict(who='tim', what='ham')),
  414. 'tim likes to eat a bag of ham worth $100')
  415. def test_is_valid(self):
  416. eq = self.assertEqual
  417. s = Template('$who likes to eat a bag of ${what} worth $$100')
  418. self.assertTrue(s.is_valid())
  419. s = Template('$who likes to eat a bag of ${what} worth $100')
  420. self.assertFalse(s.is_valid())
  421. # if the pattern has an unrecognized capture group,
  422. # it should raise ValueError like substitute and safe_substitute do
  423. class BadPattern(Template):
  424. pattern = r"""
  425. (?P<badname>.*) |
  426. (?P<escaped>@{2}) |
  427. @(?P<named>[_a-z][._a-z0-9]*) |
  428. @{(?P<braced>[_a-z][._a-z0-9]*)} |
  429. (?P<invalid>@) |
  430. """
  431. s = BadPattern('@bag.foo.who likes to eat a bag of @bag.what')
  432. self.assertRaises(ValueError, s.is_valid)
  433. def test_get_identifiers(self):
  434. eq = self.assertEqual
  435. raises = self.assertRaises
  436. s = Template('$who likes to eat a bag of ${what} worth $$100')
  437. ids = s.get_identifiers()
  438. eq(ids, ['who', 'what'])
  439. # repeated identifiers only included once
  440. s = Template('$who likes to eat a bag of ${what} worth $$100; ${who} likes to eat a bag of $what worth $$100')
  441. ids = s.get_identifiers()
  442. eq(ids, ['who', 'what'])
  443. # invalid identifiers are ignored
  444. s = Template('$who likes to eat a bag of ${what} worth $100')
  445. ids = s.get_identifiers()
  446. eq(ids, ['who', 'what'])
  447. # if the pattern has an unrecognized capture group,
  448. # it should raise ValueError like substitute and safe_substitute do
  449. class BadPattern(Template):
  450. pattern = r"""
  451. (?P<badname>.*) |
  452. (?P<escaped>@{2}) |
  453. @(?P<named>[_a-z][._a-z0-9]*) |
  454. @{(?P<braced>[_a-z][._a-z0-9]*)} |
  455. (?P<invalid>@) |
  456. """
  457. s = BadPattern('@bag.foo.who likes to eat a bag of @bag.what')
  458. self.assertRaises(ValueError, s.get_identifiers)
  459. if __name__ == '__main__':
  460. unittest.main()