blob: 6e241ac72abf2b5472e1be4510bcebaae90c65fa [file] [log] [blame]
Barry Warsaw8bee7612004-08-25 02:22:30 +00001import unittest
Serhiy Storchaka717ea082016-06-03 10:38:02 +03002import string
Barry Warsaw12827c12004-09-10 03:08:08 +00003from string import Template
Walter Dörwald0fd583c2003-02-21 12:53:50 +00004
Raymond Hettinger674f2412004-08-23 23:23:54 +00005
Walter Dörwald0fd583c2003-02-21 12:53:50 +00006class ModuleTest(unittest.TestCase):
7
8 def test_attrs(self):
R David Murray0a8f43e2015-04-13 20:04:29 -04009 # While the exact order of the items in these attributes is not
10 # technically part of the "language spec", in practice there is almost
11 # certainly user code that depends on the order, so de-facto it *is*
12 # part of the spec.
13 self.assertEqual(string.whitespace, ' \t\n\r\x0b\x0c')
14 self.assertEqual(string.ascii_lowercase, 'abcdefghijklmnopqrstuvwxyz')
15 self.assertEqual(string.ascii_uppercase, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
16 self.assertEqual(string.ascii_letters, string.ascii_lowercase + string.ascii_uppercase)
17 self.assertEqual(string.digits, '0123456789')
18 self.assertEqual(string.hexdigits, string.digits + 'abcdefABCDEF')
19 self.assertEqual(string.octdigits, '01234567')
20 self.assertEqual(string.punctuation, '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
21 self.assertEqual(string.printable, string.digits + string.ascii_lowercase + string.ascii_uppercase + string.punctuation + string.whitespace)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000022
Ezio Melotti2c6a9492009-09-26 12:19:30 +000023 def test_capwords(self):
24 self.assertEqual(string.capwords('abc def ghi'), 'Abc Def Ghi')
25 self.assertEqual(string.capwords('abc\tdef\nghi'), 'Abc Def Ghi')
26 self.assertEqual(string.capwords('abc\t def \nghi'), 'Abc Def Ghi')
27 self.assertEqual(string.capwords('ABC DEF GHI'), 'Abc Def Ghi')
28 self.assertEqual(string.capwords('ABC-DEF-GHI', '-'), 'Abc-Def-Ghi')
29 self.assertEqual(string.capwords('ABC-def DEF-ghi GHI'), 'Abc-def Def-ghi Ghi')
Ezio Melottia40bdda2009-09-26 12:33:22 +000030 self.assertEqual(string.capwords(' aBc DeF '), 'Abc Def')
31 self.assertEqual(string.capwords('\taBc\tDeF\t'), 'Abc Def')
32 self.assertEqual(string.capwords('\taBc\tDeF\t', '\t'), '\tAbc\tDef\t')
Ezio Melotti2c6a9492009-09-26 12:19:30 +000033
Nick Coghlan62ecb6a2011-05-31 19:40:11 +100034 def test_basic_formatter(self):
Eric Smith8c663262007-08-25 02:26:07 +000035 fmt = string.Formatter()
36 self.assertEqual(fmt.format("foo"), "foo")
Eric Smith7ade6482007-08-26 22:27:13 +000037 self.assertEqual(fmt.format("foo{0}", "bar"), "foobar")
38 self.assertEqual(fmt.format("foo{1}{0}-{1}", "bar", 6), "foo6bar-6")
Serhiy Storchaka8ffe9172015-03-24 22:28:43 +020039 self.assertRaises(TypeError, fmt.format)
40 self.assertRaises(TypeError, string.Formatter.format)
41
42 def test_format_keyword_arguments(self):
43 fmt = string.Formatter()
44 self.assertEqual(fmt.format("-{arg}-", arg='test'), '-test-')
45 self.assertRaises(KeyError, fmt.format, "-{arg}-")
46 self.assertEqual(fmt.format("-{self}-", self='test'), '-test-')
47 self.assertRaises(KeyError, fmt.format, "-{self}-")
48 self.assertEqual(fmt.format("-{format_string}-", format_string='test'),
49 '-test-')
50 self.assertRaises(KeyError, fmt.format, "-{format_string}-")
Serhiy Storchaka009b0a12017-01-13 09:10:51 +020051 with self.assertRaisesRegex(TypeError, "format_string"):
52 fmt.format(format_string="-{arg}-", arg='test')
Eric Smith7ade6482007-08-26 22:27:13 +000053
Eric V. Smith7ce90742014-04-14 16:43:50 -040054 def test_auto_numbering(self):
55 fmt = string.Formatter()
56 self.assertEqual(fmt.format('foo{}{}', 'bar', 6),
57 'foo{}{}'.format('bar', 6))
58 self.assertEqual(fmt.format('foo{1}{num}{1}', None, 'bar', num=6),
59 'foo{1}{num}{1}'.format(None, 'bar', num=6))
60 self.assertEqual(fmt.format('{:^{}}', 'bar', 6),
61 '{:^{}}'.format('bar', 6))
Eric V. Smith85976b12015-09-29 10:27:38 -040062 self.assertEqual(fmt.format('{:^{}} {}', 'bar', 6, 'X'),
63 '{:^{}} {}'.format('bar', 6, 'X'))
Eric V. Smith7ce90742014-04-14 16:43:50 -040064 self.assertEqual(fmt.format('{:^{pad}}{}', 'foo', 'bar', pad=6),
65 '{:^{pad}}{}'.format('foo', 'bar', pad=6))
66
67 with self.assertRaises(ValueError):
68 fmt.format('foo{1}{}', 'bar', 6)
69
70 with self.assertRaises(ValueError):
71 fmt.format('foo{}{1}', 'bar', 6)
72
Nick Coghlan62ecb6a2011-05-31 19:40:11 +100073 def test_conversion_specifiers(self):
74 fmt = string.Formatter()
75 self.assertEqual(fmt.format("-{arg!r}-", arg='test'), "-'test'-")
76 self.assertEqual(fmt.format("{0!s}", 'test'), 'test')
77 self.assertRaises(ValueError, fmt.format, "{0!h}", 'test')
R David Murraye56bf972012-08-19 17:26:34 -040078 # issue13579
79 self.assertEqual(fmt.format("{0!a}", 42), '42')
80 self.assertEqual(fmt.format("{0!a}", string.ascii_letters),
81 "'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'")
82 self.assertEqual(fmt.format("{0!a}", chr(255)), "'\\xff'")
83 self.assertEqual(fmt.format("{0!a}", chr(256)), "'\\u0100'")
Nick Coghlan62ecb6a2011-05-31 19:40:11 +100084
85 def test_name_lookup(self):
86 fmt = string.Formatter()
87 class AnyAttr:
88 def __getattr__(self, attr):
89 return attr
90 x = AnyAttr()
91 self.assertEqual(fmt.format("{0.lumber}{0.jack}", x), 'lumberjack')
92 with self.assertRaises(AttributeError):
93 fmt.format("{0.lumber}{0.jack}", '')
94
95 def test_index_lookup(self):
96 fmt = string.Formatter()
97 lookup = ["eggs", "and", "spam"]
98 self.assertEqual(fmt.format("{0[2]}{0[0]}", lookup), 'spameggs')
99 with self.assertRaises(IndexError):
100 fmt.format("{0[2]}{0[0]}", [])
101 with self.assertRaises(KeyError):
102 fmt.format("{0[2]}{0[0]}", {})
103
104 def test_override_get_value(self):
Eric Smith7ade6482007-08-26 22:27:13 +0000105 class NamespaceFormatter(string.Formatter):
106 def __init__(self, namespace={}):
107 string.Formatter.__init__(self)
108 self.namespace = namespace
109
110 def get_value(self, key, args, kwds):
111 if isinstance(key, str):
112 try:
113 # Check explicitly passed arguments first
114 return kwds[key]
115 except KeyError:
116 return self.namespace[key]
117 else:
118 string.Formatter.get_value(key, args, kwds)
119
120 fmt = NamespaceFormatter({'greeting':'hello'})
121 self.assertEqual(fmt.format("{greeting}, world!"), 'hello, world!')
Eric Smith8c663262007-08-25 02:26:07 +0000122
123
Nick Coghlan62ecb6a2011-05-31 19:40:11 +1000124 def test_override_format_field(self):
Eric Smith81936692007-08-31 01:14:01 +0000125 class CallFormatter(string.Formatter):
126 def format_field(self, value, format_spec):
127 return format(value(), format_spec)
128
129 fmt = CallFormatter()
130 self.assertEqual(fmt.format('*{0}*', lambda : 'result'), '*result*')
131
132
Nick Coghlan62ecb6a2011-05-31 19:40:11 +1000133 def test_override_convert_field(self):
Eric Smith81936692007-08-31 01:14:01 +0000134 class XFormatter(string.Formatter):
135 def convert_field(self, value, conversion):
136 if conversion == 'x':
137 return None
Nick Coghlan62ecb6a2011-05-31 19:40:11 +1000138 return super().convert_field(value, conversion)
Eric Smith81936692007-08-31 01:14:01 +0000139
140 fmt = XFormatter()
141 self.assertEqual(fmt.format("{0!r}:{0!x}", 'foo', 'foo'), "'foo':None")
142
143
Nick Coghlan62ecb6a2011-05-31 19:40:11 +1000144 def test_override_parse(self):
Eric Smith81936692007-08-31 01:14:01 +0000145 class BarFormatter(string.Formatter):
146 # returns an iterable that contains tuples of the form:
147 # (literal_text, field_name, format_spec, conversion)
148 def parse(self, format_string):
149 for field in format_string.split('|'):
150 if field[0] == '+':
151 # it's markup
152 field_name, _, format_spec = field[1:].partition(':')
153 yield '', field_name, format_spec, None
154 else:
155 yield field, None, None, None
156
157 fmt = BarFormatter()
158 self.assertEqual(fmt.format('*|+0:^10s|*', 'foo'), '* foo *')
159
Nick Coghlan62ecb6a2011-05-31 19:40:11 +1000160 def test_check_unused_args(self):
Eric Smith3bcc42a2007-08-31 02:26:31 +0000161 class CheckAllUsedFormatter(string.Formatter):
162 def check_unused_args(self, used_args, args, kwargs):
Ezio Melotti42da6632011-03-15 05:18:48 +0200163 # Track which arguments actually got used
Eric Smith3bcc42a2007-08-31 02:26:31 +0000164 unused_args = set(kwargs.keys())
165 unused_args.update(range(0, len(args)))
166
167 for arg in used_args:
168 unused_args.remove(arg)
169
170 if unused_args:
171 raise ValueError("unused arguments")
172
173 fmt = CheckAllUsedFormatter()
174 self.assertEqual(fmt.format("{0}", 10), "10")
175 self.assertEqual(fmt.format("{0}{i}", 10, i=100), "10100")
176 self.assertEqual(fmt.format("{0}{i}{1}", 10, 20, i=100), "1010020")
177 self.assertRaises(ValueError, fmt.format, "{0}{i}{1}", 10, 20, i=100, j=0)
178 self.assertRaises(ValueError, fmt.format, "{0}", 10, 20)
179 self.assertRaises(ValueError, fmt.format, "{0}", 10, 20, i=100)
180 self.assertRaises(ValueError, fmt.format, "{i}", 10, 20, i=100)
181
Nick Coghlan62ecb6a2011-05-31 19:40:11 +1000182 def test_vformat_recursion_limit(self):
183 fmt = string.Formatter()
184 args = ()
185 kwargs = dict(i=100)
186 with self.assertRaises(ValueError) as err:
187 fmt._vformat("{i}", args, kwargs, set(), -1)
188 self.assertIn("recursion", str(err.exception))
Nick Coghland25fd4d2011-03-15 08:54:37 +1000189
190
Serhiy Storchaka717ea082016-06-03 10:38:02 +0300191# Template tests (formerly housed in test_pep292.py)
192
Barry Warsaw12827c12004-09-10 03:08:08 +0000193class Bag:
194 pass
195
196class Mapping:
197 def __getitem__(self, name):
198 obj = self
199 for part in name.split('.'):
200 try:
201 obj = getattr(obj, part)
202 except AttributeError:
203 raise KeyError(name)
204 return obj
205
Barry Warsaw8bee7612004-08-25 02:22:30 +0000206
207class TestTemplate(unittest.TestCase):
Barry Warsaw8bee7612004-08-25 02:22:30 +0000208 def test_regular_templates(self):
209 s = Template('$who likes to eat a bag of $what worth $$100')
Barry Warsaw12827c12004-09-10 03:08:08 +0000210 self.assertEqual(s.substitute(dict(who='tim', what='ham')),
Barry Warsaw8bee7612004-08-25 02:22:30 +0000211 'tim likes to eat a bag of ham worth $100')
Barry Warsaw12827c12004-09-10 03:08:08 +0000212 self.assertRaises(KeyError, s.substitute, dict(who='tim'))
Serhiy Storchaka8ffe9172015-03-24 22:28:43 +0200213 self.assertRaises(TypeError, Template.substitute)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000214
215 def test_regular_templates_with_braces(self):
216 s = Template('$who likes ${what} for ${meal}')
Barry Warsaw12827c12004-09-10 03:08:08 +0000217 d = dict(who='tim', what='ham', meal='dinner')
218 self.assertEqual(s.substitute(d), 'tim likes ham for dinner')
219 self.assertRaises(KeyError, s.substitute,
220 dict(who='tim', what='ham'))
Barry Warsaw8bee7612004-08-25 02:22:30 +0000221
222 def test_escapes(self):
223 eq = self.assertEqual
224 s = Template('$who likes to eat a bag of $$what worth $$100')
Barry Warsaw12827c12004-09-10 03:08:08 +0000225 eq(s.substitute(dict(who='tim', what='ham')),
Barry Warsaw8bee7612004-08-25 02:22:30 +0000226 'tim likes to eat a bag of $what worth $100')
227 s = Template('$who likes $$')
Barry Warsaw12827c12004-09-10 03:08:08 +0000228 eq(s.substitute(dict(who='tim', what='ham')), 'tim likes $')
Barry Warsaw8bee7612004-08-25 02:22:30 +0000229
230 def test_percents(self):
Barry Warsaw12827c12004-09-10 03:08:08 +0000231 eq = self.assertEqual
Barry Warsaw8bee7612004-08-25 02:22:30 +0000232 s = Template('%(foo)s $foo ${foo}')
Barry Warsaw12827c12004-09-10 03:08:08 +0000233 d = dict(foo='baz')
234 eq(s.substitute(d), '%(foo)s baz baz')
235 eq(s.safe_substitute(d), '%(foo)s baz baz')
Barry Warsaw8bee7612004-08-25 02:22:30 +0000236
237 def test_stringification(self):
Barry Warsaw12827c12004-09-10 03:08:08 +0000238 eq = self.assertEqual
Barry Warsaw8bee7612004-08-25 02:22:30 +0000239 s = Template('tim has eaten $count bags of ham today')
Barry Warsaw12827c12004-09-10 03:08:08 +0000240 d = dict(count=7)
241 eq(s.substitute(d), 'tim has eaten 7 bags of ham today')
242 eq(s.safe_substitute(d), 'tim has eaten 7 bags of ham today')
243 s = Template('tim has eaten ${count} bags of ham today')
244 eq(s.substitute(d), 'tim has eaten 7 bags of ham today')
Barry Warsaw8bee7612004-08-25 02:22:30 +0000245
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000246 def test_tupleargs(self):
247 eq = self.assertEqual
248 s = Template('$who ate ${meal}')
249 d = dict(who=('tim', 'fred'), meal=('ham', 'kung pao'))
250 eq(s.substitute(d), "('tim', 'fred') ate ('ham', 'kung pao')")
251 eq(s.safe_substitute(d), "('tim', 'fred') ate ('ham', 'kung pao')")
252
Barry Warsaw8bee7612004-08-25 02:22:30 +0000253 def test_SafeTemplate(self):
254 eq = self.assertEqual
Barry Warsaw12827c12004-09-10 03:08:08 +0000255 s = Template('$who likes ${what} for ${meal}')
256 eq(s.safe_substitute(dict(who='tim')), 'tim likes ${what} for ${meal}')
257 eq(s.safe_substitute(dict(what='ham')), '$who likes ham for ${meal}')
258 eq(s.safe_substitute(dict(what='ham', meal='dinner')),
Barry Warsaw8bee7612004-08-25 02:22:30 +0000259 '$who likes ham for dinner')
Barry Warsaw12827c12004-09-10 03:08:08 +0000260 eq(s.safe_substitute(dict(who='tim', what='ham')),
Barry Warsaw8bee7612004-08-25 02:22:30 +0000261 'tim likes ham for ${meal}')
Barry Warsaw12827c12004-09-10 03:08:08 +0000262 eq(s.safe_substitute(dict(who='tim', what='ham', meal='dinner')),
Barry Warsaw8bee7612004-08-25 02:22:30 +0000263 'tim likes ham for dinner')
264
265 def test_invalid_placeholders(self):
266 raises = self.assertRaises
267 s = Template('$who likes $')
Barry Warsaw12827c12004-09-10 03:08:08 +0000268 raises(ValueError, s.substitute, dict(who='tim'))
Barry Warsaw8bee7612004-08-25 02:22:30 +0000269 s = Template('$who likes ${what)')
Barry Warsaw12827c12004-09-10 03:08:08 +0000270 raises(ValueError, s.substitute, dict(who='tim'))
Barry Warsaw8bee7612004-08-25 02:22:30 +0000271 s = Template('$who likes $100')
Barry Warsaw12827c12004-09-10 03:08:08 +0000272 raises(ValueError, s.substitute, dict(who='tim'))
273
Barry Warsaw12827c12004-09-10 03:08:08 +0000274 def test_idpattern_override(self):
275 class PathPattern(Template):
276 idpattern = r'[_a-z][._a-z0-9]*'
277 m = Mapping()
278 m.bag = Bag()
279 m.bag.foo = Bag()
280 m.bag.foo.who = 'tim'
281 m.bag.what = 'ham'
282 s = PathPattern('$bag.foo.who likes to eat a bag of $bag.what')
283 self.assertEqual(s.substitute(m), 'tim likes to eat a bag of ham')
284
Barry Warsawba427962017-09-04 16:32:10 -0400285 def test_idpattern_override_inside_outside(self):
286 # bpo-1198569: Allow the regexp inside and outside braces to be
287 # different when deriving from Template.
288 class MyPattern(Template):
289 idpattern = r'[a-z]+'
290 braceidpattern = r'[A-Z]+'
291 flags = 0
292 m = dict(foo='foo', BAR='BAR')
293 s = MyPattern('$foo ${BAR}')
294 self.assertEqual(s.substitute(m), 'foo BAR')
295
296 def test_idpattern_override_inside_outside_invalid_unbraced(self):
297 # bpo-1198569: Allow the regexp inside and outside braces to be
298 # different when deriving from Template.
299 class MyPattern(Template):
300 idpattern = r'[a-z]+'
301 braceidpattern = r'[A-Z]+'
302 flags = 0
303 m = dict(foo='foo', BAR='BAR')
304 s = MyPattern('$FOO')
305 self.assertRaises(ValueError, s.substitute, m)
306 s = MyPattern('${bar}')
307 self.assertRaises(ValueError, s.substitute, m)
308
Barry Warsaw12827c12004-09-10 03:08:08 +0000309 def test_pattern_override(self):
310 class MyPattern(Template):
311 pattern = r"""
312 (?P<escaped>@{2}) |
313 @(?P<named>[_a-z][._a-z0-9]*) |
314 @{(?P<braced>[_a-z][._a-z0-9]*)} |
Barry Warsaw3e773fb2004-09-13 20:53:27 +0000315 (?P<invalid>@)
Barry Warsaw12827c12004-09-10 03:08:08 +0000316 """
317 m = Mapping()
318 m.bag = Bag()
319 m.bag.foo = Bag()
320 m.bag.foo.who = 'tim'
321 m.bag.what = 'ham'
322 s = MyPattern('@bag.foo.who likes to eat a bag of @bag.what')
323 self.assertEqual(s.substitute(m), 'tim likes to eat a bag of ham')
324
Neal Norwitz6627a962004-10-17 16:27:18 +0000325 class BadPattern(Template):
326 pattern = r"""
327 (?P<badname>.*) |
328 (?P<escaped>@{2}) |
329 @(?P<named>[_a-z][._a-z0-9]*) |
330 @{(?P<braced>[_a-z][._a-z0-9]*)} |
331 (?P<invalid>@) |
332 """
333 s = BadPattern('@bag.foo.who likes to eat a bag of @bag.what')
334 self.assertRaises(ValueError, s.substitute, {})
335 self.assertRaises(ValueError, s.safe_substitute, {})
336
Florent Xiclunaeb19dce2010-09-18 23:34:07 +0000337 def test_braced_override(self):
338 class MyTemplate(Template):
339 pattern = r"""
340 \$(?:
341 (?P<escaped>$) |
342 (?P<named>[_a-z][_a-z0-9]*) |
343 @@(?P<braced>[_a-z][_a-z0-9]*)@@ |
344 (?P<invalid>) |
345 )
346 """
347
348 tmpl = 'PyCon in $@@location@@'
349 t = MyTemplate(tmpl)
350 self.assertRaises(KeyError, t.substitute, {})
351 val = t.substitute({'location': 'Cleveland'})
352 self.assertEqual(val, 'PyCon in Cleveland')
353
354 def test_braced_override_safe(self):
355 class MyTemplate(Template):
356 pattern = r"""
357 \$(?:
358 (?P<escaped>$) |
359 (?P<named>[_a-z][_a-z0-9]*) |
360 @@(?P<braced>[_a-z][_a-z0-9]*)@@ |
361 (?P<invalid>) |
362 )
363 """
364
365 tmpl = 'PyCon in $@@location@@'
366 t = MyTemplate(tmpl)
367 self.assertEqual(t.safe_substitute(), tmpl)
368 val = t.safe_substitute({'location': 'Cleveland'})
369 self.assertEqual(val, 'PyCon in Cleveland')
370
Nick Coghlan62ecb6a2011-05-31 19:40:11 +1000371 def test_invalid_with_no_lines(self):
372 # The error formatting for invalid templates
373 # has a special case for no data that the default
374 # pattern can't trigger (always has at least '$')
375 # So we craft a pattern that is always invalid
376 # with no leading data.
377 class MyTemplate(Template):
378 pattern = r"""
379 (?P<invalid>) |
380 unreachable(
381 (?P<named>) |
382 (?P<braced>) |
383 (?P<escaped>)
384 )
385 """
386 s = MyTemplate('')
387 with self.assertRaises(ValueError) as err:
388 s.substitute({})
389 self.assertIn('line 1, col 1', str(err.exception))
390
Barry Warsaw12827c12004-09-10 03:08:08 +0000391 def test_unicode_values(self):
392 s = Template('$who likes $what')
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000393 d = dict(who='t\xffm', what='f\xfe\fed')
394 self.assertEqual(s.substitute(d), 't\xffm likes f\xfe\x0ced')
Barry Warsaw8bee7612004-08-25 02:22:30 +0000395
Barry Warsaw302bd582004-09-13 14:35:59 +0000396 def test_keyword_arguments(self):
397 eq = self.assertEqual
398 s = Template('$who likes $what')
399 eq(s.substitute(who='tim', what='ham'), 'tim likes ham')
400 eq(s.substitute(dict(who='tim'), what='ham'), 'tim likes ham')
401 eq(s.substitute(dict(who='fred', what='kung pao'),
402 who='tim', what='ham'),
403 'tim likes ham')
404 s = Template('the mapping is $mapping')
405 eq(s.substitute(dict(foo='none'), mapping='bozo'),
406 'the mapping is bozo')
407 eq(s.substitute(dict(mapping='one'), mapping='two'),
408 'the mapping is two')
409
Serhiy Storchaka8ffe9172015-03-24 22:28:43 +0200410 s = Template('the self is $self')
411 eq(s.substitute(self='bozo'), 'the self is bozo')
412
Barry Warsaw302bd582004-09-13 14:35:59 +0000413 def test_keyword_arguments_safe(self):
414 eq = self.assertEqual
Barry Warsawc7cd20c2004-09-13 15:24:43 +0000415 raises = self.assertRaises
Barry Warsaw302bd582004-09-13 14:35:59 +0000416 s = Template('$who likes $what')
417 eq(s.safe_substitute(who='tim', what='ham'), 'tim likes ham')
418 eq(s.safe_substitute(dict(who='tim'), what='ham'), 'tim likes ham')
419 eq(s.safe_substitute(dict(who='fred', what='kung pao'),
420 who='tim', what='ham'),
421 'tim likes ham')
422 s = Template('the mapping is $mapping')
423 eq(s.safe_substitute(dict(foo='none'), mapping='bozo'),
424 'the mapping is bozo')
425 eq(s.safe_substitute(dict(mapping='one'), mapping='two'),
426 'the mapping is two')
Barry Warsawc7cd20c2004-09-13 15:24:43 +0000427 d = dict(mapping='one')
428 raises(TypeError, s.substitute, d, {})
429 raises(TypeError, s.safe_substitute, d, {})
Barry Warsaw302bd582004-09-13 14:35:59 +0000430
Serhiy Storchaka8ffe9172015-03-24 22:28:43 +0200431 s = Template('the self is $self')
432 eq(s.safe_substitute(self='bozo'), 'the self is bozo')
433
Raymond Hettinger6d191112004-09-14 02:34:08 +0000434 def test_delimiter_override(self):
Barry Warsaw8c72eae2004-11-01 03:52:43 +0000435 eq = self.assertEqual
436 raises = self.assertRaises
Raymond Hettinger6d191112004-09-14 02:34:08 +0000437 class AmpersandTemplate(Template):
438 delimiter = '&'
439 s = AmpersandTemplate('this &gift is for &{who} &&')
Barry Warsaw8c72eae2004-11-01 03:52:43 +0000440 eq(s.substitute(gift='bud', who='you'), 'this bud is for you &')
441 raises(KeyError, s.substitute)
442 eq(s.safe_substitute(gift='bud', who='you'), 'this bud is for you &')
443 eq(s.safe_substitute(), 'this &gift is for &{who} &')
Raymond Hettinger6d191112004-09-14 02:34:08 +0000444 s = AmpersandTemplate('this &gift is for &{who} &')
Barry Warsaw8c72eae2004-11-01 03:52:43 +0000445 raises(ValueError, s.substitute, dict(gift='bud', who='you'))
446 eq(s.safe_substitute(), 'this &gift is for &{who} &')
447
Georg Brandl89fad142010-03-14 10:23:39 +0000448 class PieDelims(Template):
449 delimiter = '@'
450 s = PieDelims('@who likes to eat a bag of @{what} worth $100')
451 self.assertEqual(s.substitute(dict(who='tim', what='ham')),
452 'tim likes to eat a bag of ham worth $100')
453
Barry Warsaw8bee7612004-08-25 02:22:30 +0000454
Barry Warsaw8bee7612004-08-25 02:22:30 +0000455if __name__ == '__main__':
Zachary Ware38c707e2015-04-13 15:00:43 -0500456 unittest.main()