Debian Codegraph @

Lib/test/test_tstring.py

raw
1 import unittest
2
3 from test.test_string._support import TStringBaseCase, fstring
4
5
6 class TestTString(unittest.TestCase, TStringBaseCase):
7 def test_string_representation(self):
8 # Test __repr__
9 t = t"Hello"
10 self.assertEqual(repr(t), "Template(strings=('Hello',), interpolations=())")
11
12 name = "Python"
13 t = t"Hello, {name}"
14 self.assertEqual(repr(t),
15 "Template(strings=('Hello, ', ''), "
16 "interpolations=(Interpolation('Python', 'name', None, ''),))"
17 )
18
19 def test_interpolation_basics(self):
20 # Test basic interpolation
21 name = "Python"
22 t = t"Hello, {name}"
23 self.assertTStringEqual(t, ("Hello, ", ""), [(name, "name")])
24 self.assertEqual(fstring(t), "Hello, Python")
25
26 # Multiple interpolations
27 first = "Python"
28 last = "Developer"
29 t = t"{first} {last}"
30 self.assertTStringEqual(
31 t, ("", " ", ""), [(first, 'first'), (last, 'last')]
32 )
33 self.assertEqual(fstring(t), "Python Developer")
34
35 # Interpolation with expressions
36 a = 10
37 b = 20
38 t = t"Sum: {a + b}"
39 self.assertTStringEqual(t, ("Sum: ", ""), [(a + b, "a + b")])
40 self.assertEqual(fstring(t), "Sum: 30")
41
42 # Interpolation with function
43 def square(x):
44 return x * x
45 t = t"Square: {square(5)}"
46 self.assertTStringEqual(
47 t, ("Square: ", ""), [(square(5), "square(5)")]
48 )
49 self.assertEqual(fstring(t), "Square: 25")
50
51 # Test attribute access in expressions
52 class Person:
53 def __init__(self, name):
54 self.name = name
55
56 def upper(self):
57 return self.name.upper()
58
59 person = Person("Alice")
60 t = t"Name: {person.name}"
61 self.assertTStringEqual(
62 t, ("Name: ", ""), [(person.name, "person.name")]
63 )
64 self.assertEqual(fstring(t), "Name: Alice")
65
66 # Test method calls
67 t = t"Name: {person.upper()}"
68 self.assertTStringEqual(
69 t, ("Name: ", ""), [(person.upper(), "person.upper()")]
70 )
71 self.assertEqual(fstring(t), "Name: ALICE")
72
73 # Test dictionary access
74 data = {"name": "Bob", "age": 30}
75 t = t"Name: {data['name']}, Age: {data['age']}"
76 self.assertTStringEqual(
77 t, ("Name: ", ", Age: ", ""),
78 [(data["name"], "data['name']"), (data["age"], "data['age']")],
79 )
80 self.assertEqual(fstring(t), "Name: Bob, Age: 30")
81
82 def test_format_specifiers(self):
83 # Test basic format specifiers
84 value = 3.14159
85 t = t"Pi: {value:.2f}"
86 self.assertTStringEqual(
87 t, ("Pi: ", ""), [(value, "value", None, ".2f")]
88 )
89 self.assertEqual(fstring(t), "Pi: 3.14")
90
91 def test_conversions(self):
92 # Test !s conversion (str)
93 obj = object()
94 t = t"Object: {obj!s}"
95 self.assertTStringEqual(t, ("Object: ", ""), [(obj, "obj", "s")])
96 self.assertEqual(fstring(t), f"Object: {str(obj)}")
97
98 # Test !r conversion (repr)
99 t = t"Data: {obj!r}"
100 self.assertTStringEqual(t, ("Data: ", ""), [(obj, "obj", "r")])
101 self.assertEqual(fstring(t), f"Data: {repr(obj)}")
102
103 # Test !a conversion (ascii)
104 text = "Café"
105 t = t"ASCII: {text!a}"
106 self.assertTStringEqual(t, ("ASCII: ", ""), [(text, "text", "a")])
107 self.assertEqual(fstring(t), f"ASCII: {ascii(text)}")
108
109 # Test !z conversion (error)
110 num = 1
111 with self.assertRaises(SyntaxError):
112 eval("t'{num!z}'")
113
114 def test_debug_specifier(self):
115 # Test debug specifier
116 value = 42
117 t = t"Value: {value=}"
118 self.assertTStringEqual(
119 t, ("Value: value=", ""), [(value, "value", "r")]
120 )
121 self.assertEqual(fstring(t), "Value: value=42")
122
123 # Test debug specifier with format (conversion default to !r)
124 t = t"Value: {value=:.2f}"
125 self.assertTStringEqual(
126 t, ("Value: value=", ""), [(value, "value", None, ".2f")]
127 )
128 self.assertEqual(fstring(t), "Value: value=42.00")
129
130 # Test debug specifier with conversion
131 t = t"Value: {value=!s}"
132 self.assertTStringEqual(
133 t, ("Value: value=", ""), [(value, "value", "s")]
134 )
135
136 # Test white space in debug specifier
137 t = t"Value: {value = }"
138 self.assertTStringEqual(
139 t, ("Value: value = ", ""), [(value, "value", "r")]
140 )
141 self.assertEqual(fstring(t), "Value: value = 42")
142
143 def test_raw_tstrings(self):
144 path = r"C:\Users"
145 t = rt"{path}\Documents"
146 self.assertTStringEqual(t, ("", r"\Documents"), [(path, "path")])
147 self.assertEqual(fstring(t), r"C:\Users\Documents")
148
149 # Test alternative prefix
150 t = tr"{path}\Documents"
151 self.assertTStringEqual(t, ("", r"\Documents"), [(path, "path")])
152
153 def test_template_concatenation(self):
154 # Test template + template
155 t1 = t"Hello, "
156 t2 = t"world"
157 combined = t1 + t2
158 self.assertTStringEqual(combined, ("Hello, world",), ())
159 self.assertEqual(fstring(combined), "Hello, world")
160
161 # Test template + string
162 t1 = t"Hello"
163 expected_msg = 'can only concatenate string.templatelib.Template ' \
164 '\\(not "str"\\) to string.templatelib.Template'
165 with self.assertRaisesRegex(TypeError, expected_msg):
166 t1 + ", world"
167
168 # Test template + template with interpolation
169 name = "Python"
170 t1 = t"Hello, "
171 t2 = t"{name}"
172 combined = t1 + t2
173 self.assertTStringEqual(combined, ("Hello, ", ""), [(name, "name")])
174 self.assertEqual(fstring(combined), "Hello, Python")
175
176 # Test string + template
177 expected_msg = 'can only concatenate str ' \
178 '\\(not "string.templatelib.Template"\\) to str'
179 with self.assertRaisesRegex(TypeError, expected_msg):
180 "Hello, " + t"{name}"
181
182 def test_nested_templates(self):
183 # Test a template inside another template expression
184 name = "Python"
185 inner = t"{name}"
186 t = t"Language: {inner}"
187
188 t_interp = t.interpolations[0]
189 self.assertEqual(t.strings, ("Language: ", ""))
190 self.assertEqual(t_interp.value.strings, ("", ""))
191 self.assertEqual(t_interp.value.interpolations[0].value, name)
192 self.assertEqual(t_interp.value.interpolations[0].expression, "name")
193 self.assertEqual(t_interp.value.interpolations[0].conversion, None)
194 self.assertEqual(t_interp.value.interpolations[0].format_spec, "")
195 self.assertEqual(t_interp.expression, "inner")
196 self.assertEqual(t_interp.conversion, None)
197 self.assertEqual(t_interp.format_spec, "")
198
199 def test_syntax_errors(self):
200 for case, err in (
201 ("t'", "unterminated t-string literal"),
202 ("t'''", "unterminated triple-quoted t-string literal"),
203 ("t''''", "unterminated triple-quoted t-string literal"),
204 ("t'{", "'{' was never closed"),
205 ("t'{'", "t-string: expecting '}'"),
206 ("t'{a'", "t-string: expecting '}'"),
207 ("t'}'", "t-string: single '}' is not allowed"),
208 ("t'{}'", "t-string: valid expression required before '}'"),
209 ("t'{=x}'", "t-string: valid expression required before '='"),
210 ("t'{!x}'", "t-string: valid expression required before '!'"),
211 ("t'{:x}'", "t-string: valid expression required before ':'"),
212 ("t'{x;y}'", "t-string: expecting '=', or '!', or ':', or '}'"),
213 ("t'{x=y}'", "t-string: expecting '!', or ':', or '}'"),
214 ("t'{x!s!}'", "t-string: expecting ':' or '}'"),
215 ("t'{x!s:'", "t-string: expecting '}', or format specs"),
216 ("t'{x!}'", "t-string: missing conversion character"),
217 ("t'{x=!}'", "t-string: missing conversion character"),
218 ("t'{x!z}'", "t-string: invalid conversion character 'z': "
219 "expected 's', 'r', or 'a'"),
220 ("t'{lambda:1}'", "t-string: lambda expressions are not allowed "
221 "without parentheses"),
222 ("t'{x:{;}}'", "t-string: expecting a valid expression after '{'"),
223 ("t'{1:d\n}'", "t-string: newlines are not allowed in format specifiers")
224 ):
225 with self.subTest(case), self.assertRaisesRegex(SyntaxError, err):
226 eval(case)
227
228 def test_runtime_errors(self):
229 # Test missing variables
230 with self.assertRaises(NameError):
231 eval("t'Hello, {name}'")
232
233 def test_literal_concatenation(self):
234 # Test concatenation of t-string literals
235 t = t"Hello, " t"world"
236 self.assertTStringEqual(t, ("Hello, world",), ())
237 self.assertEqual(fstring(t), "Hello, world")
238
239 # Test concatenation with interpolation
240 name = "Python"
241 t = t"Hello, " t"{name}"
242 self.assertTStringEqual(t, ("Hello, ", ""), [(name, "name")])
243 self.assertEqual(fstring(t), "Hello, Python")
244
245 # Test disallowed mix of t-string and string/f-string (incl. bytes)
246 what = 't'
247 expected_msg = 'cannot mix t-string literals with string or bytes literals'
248 for case in (
249 "t'{what}-string literal' 'str literal'",
250 "t'{what}-string literal' u'unicode literal'",
251 "t'{what}-string literal' f'f-string literal'",
252 "t'{what}-string literal' r'raw string literal'",
253 "t'{what}-string literal' rf'raw f-string literal'",
254 "t'{what}-string literal' b'bytes literal'",
255 "t'{what}-string literal' br'raw bytes literal'",
256 "'str literal' t'{what}-string literal'",
257 "u'unicode literal' t'{what}-string literal'",
258 "f'f-string literal' t'{what}-string literal'",
259 "r'raw string literal' t'{what}-string literal'",
260 "rf'raw f-string literal' t'{what}-string literal'",
261 "b'bytes literal' t'{what}-string literal'",
262 "br'raw bytes literal' t'{what}-string literal'",
263 ):
264 with self.subTest(case):
265 with self.assertRaisesRegex(SyntaxError, expected_msg):
266 eval(case)
267
268 def test_triple_quoted(self):
269 # Test triple-quoted t-strings
270 t = t"""
271 Hello,
272 world
273 """
274 self.assertTStringEqual(
275 t, ("\n Hello,\n world\n ",), ()
276 )
277 self.assertEqual(fstring(t), "\n Hello,\n world\n ")
278
279 # Test triple-quoted with interpolation
280 name = "Python"
281 t = t"""
282 Hello,
283 {name}
284 """
285 self.assertTStringEqual(
286 t, ("\n Hello,\n ", "\n "), [(name, "name")]
287 )
288 self.assertEqual(fstring(t), "\n Hello,\n Python\n ")
289
290 if __name__ == '__main__':
291 unittest.main()