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