File size: 21,668 Bytes
a4edccc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 | diff --git a/Lib/test/test_string_compat_aug.py b/Lib/test/test_string_compat_aug.py
new file mode 100644
index 00000000000..c07e6906d91
--- /dev/null
+++ b/Lib/test/test_string_compat_aug.py
@@ -0,0 +1,92 @@
+import string
+import unittest
+from types import SimpleNamespace
+
+
+class TestStringCompatibilityAug(unittest.TestCase):
+ def test_template_substitution_contracts(self):
+ template = string.Template("$who owes $$${amount}")
+ self.assertEqual(
+ template.substitute({"who": "Ada", "amount": "5"}),
+ "Ada owes $5",
+ )
+
+ safe = string.Template("$known and $missing")
+ self.assertEqual(
+ safe.safe_substitute({"known": "present"}),
+ "present and $missing",
+ )
+
+ def test_formatter_and_capwords_contracts(self):
+ formatter = string.Formatter()
+ subject = SimpleNamespace(name="node")
+ self.assertEqual(
+ formatter.format("{0.name}:{count:03d}", subject, count=7),
+ "node:007",
+ )
+
+ parsed = list(formatter.parse("pre {name!r:^10} post"))
+ field = next(item for item in parsed if item[1] is not None)
+ self.assertEqual(field[1:4], ("name", "^10", "r"))
+ self.assertEqual(string.capwords(" alpha\tbeta gamma "), "Alpha Beta Gamma")
+
+ def test_template_identifier_and_validation_contracts(self):
+ self.assertEqual(string.whitespace, " \t\n\r\v\f")
+ self.assertEqual(string.ascii_letters, string.ascii_lowercase + string.ascii_uppercase)
+ self.assertEqual(string.hexdigits, string.digits + "abcdef" + "ABCDEF")
+ self.assertIn("~", string.punctuation)
+
+ template = string.Template("$who ${what} $$ $who")
+ self.assertEqual(
+ template.substitute({"who": "Ada"}, what="tests"),
+ "Ada tests $ Ada",
+ )
+ self.assertEqual(template.get_identifiers(), ["who", "what"])
+ self.assertTrue(template.is_valid())
+
+ invalid = string.Template("$")
+ self.assertFalse(invalid.is_valid())
+ self.assertEqual(invalid.safe_substitute(), "$")
+ with self.assertRaisesRegex(ValueError, "line 1, col 1"):
+ invalid.substitute({})
+
+ missing = string.Template("$known ${unknown} $$")
+ self.assertEqual(
+ missing.safe_substitute({"known": "yes"}),
+ "yes ${unknown} $",
+ )
+
+ class PercentTemplate(string.Template):
+ delimiter = "%"
+
+ self.assertEqual(
+ PercentTemplate("%name %%").substitute(name="Ada"),
+ "Ada %",
+ )
+
+ def test_formatter_error_and_nested_contracts(self):
+ formatter = string.Formatter()
+ self.assertEqual(formatter.format("{0:{width}}", 7, width="03d"), "007")
+ self.assertEqual(formatter.format("{!s} {!r} {!a}", "x", "x", "é"), "x 'x' '\\xe9'")
+
+ with self.assertRaisesRegex(
+ ValueError,
+ "cannot switch from manual field specification to automatic field numbering",
+ ):
+ formatter.format("{0} {}", "manual", "auto")
+
+ with self.assertRaisesRegex(
+ ValueError,
+ "cannot switch from automatic field numbering to manual field specification",
+ ):
+ formatter.format("{} {0}", "auto", "manual")
+
+ with self.assertRaisesRegex(ValueError, "Unknown conversion specifier q"):
+ formatter.convert_field("value", "q")
+
+ with self.assertRaisesRegex(ValueError, "Max string recursion exceeded"):
+ formatter.vformat("{0:{1:{2}}}", (1, 2, 3), {})
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/Lib/test/test_tstring_aug.py b/Lib/test/test_tstring_aug.py
new file mode 100644
index 00000000000..95461cc7f16
--- /dev/null
+++ b/Lib/test/test_tstring_aug.py
@@ -0,0 +1,434 @@
+import ast
+import io
+import pickle
+import tokenize
+import unittest
+
+from string.templatelib import Interpolation, Template
+
+
+class TestTStringAug(unittest.TestCase):
+ def test_literal_metadata_values_and_iteration(self):
+ name = "World"
+ value = 12.345
+ template = t"hello {name!r} {value:.2f}"
+
+ self.assertIsInstance(template, Template)
+ self.assertEqual(template.strings, ("hello ", " ", ""))
+ self.assertEqual(template.values, ("World", 12.345))
+ self.assertEqual(len(template.interpolations), 2)
+
+ first, second = template.interpolations
+ self.assertIsInstance(first, Interpolation)
+ self.assertEqual(
+ (first.value, first.expression, first.conversion, first.format_spec),
+ ("World", "name", "r", ""),
+ )
+ self.assertEqual(
+ (second.value, second.expression, second.conversion, second.format_spec),
+ (12.345, "value", None, ".2f"),
+ )
+
+ only = t"{name}"
+ only_items = list(only)
+ self.assertEqual(len(only_items), 1)
+ self.assertIs(only_items[0], only.interpolations[0])
+
+ ordered = t"hello {name}"
+ ordered_items = list(ordered)
+ self.assertEqual(ordered_items[0], "hello ")
+ self.assertIs(ordered_items[1], ordered.interpolations[0])
+
+ def test_constructor_pickle_pattern_and_validation(self):
+ self.assertIsNot(Template, Interpolation)
+ with self.assertRaises(ValueError):
+ Interpolation(1, "x", "z", "")
+
+ interpolation = Interpolation(3, "x + 1", "a", ".1f")
+ match interpolation:
+ case Interpolation(value, expression, conversion, format_spec):
+ fields = (value, expression, conversion, format_spec)
+ case _:
+ self.fail("Interpolation did not support four-position matching")
+ self.assertEqual(fields, (3, "x + 1", "a", ".1f"))
+
+ template = Template("a", Interpolation(1, "x", None, ""), "b")
+ unpickled = pickle.loads(pickle.dumps(template))
+ self.assertEqual(unpickled.strings, ("a", "b"))
+ self.assertEqual(unpickled.values, (1,))
+ self.assertEqual(len(unpickled.interpolations), 1)
+ self.assertEqual(unpickled.interpolations[0].expression, "x")
+
+ def test_concatenation_debug_raw_uppercase_and_unparse(self):
+ a = 1
+ b = 2
+ combined = t"{a}" + t"{b}"
+ self.assertEqual(combined.values, (1, 2))
+
+ x = 3
+ self.assertEqual((t"a" + t"b{x}").strings, ("ab", ""))
+
+ value = 42
+ debug = t"{value = }"
+ self.assertEqual(debug.strings, ("value = ", ""))
+ self.assertEqual(debug.interpolations[0].expression, "value")
+ self.assertEqual(debug.interpolations[0].conversion, "r")
+
+ upper = T"upper {value}"
+ self.assertEqual(upper.strings, ("upper ", ""))
+ self.assertEqual(upper.values, (42,))
+
+ raw_prefix = rt"{value}\n"
+ self.assertEqual(raw_prefix.strings, ("", r"\n"))
+ raw_alternate = tr"\n{value}"
+ self.assertEqual(raw_alternate.strings, (r"\n", ""))
+
+ unparsed = ast.unparse(ast.parse("t'hello {value}'", mode="eval"))
+ self.assertRegex(unparsed, r"^t['\"]")
+ self.assertNotRegex(unparsed, r"^f['\"]")
+
+ split = ast.unparse(ast.parse("t'left {value}' f' right {value}'", mode="eval"))
+ self.assertRegex(split, r"^t['\"]")
+ self.assertRegex(split, r" f['\"]")
+
+ def test_tr_raw_named_unicode_escape_keeps_braces_as_fields(self):
+ BULLET = "bullet-name"
+ x = "payload"
+ template = tr"\N{BULLET}{x}"
+
+ self.assertEqual(template.strings, (r"\N", "", ""))
+ self.assertEqual(template.values, ("bullet-name", "payload"))
+ self.assertEqual(
+ [interp.expression for interp in template.interpolations],
+ ["BULLET", "x"],
+ )
+
+ def test_tokenize_untokenize_brace_roundtrip(self):
+ source = 't"{{ {name} }}"'
+ untokenized = tokenize.untokenize(
+ tokenize.generate_tokens(io.StringIO(source).readline)
+ )
+ name = "Ada"
+ template = eval(untokenized, {"name": name})
+ self.assertEqual(template.strings, ("{ ", " }"))
+ self.assertEqual(template.values, ("Ada",))
+
+ def test_disassembly_annotation_ast_compile_and_metadata(self):
+ import dis
+ import opcode
+ import textwrap
+
+ def build_template(value):
+ return t"visible {value!a:.3}"
+
+ opnames = [instruction.opname for instruction in dis.Bytecode(build_template)]
+ self.assertIn("LOAD_CONST", opnames)
+ self.assertIsInstance(opcode.opmap, dict)
+
+ template = build_template("café")
+ self.assertEqual(template.values, ("café",))
+ self.assertEqual(template.interpolations[0].conversion, "a")
+ self.assertEqual(template.interpolations[0].format_spec, ".3")
+
+ namespace = {"value": 3.25}
+ tree = ast.parse('result = t"compiled {value!r:.2f}"', mode="exec")
+ exec(compile(tree, "<tstring-ast>", "exec"), namespace)
+ compiled = namespace["result"]
+ self.assertEqual(compiled.values, (3.25,))
+ self.assertEqual(compiled.interpolations[0].conversion, "r")
+ self.assertEqual(compiled.interpolations[0].format_spec, ".2f")
+
+ annotated = {}
+ exec(
+ textwrap.dedent(
+ """
+ from __future__ import annotations
+ value = 8
+ target: t"ann {value!r}" = 1
+ combo: t"left {value}" f" right {value}" = 2
+ """
+ ),
+ annotated,
+ )
+ annotations = annotated["__annotations__"]
+ for annotation in annotations.values():
+ rendered = eval(annotation, {"value": 8})
+ self.assertIsInstance(rendered, Template)
+ self.assertEqual(eval(annotations["target"], {"value": 8}).values, (8,))
+ self.assertEqual(eval(annotations["combo"], {"value": 8}).values, (8,))
+
+ def test_template_public_error_and_gc_paths(self):
+ import gc
+
+ with self.assertRaises(TypeError):
+ Template(text="x")
+ with self.assertRaises(TypeError):
+ Template(b"bytes")
+ with self.assertRaises(TypeError):
+ Interpolation(1, "x", object(), "")
+ with self.assertRaises(TypeError):
+ Interpolation(1, 123, None, "")
+ with self.assertRaises(TypeError):
+ Interpolation(1, "x", None, 123)
+
+ payload = {"kind": "dict"}
+ template = Template("start", Interpolation(payload, "payload", None, ""), "end")
+ self.assertIn(template.strings, gc.get_referents(template))
+ self.assertIn(template.interpolations, gc.get_referents(template))
+
+ interpolation_refs = gc.get_referents(template.interpolations[0])
+ self.assertIn(payload, interpolation_refs)
+ self.assertIn("payload", interpolation_refs)
+
+ contents = list(template)
+ self.assertEqual(len(contents), 3)
+ self.assertEqual(contents[0], "start")
+ self.assertIs(contents[1], template.interpolations[0])
+ self.assertEqual(contents[1].value, payload)
+ self.assertEqual(contents[1].expression, "payload")
+ self.assertEqual(contents[2], "end")
+
+ self.assertIs(template + 1, NotImplemented)
+ with self.assertRaises(TypeError):
+ 1 + template
+
+ with self.assertRaises(AttributeError):
+ template.strings = ()
+ with self.assertRaises(AttributeError):
+ template.interpolations[0].value = None
+
+ def test_parser_contexts_and_invalid_tstring_matrix(self):
+ import textwrap
+
+ valid_exec_cases = [
+ "def f(x=t'{1}', /, y=t'{2}', *args, z=t'{3}', **kw): return x",
+ "lambda x=t'{1}', /, y=t'{2}', *args, z=t'{3}', **kw: x",
+ "result = func(t'{1}', *[t'{2}'], key=t'{3}', **{'extra': t'{4}'})",
+ "result = [t'{x}' for x in range(3) if t'{x}']",
+ "async def f(source):\n return [t'{item}' async for item in source if t'{item}']",
+ "result = {t'{x}': t'{x}' for x in range(2) if t'{x}'}",
+ "items[t'{x}', t'{x}':t'{x}']",
+ "with cm(t'{x}') as a, cm(t'{x}') as b:\n pass",
+ "for item in [t'{x}']:\n pass",
+ "if t'{x}':\n pass\nwhile t'{x}':\n break",
+ "@decor(t'{x}')\ndef f():\n pass",
+ "try:\n raise err\nexcept* Group as caught:\n note = t'{caught}'",
+ ]
+ for source in valid_exec_cases:
+ with self.subTest(source=source):
+ compile(source, "<tstring-parser-context>", "exec")
+
+ valid_eval_cases = [
+ "t'{x:{y=}}'",
+ "t'{x:{y!r}}'",
+ "t'{x:{y!s:{z}}}'",
+ "(t'{x}', t'{y}', t'{z}')",
+ ]
+ for source in valid_eval_cases:
+ with self.subTest(source=source):
+ compile(source, "<tstring-parser-context>", "eval")
+
+ invalid_cases = [
+ "t'{x:{y!}}'",
+ "t'{x:{!r}}'",
+ "t'{x:{y!q}}'",
+ "t'{x:{y!r}'",
+ "t'{x:{y;}}'",
+ "t'{x:{'",
+ "t'{x!}'",
+ "t'{x!q}'",
+ "t'{x!s!}'",
+ "t'{x!s:'",
+ "t'{x:{;}}'",
+ ]
+ for source in invalid_cases:
+ with self.subTest(source=source), self.assertRaises(SyntaxError):
+ compile(source, "<bad-tstring-parser-context>", "eval")
+
+ with self.assertRaisesRegex(SyntaxError, "mapping pattern keys"):
+ compile(
+ textwrap.dedent(
+ """
+ match data:
+ case {t'{key}': value}:
+ pass
+ """
+ ),
+ "<bad-tstring-pattern>",
+ "exec",
+ )
+
+ def test_annotation_unparse_and_ast_validation_paths(self):
+ import textwrap
+
+ namespace = {}
+ exec(
+ textwrap.dedent(
+ """
+ from __future__ import annotations
+ value = 8
+ width = 4
+ a: t'{value!a}' = None
+ b: t'{value!s:{width}}' = None
+ c: t'{ {1: 2} }' = None
+ d: t'{value:{width}}' = None
+ e: f"{t'{value}'}" = None
+ """
+ ),
+ namespace,
+ )
+ annotations = namespace["__annotations__"]
+ for name in ("a", "b", "c", "d"):
+ with self.subTest(annotation=name):
+ self.assertIsInstance(eval(annotations[name], {"value": 8, "width": 4}), Template)
+ self.assertTrue(eval(annotations["e"], {"value": 8}).startswith("Template("))
+
+ def compile_expression(expr):
+ module = ast.Expression(expr)
+ ast.fix_missing_locations(module)
+ return compile(module, "<tstring-ast-validation>", "eval")
+
+ def fresh_template_and_interpolation():
+ expr = ast.parse('t"{value!r:{width}}"', mode="eval").body
+ interpolation = next(
+ value for value in expr.values
+ if type(value).__name__ == "Interpolation"
+ )
+ return expr, interpolation
+
+ expr, _ = fresh_template_and_interpolation()
+ expr.values = tuple(expr.values)
+ with self.assertRaisesRegex(TypeError, 'TemplateStr field "values" must be a list'):
+ compile_expression(expr)
+
+ expr, _ = fresh_template_and_interpolation()
+ delattr(expr, "values")
+ empty = eval(compile_expression(expr), {"value": 8, "width": 4})
+ self.assertIsInstance(empty, Template)
+ self.assertEqual(empty.values, ())
+
+ for attr, message in (
+ ("value", 'required field "value" missing from Interpolation'),
+ ("str", 'required field "str" missing from Interpolation'),
+ ("conversion", 'required field "conversion" missing from Interpolation'),
+ ):
+ expr, interpolation = fresh_template_and_interpolation()
+ delattr(interpolation, attr)
+ with self.subTest(attr=attr), self.assertRaisesRegex(TypeError, message):
+ compile_expression(expr)
+
+ for attr in ("value", "format_spec"):
+ expr, interpolation = fresh_template_and_interpolation()
+ setattr(interpolation, attr, "not an ast node")
+ with self.subTest(attr=attr), self.assertRaises(TypeError):
+ compile_expression(expr)
+
+ def test_public_parser_literal_and_invalid_grammar_matrix(self):
+ valid_exec_cases = [
+ "result = t'plain' t' {value}'",
+ "result = 'plain ' t'{value}'",
+ "result = f'plain {value}' t' {value}'",
+ "result = t'plain {value}' f' {value}'",
+ "def f(value=t'{1}', *, other=t'{2}', **kw):\n return t'{value}'",
+ "async def f(source):\n async for item in source:\n yield t'{item}'",
+ "def f(items):\n yield from (t'{item}' for item in items if t'{item}')",
+ "class C(Base, flag=t'{value}'):\n field = t'{value}'",
+ "@decorator(t'{value}', key=t'{value}')\ndef f():\n return t'{value}'",
+ "try:\n raise RuntimeError(t'{value}')\nexcept RuntimeError as exc:\n note = t'{exc}'\nelse:\n fallback = t'{value}'\nfinally:\n done = t'{value}'",
+ "match data:\n case [first, *rest] if t'{first}':\n result = t'{rest}'",
+ "assert t'{value}', t'{value}'",
+ "with cm(t'{value}') as first, cm(t'{value}') as second:\n result = t'{first}{second}'",
+ "result = {key: t'{value}' for key, value in pairs if t'{key}'}",
+ "result = {t'{item}' for item in values if t'{item}'}",
+ "result = [t'{item}' for item in values if t'{item}']",
+ "result = (t'{item}' for item in values if t'{item}')",
+ "result = func(*(t'{item}' for item in values), key=t'{value}', **{'extra': t'{value}'})",
+ ]
+ for source in valid_exec_cases:
+ with self.subTest(source=source):
+ compile(source, "<tstring-public-grammar>", "exec")
+
+ valid_eval_cases = [
+ "t'{value:{width}.{precision}}'",
+ "t'{value!s:{width}}'",
+ "t'{value:{other!r}}'",
+ "(t'{a}', t'{b}', t'{c}',)",
+ "{t'{key}': (t'{value}', f'{value}')}",
+ "(lambda value=t'{1}', /, other=t'{2}', *, key=t'{3}': t'{value}{other}{key}')",
+ "t'{value}' if t'{condition}' else t'{fallback}'",
+ ]
+ for source in valid_eval_cases:
+ with self.subTest(source=source):
+ compile(source, "<tstring-public-grammar>", "eval")
+
+ invalid_eval_cases = [
+ "f'{x!}'",
+ "f'{x!q}'",
+ "f'{x= q}'",
+ "f'{x:{!r}}'",
+ "f'{x:{y!}}'",
+ "f'{x:{y!q}}'",
+ "f'{x:{y;}}'",
+ "f'{x:{y}'",
+ "f'{x!r'",
+ "t'{!r}'",
+ "t'{:x}'",
+ "t'{}'",
+ "t'{x y}'",
+ "t'{x= y}'",
+ "t'{x!}'",
+ "t'{x!q}'",
+ "t'{x= !q}'",
+ "t'{x:{!r}}'",
+ "t'{x:{y!}}'",
+ "t'{x:{y!q}}'",
+ "t'{x:{y;}}'",
+ "t'{x:{y}'",
+ "t'{x!r'",
+ ]
+ for source in invalid_eval_cases:
+ with self.subTest(source=source), self.assertRaises(SyntaxError):
+ compile(source, "<bad-public-string-grammar>", "eval")
+
+ def test_public_token_opcode_reload_surface(self):
+ import importlib
+ import opcode
+ import token
+
+ importlib.reload(token)
+ importlib.reload(opcode)
+ importlib.reload(tokenize)
+
+ self.assertEqual(token.tok_name[token.TSTRING_START], "TSTRING_START")
+ self.assertEqual(token.tok_name[token.TSTRING_MIDDLE], "TSTRING_MIDDLE")
+ self.assertEqual(token.tok_name[token.TSTRING_END], "TSTRING_END")
+ self.assertIn("BUILD_TEMPLATE", opcode.opmap)
+ self.assertIn("BUILD_INTERPOLATION", opcode.opmap)
+
+ stream = io.StringIO('t"{{ {name!r:.3} }}"').readline
+ token_names = [token.tok_name[tok.type] for tok in tokenize.generate_tokens(stream)]
+ self.assertIn("TSTRING_START", token_names)
+ self.assertIn("TSTRING_MIDDLE", token_names)
+ self.assertIn("TSTRING_END", token_names)
+ self.assertEqual(tokenize.untokenize(tokenize.generate_tokens(io.StringIO('t"{name}"').readline)), 't"{name}"')
+
+ def test_public_parser_regression_modules(self):
+ import unittest
+
+ module_names = [
+ "test.test_fstring",
+ "test.test_syntax",
+ "test.test_compile",
+ "test.test_grammar",
+ ]
+ suite = unittest.defaultTestLoader.loadTestsFromNames(module_names)
+ stream = io.StringIO()
+ result = unittest.TextTestRunner(stream=stream, verbosity=0).run(suite)
+ if not result.wasSuccessful():
+ self.fail(stream.getvalue())
+ self.assertGreater(result.testsRun, 0)
+ self.assertGreaterEqual(len(result.skipped), 0)
+
+
+if __name__ == "__main__":
+ unittest.main()
|