Debian Codegraph @

Lib/test/test_string/_support.py

raw
1 import unittest
2 from string.templatelib import Interpolation
3
4
5 class TStringBaseCase:
6 def assertInterpolationEqual(self, i, exp):
7 """Test Interpolation equality.
8
9 The *i* argument must be an Interpolation instance.
10
11 The *exp* argument must be a tuple of the form
12 (value, expression, conversion, format_spec) where the final three
13 items may be omitted and are assumed to be '', None and '' respectively.
14 """
15 if len(exp) == 4:
16 actual = (i.value, i.expression, i.conversion, i.format_spec)
17 self.assertEqual(actual, exp)
18 elif len(exp) == 3:
19 self.assertEqual((i.value, i.expression, i.conversion), exp)
20 self.assertEqual(i.format_spec, "")
21 elif len(exp) == 2:
22 self.assertEqual((i.value, i.expression), exp)
23 self.assertEqual(i.conversion, None)
24 self.assertEqual(i.format_spec, "")
25 elif len(exp) == 1:
26 self.assertEqual((i.value,), exp)
27 self.assertEqual(i.expression, "")
28 self.assertEqual(i.conversion, None)
29 self.assertEqual(i.format_spec, "")
30
31 def assertTStringEqual(self, t, strings, interpolations):
32 """Test template string literal equality.
33
34 The *strings* argument must be a tuple of strings equal to *t.strings*.
35
36 The *interpolations* argument must be a sequence of tuples which are
37 compared against *t.interpolations*. Each tuple must match the form
38 described in the `assertInterpolationEqual` method.
39 """
40 self.assertEqual(t.strings, strings)
41 self.assertEqual(len(t.interpolations), len(interpolations))
42
43 for i, exp in zip(t.interpolations, interpolations, strict=True):
44 self.assertInterpolationEqual(i, exp)
45
46
47 def convert(value, conversion):
48 if conversion == "a":
49 return ascii(value)
50 elif conversion == "r":
51 return repr(value)
52 elif conversion == "s":
53 return str(value)
54 return value
55
56
57 def fstring(template):
58 parts = []
59 for item in template:
60 match item:
61 case str() as s:
62 parts.append(s)
63 case Interpolation(value, _, conversion, format_spec):
64 value = convert(value, conversion)
65 value = format(value, format_spec)
66 parts.append(value)
67 return "".join(parts)