blob: 0cd2b86217956c09a3f2284c467d0298e3df2638 [file] [log] [blame]
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001import unittest, string
Walter Dörwald0fd583c2003-02-21 12:53:50 +00002
Raymond Hettinger674f2412004-08-23 23:23:54 +00003
Walter Dörwald0fd583c2003-02-21 12:53:50 +00004class ModuleTest(unittest.TestCase):
5
6 def test_attrs(self):
R David Murray0a8f43e2015-04-13 20:04:29 -04007 # While the exact order of the items in these attributes is not
8 # technically part of the "language spec", in practice there is almost
9 # certainly user code that depends on the order, so de-facto it *is*
10 # part of the spec.
11 self.assertEqual(string.whitespace, ' \t\n\r\x0b\x0c')
12 self.assertEqual(string.ascii_lowercase, 'abcdefghijklmnopqrstuvwxyz')
13 self.assertEqual(string.ascii_uppercase, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
14 self.assertEqual(string.ascii_letters, string.ascii_lowercase + string.ascii_uppercase)
15 self.assertEqual(string.digits, '0123456789')
16 self.assertEqual(string.hexdigits, string.digits + 'abcdefABCDEF')
17 self.assertEqual(string.octdigits, '01234567')
18 self.assertEqual(string.punctuation, '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
19 self.assertEqual(string.printable, string.digits + string.ascii_lowercase + string.ascii_uppercase + string.punctuation + string.whitespace)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000020
Ezio Melotti2c6a9492009-09-26 12:19:30 +000021 def test_capwords(self):
22 self.assertEqual(string.capwords('abc def ghi'), 'Abc Def Ghi')
23 self.assertEqual(string.capwords('abc\tdef\nghi'), 'Abc Def Ghi')
24 self.assertEqual(string.capwords('abc\t def \nghi'), 'Abc Def Ghi')
25 self.assertEqual(string.capwords('ABC DEF GHI'), 'Abc Def Ghi')
26 self.assertEqual(string.capwords('ABC-DEF-GHI', '-'), 'Abc-Def-Ghi')
27 self.assertEqual(string.capwords('ABC-def DEF-ghi GHI'), 'Abc-def Def-ghi Ghi')
Ezio Melottia40bdda2009-09-26 12:33:22 +000028 self.assertEqual(string.capwords(' aBc DeF '), 'Abc Def')
29 self.assertEqual(string.capwords('\taBc\tDeF\t'), 'Abc Def')
30 self.assertEqual(string.capwords('\taBc\tDeF\t', '\t'), '\tAbc\tDef\t')
Ezio Melotti2c6a9492009-09-26 12:19:30 +000031
Nick Coghlan62ecb6a2011-05-31 19:40:11 +100032 def test_basic_formatter(self):
Eric Smith8c663262007-08-25 02:26:07 +000033 fmt = string.Formatter()
34 self.assertEqual(fmt.format("foo"), "foo")
Eric Smith7ade6482007-08-26 22:27:13 +000035 self.assertEqual(fmt.format("foo{0}", "bar"), "foobar")
36 self.assertEqual(fmt.format("foo{1}{0}-{1}", "bar", 6), "foo6bar-6")
Serhiy Storchaka8ffe9172015-03-24 22:28:43 +020037 self.assertRaises(TypeError, fmt.format)
38 self.assertRaises(TypeError, string.Formatter.format)
39
40 def test_format_keyword_arguments(self):
41 fmt = string.Formatter()
42 self.assertEqual(fmt.format("-{arg}-", arg='test'), '-test-')
43 self.assertRaises(KeyError, fmt.format, "-{arg}-")
44 self.assertEqual(fmt.format("-{self}-", self='test'), '-test-')
45 self.assertRaises(KeyError, fmt.format, "-{self}-")
46 self.assertEqual(fmt.format("-{format_string}-", format_string='test'),
47 '-test-')
48 self.assertRaises(KeyError, fmt.format, "-{format_string}-")
Serhiy Storchakab876df42015-03-24 22:30:46 +020049 with self.assertWarnsRegex(DeprecationWarning, "format_string"):
50 self.assertEqual(fmt.format(arg='test', format_string="-{arg}-"),
51 '-test-')
Eric Smith7ade6482007-08-26 22:27:13 +000052
Eric V. Smith7ce90742014-04-14 16:43:50 -040053 def test_auto_numbering(self):
54 fmt = string.Formatter()
55 self.assertEqual(fmt.format('foo{}{}', 'bar', 6),
56 'foo{}{}'.format('bar', 6))
57 self.assertEqual(fmt.format('foo{1}{num}{1}', None, 'bar', num=6),
58 'foo{1}{num}{1}'.format(None, 'bar', num=6))
59 self.assertEqual(fmt.format('{:^{}}', 'bar', 6),
60 '{:^{}}'.format('bar', 6))
Eric V. Smith85976b12015-09-29 10:27:38 -040061 self.assertEqual(fmt.format('{:^{}} {}', 'bar', 6, 'X'),
62 '{:^{}} {}'.format('bar', 6, 'X'))
Eric V. Smith7ce90742014-04-14 16:43:50 -040063 self.assertEqual(fmt.format('{:^{pad}}{}', 'foo', 'bar', pad=6),
64 '{:^{pad}}{}'.format('foo', 'bar', pad=6))
65
66 with self.assertRaises(ValueError):
67 fmt.format('foo{1}{}', 'bar', 6)
68
69 with self.assertRaises(ValueError):
70 fmt.format('foo{}{1}', 'bar', 6)
71
Nick Coghlan62ecb6a2011-05-31 19:40:11 +100072 def test_conversion_specifiers(self):
73 fmt = string.Formatter()
74 self.assertEqual(fmt.format("-{arg!r}-", arg='test'), "-'test'-")
75 self.assertEqual(fmt.format("{0!s}", 'test'), 'test')
76 self.assertRaises(ValueError, fmt.format, "{0!h}", 'test')
R David Murraye56bf972012-08-19 17:26:34 -040077 # issue13579
78 self.assertEqual(fmt.format("{0!a}", 42), '42')
79 self.assertEqual(fmt.format("{0!a}", string.ascii_letters),
80 "'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'")
81 self.assertEqual(fmt.format("{0!a}", chr(255)), "'\\xff'")
82 self.assertEqual(fmt.format("{0!a}", chr(256)), "'\\u0100'")
Nick Coghlan62ecb6a2011-05-31 19:40:11 +100083
84 def test_name_lookup(self):
85 fmt = string.Formatter()
86 class AnyAttr:
87 def __getattr__(self, attr):
88 return attr
89 x = AnyAttr()
90 self.assertEqual(fmt.format("{0.lumber}{0.jack}", x), 'lumberjack')
91 with self.assertRaises(AttributeError):
92 fmt.format("{0.lumber}{0.jack}", '')
93
94 def test_index_lookup(self):
95 fmt = string.Formatter()
96 lookup = ["eggs", "and", "spam"]
97 self.assertEqual(fmt.format("{0[2]}{0[0]}", lookup), 'spameggs')
98 with self.assertRaises(IndexError):
99 fmt.format("{0[2]}{0[0]}", [])
100 with self.assertRaises(KeyError):
101 fmt.format("{0[2]}{0[0]}", {})
102
103 def test_override_get_value(self):
Eric Smith7ade6482007-08-26 22:27:13 +0000104 class NamespaceFormatter(string.Formatter):
105 def __init__(self, namespace={}):
106 string.Formatter.__init__(self)
107 self.namespace = namespace
108
109 def get_value(self, key, args, kwds):
110 if isinstance(key, str):
111 try:
112 # Check explicitly passed arguments first
113 return kwds[key]
114 except KeyError:
115 return self.namespace[key]
116 else:
117 string.Formatter.get_value(key, args, kwds)
118
119 fmt = NamespaceFormatter({'greeting':'hello'})
120 self.assertEqual(fmt.format("{greeting}, world!"), 'hello, world!')
Eric Smith8c663262007-08-25 02:26:07 +0000121
122
Nick Coghlan62ecb6a2011-05-31 19:40:11 +1000123 def test_override_format_field(self):
Eric Smith81936692007-08-31 01:14:01 +0000124 class CallFormatter(string.Formatter):
125 def format_field(self, value, format_spec):
126 return format(value(), format_spec)
127
128 fmt = CallFormatter()
129 self.assertEqual(fmt.format('*{0}*', lambda : 'result'), '*result*')
130
131
Nick Coghlan62ecb6a2011-05-31 19:40:11 +1000132 def test_override_convert_field(self):
Eric Smith81936692007-08-31 01:14:01 +0000133 class XFormatter(string.Formatter):
134 def convert_field(self, value, conversion):
135 if conversion == 'x':
136 return None
Nick Coghlan62ecb6a2011-05-31 19:40:11 +1000137 return super().convert_field(value, conversion)
Eric Smith81936692007-08-31 01:14:01 +0000138
139 fmt = XFormatter()
140 self.assertEqual(fmt.format("{0!r}:{0!x}", 'foo', 'foo'), "'foo':None")
141
142
Nick Coghlan62ecb6a2011-05-31 19:40:11 +1000143 def test_override_parse(self):
Eric Smith81936692007-08-31 01:14:01 +0000144 class BarFormatter(string.Formatter):
145 # returns an iterable that contains tuples of the form:
146 # (literal_text, field_name, format_spec, conversion)
147 def parse(self, format_string):
148 for field in format_string.split('|'):
149 if field[0] == '+':
150 # it's markup
151 field_name, _, format_spec = field[1:].partition(':')
152 yield '', field_name, format_spec, None
153 else:
154 yield field, None, None, None
155
156 fmt = BarFormatter()
157 self.assertEqual(fmt.format('*|+0:^10s|*', 'foo'), '* foo *')
158
Nick Coghlan62ecb6a2011-05-31 19:40:11 +1000159 def test_check_unused_args(self):
Eric Smith3bcc42a2007-08-31 02:26:31 +0000160 class CheckAllUsedFormatter(string.Formatter):
161 def check_unused_args(self, used_args, args, kwargs):
Ezio Melotti42da6632011-03-15 05:18:48 +0200162 # Track which arguments actually got used
Eric Smith3bcc42a2007-08-31 02:26:31 +0000163 unused_args = set(kwargs.keys())
164 unused_args.update(range(0, len(args)))
165
166 for arg in used_args:
167 unused_args.remove(arg)
168
169 if unused_args:
170 raise ValueError("unused arguments")
171
172 fmt = CheckAllUsedFormatter()
173 self.assertEqual(fmt.format("{0}", 10), "10")
174 self.assertEqual(fmt.format("{0}{i}", 10, i=100), "10100")
175 self.assertEqual(fmt.format("{0}{i}{1}", 10, 20, i=100), "1010020")
176 self.assertRaises(ValueError, fmt.format, "{0}{i}{1}", 10, 20, i=100, j=0)
177 self.assertRaises(ValueError, fmt.format, "{0}", 10, 20)
178 self.assertRaises(ValueError, fmt.format, "{0}", 10, 20, i=100)
179 self.assertRaises(ValueError, fmt.format, "{i}", 10, 20, i=100)
180
Nick Coghlan62ecb6a2011-05-31 19:40:11 +1000181 def test_vformat_recursion_limit(self):
182 fmt = string.Formatter()
183 args = ()
184 kwargs = dict(i=100)
185 with self.assertRaises(ValueError) as err:
186 fmt._vformat("{i}", args, kwargs, set(), -1)
187 self.assertIn("recursion", str(err.exception))
Nick Coghland25fd4d2011-03-15 08:54:37 +1000188
189
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000190if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500191 unittest.main()