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, "", "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, "", "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, "", "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, "", "eval") + + with self.assertRaisesRegex(SyntaxError, "mapping pattern keys"): + compile( + textwrap.dedent( + """ + match data: + case {t'{key}': value}: + pass + """ + ), + "", + "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, "", "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, "", "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, "", "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, "", "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()