-
Notifications
You must be signed in to change notification settings - Fork 136
Expand file tree
/
Copy pathtest_content.py
More file actions
527 lines (356 loc) · 13 KB
/
test_content.py
File metadata and controls
527 lines (356 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# -*- encoding: utf-8 -*-
import sys
import pytest
def test_simple():
"""
# Basic formatting
Simple positional formatting is probably the most common use-case. Use it
if the order of your arguments is not likely to change and you only have
very few elements you want to concatenate.
Since the elements are not represented by something as descriptive as a
name this simple style should only be used to format a relatively small
number of elements.
"""
old_result = '%s %s' % ('one', 'two', )
new_result = '{} {}'.format('one', 'two')
assert old_result == new_result
assert old_result == 'one two' # output
def test_simple_2():
old_result = '%d %d' % (1, 2)
new_result = '{} {}'.format(1, 2)
assert old_result == new_result
assert new_result == "1 2" # output
def test_simple_3():
"""
With new style formatting it is possible (and in Python 2.6 even mandatory)
to give placeholders an explicit positional index.
This allows for re-arranging the order of display without changing the
arguments.
"""
new_result = '{1} {0}'.format('one', 'two')
assert new_result == 'two one' # output
def test_conversion_flags():
"""
# Value conversion
The new-style simple formatter calls by default the [`__format__()`][1]
method of an object for its representation. If you just want to render the
output of `str(...)` or `repr(...)` you can use the `!s` or `!r` conversion
flags.
In %-style you usually use `%s` for the string representation but there is
`%r` for a `repr(...)` conversion.
[1]: https://docs.python.org/3/reference/datamodel.html#object.__format__
"""
class Data(object):
def __str__(self):
return 'str'
def __repr__(self):
return 'repr'
old_result = '%s %r' % (Data(), Data())
new_result = '{0!s} {0!r}'.format(Data())
assert new_result == 'str repr' # output
assert new_result == old_result
@pytest.mark.xfail(sys.version_info < (3,), reason="!a not available in Python 2")
def test_ascii_conversion():
"""
In Python 3 there exists an additional conversion flag that uses the output
of `repr(...)` but uses `ascii(...)` instead.
"""
class Data(object):
def __repr__(self):
return 'räpr'
old_result = '%r %a' % (Data(), Data())
new_result = '{0!r} {0!a}'.format(Data())
assert new_result == 'räpr r\\xe4pr' # output
assert new_result == old_result
def test_string_pad_align():
"""
# Padding and aligning strings
By default values are formatted to take up only as many characters as
needed to represent the content. It is however also possible to define that
a value should be padded to a specific length.
Unfortunately the default alignment differs between old and new style
formatting. The old style defaults to right aligned while for new style
it's left.
Align right:
"""
old_result = '%10s' % ('test', )
new_result = '{:>10}'.format('test')
assert old_result == new_result
assert old_result == ' test' # output
def test_string_pad_align_2():
"""
Align left:
"""
old_result = '%-10s' % ('test', )
new_result = '{:10}'.format('test')
assert old_result == new_result
assert old_result == 'test ' # output
def test_string_pad_align_3():
"""
Again, new style formatting surpasses the old variant by providing more
control over how values are padded and aligned.
You are able to choose the padding character:
"""
new_result = '{:_<10}'.format('test')
assert new_result == 'test______' # output
def test_string_pad_align_4():
"""
And also center align values:
"""
new_result = '{:^10}'.format('test')
assert new_result == ' test ' # output
def test_string_pad_align_5():
"""
When using center alignment where the length of the string leads to an
uneven split of the padding characters the extra character will be placed
on the right side:
"""
new_result = '{:^6}'.format('zip')
assert new_result == ' zip ' # output
def test_string_truncating():
"""
# Truncating long strings
Inverse to padding it is also possible to truncate overly long values
to a specific number of characters.
The number behind a `.` in the format specifies the precision of the
output. For strings that means that the output is truncated to the
specified length. In our example this would be 5 characters.
"""
old_result = '%.5s' % ('xylophone', )
new_result = '{:.5}'.format('xylophone')
assert old_result == new_result
assert old_result == 'xylop' # output
def test_string_trunc_pad():
"""
# Combining truncating and padding
It is also possible to combine truncating and padding:
"""
old_result = '%-10.5s' % ('xylophone', )
new_result = '{:10.5}'.format('xylophone')
assert old_result == new_result
assert new_result == 'xylop ' # output
def test_number():
"""
# Numbers
Of course it is also possible to format numbers.
Integers:
"""
old_result = '%d' % (42, )
new_result = '{:d}'.format(42)
assert old_result == new_result
assert old_result == '42' # output
def test_number_2():
"""
Floats:
"""
old_result = '%f' % (3.141592653589793, )
new_result = '{:f}'.format(3.141592653589793)
assert old_result == new_result
assert old_result == '3.141593' # output
def test_number_padding():
"""
# Padding numbers
Similar to strings numbers can also be constrained to a specific width.
"""
old_result = '%4d' % (42, )
new_result = '{:4d}'.format(42)
assert old_result == new_result
assert old_result == ' 42' # output
def test_number_padding_2():
"""
Again similar to truncating strings the precision for floating point
numbers limits the number of positions after the decimal point.
For floating points the padding value represents the length of the complete
output. In the example below we want our output to have at least 6
characters with 2 after the decimal point.
"""
old_result = '%06.2f' % (3.141592653589793, )
new_result = '{:06.2f}'.format(3.141592653589793)
assert old_result == new_result
assert old_result == '003.14' # output
def test_number_padding_3():
"""
For integer values providing a precision doesn't make much sense and is
actually forbidden in the new style (it will result in a ValueError).
"""
old_result = '%04d' % (42, )
new_result = '{:04d}'.format(42)
with pytest.raises(ValueError):
'{:04.2d}'.format(42)
assert old_result == new_result
assert old_result == '0042' # output
def test_number_sign():
"""
# Signed numbers
By default only negative numbers are prefixed with a sign. This can be
changed of course.
"""
old_result = '%+d' % (42, )
new_result = '{:+d}'.format(42)
assert old_result == new_result
assert old_result == '+42' # output
def test_number_sign_2():
"""
Use a space character to indicate that negative numbers should be prefixed
with a minus symbol and a leading space should be used for positive ones.
"""
old_result = '% d' % (-23, )
new_result = '{: d}'.format(-23)
assert old_result == new_result
assert old_result == '-23' # output
def test_number_sign_3():
old_result = '% d' % (42, )
new_result = '{: d}'.format(42)
assert old_result == new_result
assert old_result == ' 42' # output
def test_number_sign_4():
"""
New style formatting is also able to control the position of the sign
symbol relative to the padding.
"""
new_result = '{:=5d}'.format(-23)
assert new_result == '- 23' # output
def test_number_sign_5():
new_result = '{:=+5d}'.format(23)
assert new_result == '+ 23' # output
def test_named_placeholders():
"""
# Named placeholders
Both formatting styles support named placeholders.
"""
data = {
'first': 'Hodor',
'last': 'Hodor!',
}
old_result = '%(first)s %(last)s' % data
new_result = '{first} {last}'.format(**data)
assert old_result == new_result
assert old_result == 'Hodor Hodor!' # output
def test_named_placeholders_2():
"""
`.format()` also accepts keyword arguments.
"""
old_result = '%(first)s %(last)s' % dict(first="Hodor", last="Hodor!")
new_result = '{first} {last}'.format(first="Hodor", last="Hodor!")
assert new_result == 'Hodor Hodor!' # output
def test_getitem_and_getattr():
"""
# Getitem and Getattr
New style formatting allows even greater flexibility in accessing nested
data structures.
It supports accessing containers that support `__getitem__` like for
example dictionaries and lists:
"""
person = {
'first': 'Jean-Luc',
'last': 'Picard',
}
new_result = '{p[first]} {p[last]}'.format(p=person)
assert new_result == 'Jean-Luc Picard' # output
def test_getitem_and_getattr_2():
data = [4, 8, 15, 16, 23, 42]
new_result = '{d[4]} {d[5]}'.format(d=data)
assert new_result == '23 42' # output
def test_getitem_and_getattr_3():
"""
As well as accessing attributes on objects via `getattr()`:
"""
class Plant(object):
type = "tree"
new_result = '{p.type}'.format(p=Plant())
assert new_result == 'tree' # output
def test_getitem_and_getattr_4():
"""
Both type of access can be freely mixed and arbitrarily nested:
"""
class Plant(object):
type = "tree"
kinds = [{
'name': "oak",
}, {
'name': "maple"
}]
new_result = '{p.type}: {p.kinds[0][name]}'.format(p=Plant())
assert new_result == 'tree: oak' # output
def test_datetime():
"""
# Datetime
New style formatting also allows objects to control their own
rendering. This for example allows datetime objects to be formatted inline:
"""
from datetime import datetime
new_result = '{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))
assert new_result == '2001-02-03 04:05' # output
def test_param_align():
"""
# Parametrized formats
Additionally, new style formatting allows all of the components of
the format to be specified dynamically using parametrization. Parametrized
formats are nested expressions in braces that can appear anywhere in the
parent format after the colon.
Old style formatting also supports some parametrization but is much more
limited. Namely it only allows parametrization of the width and precision
of the output.
Parametrized alignment and width:
"""
new_result = '{:{align}{width}}'.format('test', align='^', width='10')
assert new_result == ' test ' # output
def test_param_prec():
"""
Parametrized precision:
"""
old_result = '%.*s = %.*f' % (3, 'Gibberish', 3, 2.7182)
new_result = '{:.{prec}} = {:.{prec}f}'.format('Gibberish', 2.7182, prec=3)
assert old_result == new_result
assert new_result == 'Gib = 2.718' # output
def test_param_width_prec():
"""
Width and precision:
"""
old_result = '%*.*f' % (5, 2, 2.7182,)
new_result = '{:{width}.{prec}f}'.format(2.7182, width=5, prec=2)
assert old_result == new_result
assert new_result == " 2.72"
def test_param_prec_2():
"""
The nested format can be used to replace *any* part of the format
spec, so the precision example above could be rewritten as:
"""
new_result = '{:{prec}} = {:{prec}}'.format('Gibberish', 2.7182, prec='.3')
assert new_result == 'Gib = 2.72' # output
def test_param_date():
"""
The components of a date-time can be set separately:
"""
from datetime import datetime
dt = datetime(2001, 2, 3, 4, 5)
new_result = '{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M')
assert new_result == '2001-02-03 04:05' # output
def test_param_order_1():
"""
The nested formats can be positional arguments. Position depends
on the order of the opening curly braces:
"""
new_result = '{:{}{}{}.{}}'.format(2.7182818284, '>', '+', 10, 3)
assert new_result == ' +2.72' # output
def test_param_order_2():
"""
And of course keyword arguments can be added to the mix as before:
"""
new_result = '{:{}{sign}{}.{}}'.format(2.7182818284, '>', 10, 3, sign='+')
assert new_result == ' +2.72' # output
def test_custom_1():
"""
# Custom objects
The datetime example works through the use of the `__format__()` magic
method. You can define custom format handling in your own objects by
overriding this method. This gives you complete control over the format
syntax used.
"""
class HAL9000(object):
def __format__(self, format):
if format == "open-the-pod-bay-doors":
return "I'm afraid I can't do that."
return "HAL 9000"
new_result = '{:open-the-pod-bay-doors}'.format(HAL9000())
assert new_result == "I'm afraid I can't do that." # output