ยปCore Development>Code coverage>Lib/test/test_string.py

Python code coverage for Lib/test/test_string.py

#countcontent
1n/aimport unittest
2n/aimport string
3n/afrom string import Template
4n/a
5n/a
6n/aclass ModuleTest(unittest.TestCase):
7n/a
8n/a def test_attrs(self):
9n/a # While the exact order of the items in these attributes is not
10n/a # technically part of the "language spec", in practice there is almost
11n/a # certainly user code that depends on the order, so de-facto it *is*
12n/a # part of the spec.
13n/a self.assertEqual(string.whitespace, ' \t\n\r\x0b\x0c')
14n/a self.assertEqual(string.ascii_lowercase, 'abcdefghijklmnopqrstuvwxyz')
15n/a self.assertEqual(string.ascii_uppercase, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
16n/a self.assertEqual(string.ascii_letters, string.ascii_lowercase + string.ascii_uppercase)
17n/a self.assertEqual(string.digits, '0123456789')
18n/a self.assertEqual(string.hexdigits, string.digits + 'abcdefABCDEF')
19n/a self.assertEqual(string.octdigits, '01234567')
20n/a self.assertEqual(string.punctuation, '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
21n/a self.assertEqual(string.printable, string.digits + string.ascii_lowercase + string.ascii_uppercase + string.punctuation + string.whitespace)
22n/a
23n/a def test_capwords(self):
24n/a self.assertEqual(string.capwords('abc def ghi'), 'Abc Def Ghi')
25n/a self.assertEqual(string.capwords('abc\tdef\nghi'), 'Abc Def Ghi')
26n/a self.assertEqual(string.capwords('abc\t def \nghi'), 'Abc Def Ghi')
27n/a self.assertEqual(string.capwords('ABC DEF GHI'), 'Abc Def Ghi')
28n/a self.assertEqual(string.capwords('ABC-DEF-GHI', '-'), 'Abc-Def-Ghi')
29n/a self.assertEqual(string.capwords('ABC-def DEF-ghi GHI'), 'Abc-def Def-ghi Ghi')
30n/a self.assertEqual(string.capwords(' aBc DeF '), 'Abc Def')
31n/a self.assertEqual(string.capwords('\taBc\tDeF\t'), 'Abc Def')
32n/a self.assertEqual(string.capwords('\taBc\tDeF\t', '\t'), '\tAbc\tDef\t')
33n/a
34n/a def test_basic_formatter(self):
35n/a fmt = string.Formatter()
36n/a self.assertEqual(fmt.format("foo"), "foo")
37n/a self.assertEqual(fmt.format("foo{0}", "bar"), "foobar")
38n/a self.assertEqual(fmt.format("foo{1}{0}-{1}", "bar", 6), "foo6bar-6")
39n/a self.assertRaises(TypeError, fmt.format)
40n/a self.assertRaises(TypeError, string.Formatter.format)
41n/a
42n/a def test_format_keyword_arguments(self):
43n/a fmt = string.Formatter()
44n/a self.assertEqual(fmt.format("-{arg}-", arg='test'), '-test-')
45n/a self.assertRaises(KeyError, fmt.format, "-{arg}-")
46n/a self.assertEqual(fmt.format("-{self}-", self='test'), '-test-')
47n/a self.assertRaises(KeyError, fmt.format, "-{self}-")
48n/a self.assertEqual(fmt.format("-{format_string}-", format_string='test'),
49n/a '-test-')
50n/a self.assertRaises(KeyError, fmt.format, "-{format_string}-")
51n/a with self.assertRaisesRegex(TypeError, "format_string"):
52n/a fmt.format(format_string="-{arg}-", arg='test')
53n/a
54n/a def test_auto_numbering(self):
55n/a fmt = string.Formatter()
56n/a self.assertEqual(fmt.format('foo{}{}', 'bar', 6),
57n/a 'foo{}{}'.format('bar', 6))
58n/a self.assertEqual(fmt.format('foo{1}{num}{1}', None, 'bar', num=6),
59n/a 'foo{1}{num}{1}'.format(None, 'bar', num=6))
60n/a self.assertEqual(fmt.format('{:^{}}', 'bar', 6),
61n/a '{:^{}}'.format('bar', 6))
62n/a self.assertEqual(fmt.format('{:^{}} {}', 'bar', 6, 'X'),
63n/a '{:^{}} {}'.format('bar', 6, 'X'))
64n/a self.assertEqual(fmt.format('{:^{pad}}{}', 'foo', 'bar', pad=6),
65n/a '{:^{pad}}{}'.format('foo', 'bar', pad=6))
66n/a
67n/a with self.assertRaises(ValueError):
68n/a fmt.format('foo{1}{}', 'bar', 6)
69n/a
70n/a with self.assertRaises(ValueError):
71n/a fmt.format('foo{}{1}', 'bar', 6)
72n/a
73n/a def test_conversion_specifiers(self):
74n/a fmt = string.Formatter()
75n/a self.assertEqual(fmt.format("-{arg!r}-", arg='test'), "-'test'-")
76n/a self.assertEqual(fmt.format("{0!s}", 'test'), 'test')
77n/a self.assertRaises(ValueError, fmt.format, "{0!h}", 'test')
78n/a # issue13579
79n/a self.assertEqual(fmt.format("{0!a}", 42), '42')
80n/a self.assertEqual(fmt.format("{0!a}", string.ascii_letters),
81n/a "'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'")
82n/a self.assertEqual(fmt.format("{0!a}", chr(255)), "'\\xff'")
83n/a self.assertEqual(fmt.format("{0!a}", chr(256)), "'\\u0100'")
84n/a
85n/a def test_name_lookup(self):
86n/a fmt = string.Formatter()
87n/a class AnyAttr:
88n/a def __getattr__(self, attr):
89n/a return attr
90n/a x = AnyAttr()
91n/a self.assertEqual(fmt.format("{0.lumber}{0.jack}", x), 'lumberjack')
92n/a with self.assertRaises(AttributeError):
93n/a fmt.format("{0.lumber}{0.jack}", '')
94n/a
95n/a def test_index_lookup(self):
96n/a fmt = string.Formatter()
97n/a lookup = ["eggs", "and", "spam"]
98n/a self.assertEqual(fmt.format("{0[2]}{0[0]}", lookup), 'spameggs')
99n/a with self.assertRaises(IndexError):
100n/a fmt.format("{0[2]}{0[0]}", [])
101n/a with self.assertRaises(KeyError):
102n/a fmt.format("{0[2]}{0[0]}", {})
103n/a
104n/a def test_override_get_value(self):
105n/a class NamespaceFormatter(string.Formatter):
106n/a def __init__(self, namespace={}):
107n/a string.Formatter.__init__(self)
108n/a self.namespace = namespace
109n/a
110n/a def get_value(self, key, args, kwds):
111n/a if isinstance(key, str):
112n/a try:
113n/a # Check explicitly passed arguments first
114n/a return kwds[key]
115n/a except KeyError:
116n/a return self.namespace[key]
117n/a else:
118n/a string.Formatter.get_value(key, args, kwds)
119n/a
120n/a fmt = NamespaceFormatter({'greeting':'hello'})
121n/a self.assertEqual(fmt.format("{greeting}, world!"), 'hello, world!')
122n/a
123n/a
124n/a def test_override_format_field(self):
125n/a class CallFormatter(string.Formatter):
126n/a def format_field(self, value, format_spec):
127n/a return format(value(), format_spec)
128n/a
129n/a fmt = CallFormatter()
130n/a self.assertEqual(fmt.format('*{0}*', lambda : 'result'), '*result*')
131n/a
132n/a
133n/a def test_override_convert_field(self):
134n/a class XFormatter(string.Formatter):
135n/a def convert_field(self, value, conversion):
136n/a if conversion == 'x':
137n/a return None
138n/a return super().convert_field(value, conversion)
139n/a
140n/a fmt = XFormatter()
141n/a self.assertEqual(fmt.format("{0!r}:{0!x}", 'foo', 'foo'), "'foo':None")
142n/a
143n/a
144n/a def test_override_parse(self):
145n/a class BarFormatter(string.Formatter):
146n/a # returns an iterable that contains tuples of the form:
147n/a # (literal_text, field_name, format_spec, conversion)
148n/a def parse(self, format_string):
149n/a for field in format_string.split('|'):
150n/a if field[0] == '+':
151n/a # it's markup
152n/a field_name, _, format_spec = field[1:].partition(':')
153n/a yield '', field_name, format_spec, None
154n/a else:
155n/a yield field, None, None, None
156n/a
157n/a fmt = BarFormatter()
158n/a self.assertEqual(fmt.format('*|+0:^10s|*', 'foo'), '* foo *')
159n/a
160n/a def test_check_unused_args(self):
161n/a class CheckAllUsedFormatter(string.Formatter):
162n/a def check_unused_args(self, used_args, args, kwargs):
163n/a # Track which arguments actually got used
164n/a unused_args = set(kwargs.keys())
165n/a unused_args.update(range(0, len(args)))
166n/a
167n/a for arg in used_args:
168n/a unused_args.remove(arg)
169n/a
170n/a if unused_args:
171n/a raise ValueError("unused arguments")
172n/a
173n/a fmt = CheckAllUsedFormatter()
174n/a self.assertEqual(fmt.format("{0}", 10), "10")
175n/a self.assertEqual(fmt.format("{0}{i}", 10, i=100), "10100")
176n/a self.assertEqual(fmt.format("{0}{i}{1}", 10, 20, i=100), "1010020")
177n/a self.assertRaises(ValueError, fmt.format, "{0}{i}{1}", 10, 20, i=100, j=0)
178n/a self.assertRaises(ValueError, fmt.format, "{0}", 10, 20)
179n/a self.assertRaises(ValueError, fmt.format, "{0}", 10, 20, i=100)
180n/a self.assertRaises(ValueError, fmt.format, "{i}", 10, 20, i=100)
181n/a
182n/a def test_vformat_recursion_limit(self):
183n/a fmt = string.Formatter()
184n/a args = ()
185n/a kwargs = dict(i=100)
186n/a with self.assertRaises(ValueError) as err:
187n/a fmt._vformat("{i}", args, kwargs, set(), -1)
188n/a self.assertIn("recursion", str(err.exception))
189n/a
190n/a
191n/a# Template tests (formerly housed in test_pep292.py)
192n/a
193n/aclass Bag:
194n/a pass
195n/a
196n/aclass Mapping:
197n/a def __getitem__(self, name):
198n/a obj = self
199n/a for part in name.split('.'):
200n/a try:
201n/a obj = getattr(obj, part)
202n/a except AttributeError:
203n/a raise KeyError(name)
204n/a return obj
205n/a
206n/a
207n/aclass TestTemplate(unittest.TestCase):
208n/a def test_regular_templates(self):
209n/a s = Template('$who likes to eat a bag of $what worth $$100')
210n/a self.assertEqual(s.substitute(dict(who='tim', what='ham')),
211n/a 'tim likes to eat a bag of ham worth $100')
212n/a self.assertRaises(KeyError, s.substitute, dict(who='tim'))
213n/a self.assertRaises(TypeError, Template.substitute)
214n/a
215n/a def test_regular_templates_with_braces(self):
216n/a s = Template('$who likes ${what} for ${meal}')
217n/a d = dict(who='tim', what='ham', meal='dinner')
218n/a self.assertEqual(s.substitute(d), 'tim likes ham for dinner')
219n/a self.assertRaises(KeyError, s.substitute,
220n/a dict(who='tim', what='ham'))
221n/a
222n/a def test_escapes(self):
223n/a eq = self.assertEqual
224n/a s = Template('$who likes to eat a bag of $$what worth $$100')
225n/a eq(s.substitute(dict(who='tim', what='ham')),
226n/a 'tim likes to eat a bag of $what worth $100')
227n/a s = Template('$who likes $$')
228n/a eq(s.substitute(dict(who='tim', what='ham')), 'tim likes $')
229n/a
230n/a def test_percents(self):
231n/a eq = self.assertEqual
232n/a s = Template('%(foo)s $foo ${foo}')
233n/a d = dict(foo='baz')
234n/a eq(s.substitute(d), '%(foo)s baz baz')
235n/a eq(s.safe_substitute(d), '%(foo)s baz baz')
236n/a
237n/a def test_stringification(self):
238n/a eq = self.assertEqual
239n/a s = Template('tim has eaten $count bags of ham today')
240n/a d = dict(count=7)
241n/a eq(s.substitute(d), 'tim has eaten 7 bags of ham today')
242n/a eq(s.safe_substitute(d), 'tim has eaten 7 bags of ham today')
243n/a s = Template('tim has eaten ${count} bags of ham today')
244n/a eq(s.substitute(d), 'tim has eaten 7 bags of ham today')
245n/a
246n/a def test_tupleargs(self):
247n/a eq = self.assertEqual
248n/a s = Template('$who ate ${meal}')
249n/a d = dict(who=('tim', 'fred'), meal=('ham', 'kung pao'))
250n/a eq(s.substitute(d), "('tim', 'fred') ate ('ham', 'kung pao')")
251n/a eq(s.safe_substitute(d), "('tim', 'fred') ate ('ham', 'kung pao')")
252n/a
253n/a def test_SafeTemplate(self):
254n/a eq = self.assertEqual
255n/a s = Template('$who likes ${what} for ${meal}')
256n/a eq(s.safe_substitute(dict(who='tim')), 'tim likes ${what} for ${meal}')
257n/a eq(s.safe_substitute(dict(what='ham')), '$who likes ham for ${meal}')
258n/a eq(s.safe_substitute(dict(what='ham', meal='dinner')),
259n/a '$who likes ham for dinner')
260n/a eq(s.safe_substitute(dict(who='tim', what='ham')),
261n/a 'tim likes ham for ${meal}')
262n/a eq(s.safe_substitute(dict(who='tim', what='ham', meal='dinner')),
263n/a 'tim likes ham for dinner')
264n/a
265n/a def test_invalid_placeholders(self):
266n/a raises = self.assertRaises
267n/a s = Template('$who likes $')
268n/a raises(ValueError, s.substitute, dict(who='tim'))
269n/a s = Template('$who likes ${what)')
270n/a raises(ValueError, s.substitute, dict(who='tim'))
271n/a s = Template('$who likes $100')
272n/a raises(ValueError, s.substitute, dict(who='tim'))
273n/a
274n/a def test_idpattern_override(self):
275n/a class PathPattern(Template):
276n/a idpattern = r'[_a-z][._a-z0-9]*'
277n/a m = Mapping()
278n/a m.bag = Bag()
279n/a m.bag.foo = Bag()
280n/a m.bag.foo.who = 'tim'
281n/a m.bag.what = 'ham'
282n/a s = PathPattern('$bag.foo.who likes to eat a bag of $bag.what')
283n/a self.assertEqual(s.substitute(m), 'tim likes to eat a bag of ham')
284n/a
285n/a def test_pattern_override(self):
286n/a class MyPattern(Template):
287n/a pattern = r"""
288n/a (?P<escaped>@{2}) |
289n/a @(?P<named>[_a-z][._a-z0-9]*) |
290n/a @{(?P<braced>[_a-z][._a-z0-9]*)} |
291n/a (?P<invalid>@)
292n/a """
293n/a m = Mapping()
294n/a m.bag = Bag()
295n/a m.bag.foo = Bag()
296n/a m.bag.foo.who = 'tim'
297n/a m.bag.what = 'ham'
298n/a s = MyPattern('@bag.foo.who likes to eat a bag of @bag.what')
299n/a self.assertEqual(s.substitute(m), 'tim likes to eat a bag of ham')
300n/a
301n/a class BadPattern(Template):
302n/a pattern = r"""
303n/a (?P<badname>.*) |
304n/a (?P<escaped>@{2}) |
305n/a @(?P<named>[_a-z][._a-z0-9]*) |
306n/a @{(?P<braced>[_a-z][._a-z0-9]*)} |
307n/a (?P<invalid>@) |
308n/a """
309n/a s = BadPattern('@bag.foo.who likes to eat a bag of @bag.what')
310n/a self.assertRaises(ValueError, s.substitute, {})
311n/a self.assertRaises(ValueError, s.safe_substitute, {})
312n/a
313n/a def test_braced_override(self):
314n/a class MyTemplate(Template):
315n/a pattern = r"""
316n/a \$(?:
317n/a (?P<escaped>$) |
318n/a (?P<named>[_a-z][_a-z0-9]*) |
319n/a @@(?P<braced>[_a-z][_a-z0-9]*)@@ |
320n/a (?P<invalid>) |
321n/a )
322n/a """
323n/a
324n/a tmpl = 'PyCon in $@@location@@'
325n/a t = MyTemplate(tmpl)
326n/a self.assertRaises(KeyError, t.substitute, {})
327n/a val = t.substitute({'location': 'Cleveland'})
328n/a self.assertEqual(val, 'PyCon in Cleveland')
329n/a
330n/a def test_braced_override_safe(self):
331n/a class MyTemplate(Template):
332n/a pattern = r"""
333n/a \$(?:
334n/a (?P<escaped>$) |
335n/a (?P<named>[_a-z][_a-z0-9]*) |
336n/a @@(?P<braced>[_a-z][_a-z0-9]*)@@ |
337n/a (?P<invalid>) |
338n/a )
339n/a """
340n/a
341n/a tmpl = 'PyCon in $@@location@@'
342n/a t = MyTemplate(tmpl)
343n/a self.assertEqual(t.safe_substitute(), tmpl)
344n/a val = t.safe_substitute({'location': 'Cleveland'})
345n/a self.assertEqual(val, 'PyCon in Cleveland')
346n/a
347n/a def test_invalid_with_no_lines(self):
348n/a # The error formatting for invalid templates
349n/a # has a special case for no data that the default
350n/a # pattern can't trigger (always has at least '$')
351n/a # So we craft a pattern that is always invalid
352n/a # with no leading data.
353n/a class MyTemplate(Template):
354n/a pattern = r"""
355n/a (?P<invalid>) |
356n/a unreachable(
357n/a (?P<named>) |
358n/a (?P<braced>) |
359n/a (?P<escaped>)
360n/a )
361n/a """
362n/a s = MyTemplate('')
363n/a with self.assertRaises(ValueError) as err:
364n/a s.substitute({})
365n/a self.assertIn('line 1, col 1', str(err.exception))
366n/a
367n/a def test_unicode_values(self):
368n/a s = Template('$who likes $what')
369n/a d = dict(who='t\xffm', what='f\xfe\fed')
370n/a self.assertEqual(s.substitute(d), 't\xffm likes f\xfe\x0ced')
371n/a
372n/a def test_keyword_arguments(self):
373n/a eq = self.assertEqual
374n/a s = Template('$who likes $what')
375n/a eq(s.substitute(who='tim', what='ham'), 'tim likes ham')
376n/a eq(s.substitute(dict(who='tim'), what='ham'), 'tim likes ham')
377n/a eq(s.substitute(dict(who='fred', what='kung pao'),
378n/a who='tim', what='ham'),
379n/a 'tim likes ham')
380n/a s = Template('the mapping is $mapping')
381n/a eq(s.substitute(dict(foo='none'), mapping='bozo'),
382n/a 'the mapping is bozo')
383n/a eq(s.substitute(dict(mapping='one'), mapping='two'),
384n/a 'the mapping is two')
385n/a
386n/a s = Template('the self is $self')
387n/a eq(s.substitute(self='bozo'), 'the self is bozo')
388n/a
389n/a def test_keyword_arguments_safe(self):
390n/a eq = self.assertEqual
391n/a raises = self.assertRaises
392n/a s = Template('$who likes $what')
393n/a eq(s.safe_substitute(who='tim', what='ham'), 'tim likes ham')
394n/a eq(s.safe_substitute(dict(who='tim'), what='ham'), 'tim likes ham')
395n/a eq(s.safe_substitute(dict(who='fred', what='kung pao'),
396n/a who='tim', what='ham'),
397n/a 'tim likes ham')
398n/a s = Template('the mapping is $mapping')
399n/a eq(s.safe_substitute(dict(foo='none'), mapping='bozo'),
400n/a 'the mapping is bozo')
401n/a eq(s.safe_substitute(dict(mapping='one'), mapping='two'),
402n/a 'the mapping is two')
403n/a d = dict(mapping='one')
404n/a raises(TypeError, s.substitute, d, {})
405n/a raises(TypeError, s.safe_substitute, d, {})
406n/a
407n/a s = Template('the self is $self')
408n/a eq(s.safe_substitute(self='bozo'), 'the self is bozo')
409n/a
410n/a def test_delimiter_override(self):
411n/a eq = self.assertEqual
412n/a raises = self.assertRaises
413n/a class AmpersandTemplate(Template):
414n/a delimiter = '&'
415n/a s = AmpersandTemplate('this &gift is for &{who} &&')
416n/a eq(s.substitute(gift='bud', who='you'), 'this bud is for you &')
417n/a raises(KeyError, s.substitute)
418n/a eq(s.safe_substitute(gift='bud', who='you'), 'this bud is for you &')
419n/a eq(s.safe_substitute(), 'this &gift is for &{who} &')
420n/a s = AmpersandTemplate('this &gift is for &{who} &')
421n/a raises(ValueError, s.substitute, dict(gift='bud', who='you'))
422n/a eq(s.safe_substitute(), 'this &gift is for &{who} &')
423n/a
424n/a class PieDelims(Template):
425n/a delimiter = '@'
426n/a s = PieDelims('@who likes to eat a bag of @{what} worth $100')
427n/a self.assertEqual(s.substitute(dict(who='tim', what='ham')),
428n/a 'tim likes to eat a bag of ham worth $100')
429n/a
430n/a
431n/aif __name__ == '__main__':
432n/a unittest.main()