Debian Codegraph @

Lib/test/test_string/test_templatelib.py

raw
1 import pickle
2 import unittest
3 from collections.abc import Iterator, Iterable
4 from string.templatelib import Template, Interpolation, convert
5
6 from test.test_string._support import TStringBaseCase, fstring
7
8
9 class TestTemplate(unittest.TestCase, TStringBaseCase):
10
11 def test_common(self):
12 self.assertEqual(type(t'').__name__, 'Template')
13 self.assertEqual(type(t'').__qualname__, 'Template')
14 self.assertEqual(type(t'').__module__, 'string.templatelib')
15
16 a = 'a'
17 i = t'{a}'.interpolations[0]
18 self.assertEqual(type(i).__name__, 'Interpolation')
19 self.assertEqual(type(i).__qualname__, 'Interpolation')
20 self.assertEqual(type(i).__module__, 'string.templatelib')
21
22 def test_final_types(self):
23 with self.assertRaisesRegex(TypeError, 'is not an acceptable base type'):
24 class Sub(Template): ...
25
26 with self.assertRaisesRegex(TypeError, 'is not an acceptable base type'):
27 class Sub(Interpolation): ...
28
29 def test_basic_creation(self):
30 # Simple t-string creation
31 t = t'Hello, world'
32 self.assertIsInstance(t, Template)
33 self.assertTStringEqual(t, ('Hello, world',), ())
34 self.assertEqual(fstring(t), 'Hello, world')
35
36 # Empty t-string
37 t = t''
38 self.assertTStringEqual(t, ('',), ())
39 self.assertEqual(fstring(t), '')
40
41 # Multi-line t-string
42 t = t"""Hello,
43 world"""
44 self.assertEqual(t.strings, ('Hello,\nworld',))
45 self.assertEqual(len(t.interpolations), 0)
46 self.assertEqual(fstring(t), 'Hello,\nworld')
47
48 def test_interpolation_creation(self):
49 i = Interpolation('Maria', 'name', 'a', 'fmt')
50 self.assertInterpolationEqual(i, ('Maria', 'name', 'a', 'fmt'))
51
52 i = Interpolation('Maria', 'name', 'a')
53 self.assertInterpolationEqual(i, ('Maria', 'name', 'a'))
54
55 i = Interpolation('Maria', 'name')
56 self.assertInterpolationEqual(i, ('Maria', 'name'))
57
58 i = Interpolation('Maria')
59 self.assertInterpolationEqual(i, ('Maria',))
60
61 def test_creation_interleaving(self):
62 # Should add strings on either side
63 t = Template(Interpolation('Maria', 'name', None, ''))
64 self.assertTStringEqual(t, ('', ''), [('Maria', 'name')])
65 self.assertEqual(fstring(t), 'Maria')
66
67 # Should prepend empty string
68 t = Template(Interpolation('Maria', 'name', None, ''), ' is my name')
69 self.assertTStringEqual(t, ('', ' is my name'), [('Maria', 'name')])
70 self.assertEqual(fstring(t), 'Maria is my name')
71
72 # Should append empty string
73 t = Template('Hello, ', Interpolation('Maria', 'name', None, ''))
74 self.assertTStringEqual(t, ('Hello, ', ''), [('Maria', 'name')])
75 self.assertEqual(fstring(t), 'Hello, Maria')
76
77 # Should concatenate strings
78 t = Template('Hello', ', ', Interpolation('Maria', 'name', None, ''),
79 '!')
80 self.assertTStringEqual(t, ('Hello, ', '!'), [('Maria', 'name')])
81 self.assertEqual(fstring(t), 'Hello, Maria!')
82
83 # Should add strings on either side and in between
84 t = Template(Interpolation('Maria', 'name', None, ''),
85 Interpolation('Python', 'language', None, ''))
86 self.assertTStringEqual(
87 t, ('', '', ''), [('Maria', 'name'), ('Python', 'language')]
88 )
89 self.assertEqual(fstring(t), 'MariaPython')
90
91 def test_template_values(self):
92 t = t'Hello, world'
93 self.assertEqual(t.values, ())
94
95 name = "Lys"
96 t = t'Hello, {name}'
97 self.assertEqual(t.values, ("Lys",))
98
99 country = "GR"
100 age = 0
101 t = t'Hello, {name}, {age} from {country}'
102 self.assertEqual(t.values, ("Lys", 0, "GR"))
103
104 def test_pickle_template(self):
105 user = 'test'
106 for template in (
107 t'',
108 t"No values",
109 t'With inter {user}',
110 t'With ! {user!r}',
111 t'With format {1 / 0.3:.2f}',
112 Template(),
113 Template('a'),
114 Template(Interpolation('Nikita', 'name', None, '')),
115 Template('a', Interpolation('Nikita', 'name', 'r', '')),
116 ):
117 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
118 with self.subTest(proto=proto, template=template):
119 pickled = pickle.dumps(template, protocol=proto)
120 unpickled = pickle.loads(pickled)
121
122 self.assertEqual(unpickled.values, template.values)
123 self.assertEqual(fstring(unpickled), fstring(template))
124
125 def test_pickle_interpolation(self):
126 for interpolation in (
127 Interpolation('Nikita', 'name', None, ''),
128 Interpolation('Nikita', 'name', 'r', ''),
129 Interpolation(1/3, 'x', None, '.2f'),
130 ):
131 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
132 with self.subTest(proto=proto, interpolation=interpolation):
133 pickled = pickle.dumps(interpolation, protocol=proto)
134 unpickled = pickle.loads(pickled)
135
136 self.assertEqual(unpickled.value, interpolation.value)
137 self.assertEqual(unpickled.expression, interpolation.expression)
138 self.assertEqual(unpickled.conversion, interpolation.conversion)
139 self.assertEqual(unpickled.format_spec, interpolation.format_spec)
140
141
142 class TemplateIterTests(unittest.TestCase):
143 def test_abc(self):
144 self.assertIsInstance(iter(t''), Iterable)
145 self.assertIsInstance(iter(t''), Iterator)
146
147 def test_final(self):
148 TemplateIter = type(iter(t''))
149 with self.assertRaisesRegex(TypeError, 'is not an acceptable base type'):
150 class Sub(TemplateIter): ...
151
152 def test_iter(self):
153 x = 1
154 res = list(iter(t'abc {x} yz'))
155
156 self.assertEqual(res[0], 'abc ')
157 self.assertIsInstance(res[1], Interpolation)
158 self.assertEqual(res[1].value, 1)
159 self.assertEqual(res[1].expression, 'x')
160 self.assertEqual(res[1].conversion, None)
161 self.assertEqual(res[1].format_spec, '')
162 self.assertEqual(res[2], ' yz')
163
164 def test_exhausted(self):
165 # See https://github.com/python/cpython/issues/134119.
166 template_iter = iter(t"{1}")
167 self.assertIsInstance(next(template_iter), Interpolation)
168 self.assertRaises(StopIteration, next, template_iter)
169 self.assertRaises(StopIteration, next, template_iter)
170
171
172 class TestFunctions(unittest.TestCase):
173 def test_convert(self):
174 from fractions import Fraction
175
176 for obj in ('Café', None, 3.14, Fraction(1, 2)):
177 with self.subTest(f'{obj=}'):
178 self.assertEqual(convert(obj, None), obj)
179 self.assertEqual(convert(obj, 's'), str(obj))
180 self.assertEqual(convert(obj, 'r'), repr(obj))
181 self.assertEqual(convert(obj, 'a'), ascii(obj))
182
183 # Invalid conversion specifier
184 with self.assertRaises(ValueError):
185 convert(obj, 'z')
186 with self.assertRaises(ValueError):
187 convert(obj, 1)
188 with self.assertRaises(ValueError):
189 convert(obj, object())
190
191
192 if __name__ == '__main__':
193 unittest.main()