| 1 |
""" |
| 2 |
Test cases for the repr module |
| 3 |
Nick Mathewson |
| 4 |
""" |
| 5 |
|
| 6 |
import annotationlib |
| 7 |
import sys |
| 8 |
import os |
| 9 |
import shutil |
| 10 |
import importlib |
| 11 |
import importlib.util |
| 12 |
import unittest |
| 13 |
import textwrap |
| 14 |
|
| 15 |
from test.support import verbose, EqualToForwardRef |
| 16 |
from test.support.os_helper import create_empty_file |
| 17 |
from reprlib import repr as r # Don't shadow builtin repr |
| 18 |
from reprlib import Repr |
| 19 |
from reprlib import recursive_repr |
| 20 |
|
| 21 |
|
| 22 |
def nestedTuple(nesting): |
| 23 |
t = () |
| 24 |
for i in range(nesting): |
| 25 |
t = (t,) |
| 26 |
return t |
| 27 |
|
| 28 |
class ReprTests(unittest.TestCase): |
| 29 |
|
| 30 |
def test_init_kwargs(self): |
| 31 |
example_kwargs = { |
| 32 |
"maxlevel": 101, |
| 33 |
"maxtuple": 102, |
| 34 |
"maxlist": 103, |
| 35 |
"maxarray": 104, |
| 36 |
"maxdict": 105, |
| 37 |
"maxset": 106, |
| 38 |
"maxfrozenset": 107, |
| 39 |
"maxdeque": 108, |
| 40 |
"maxstring": 109, |
| 41 |
"maxlong": 110, |
| 42 |
"maxother": 111, |
| 43 |
"fillvalue": "x" * 112, |
| 44 |
"indent": "x" * 113, |
| 45 |
} |
| 46 |
r1 = Repr() |
| 47 |
for attr, val in example_kwargs.items(): |
| 48 |
setattr(r1, attr, val) |
| 49 |
r2 = Repr(**example_kwargs) |
| 50 |
for attr in example_kwargs: |
| 51 |
self.assertEqual(getattr(r1, attr), getattr(r2, attr), msg=attr) |
| 52 |
|
| 53 |
def test_string(self): |
| 54 |
eq = self.assertEqual |
| 55 |
eq(r("abc"), "'abc'") |
| 56 |
eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'") |
| 57 |
|
| 58 |
s = "a"*30+"b"*30 |
| 59 |
expected = repr(s)[:13] + "..." + repr(s)[-14:] |
| 60 |
eq(r(s), expected) |
| 61 |
|
| 62 |
eq(r("\"'"), repr("\"'")) |
| 63 |
s = "\""*30+"'"*100 |
| 64 |
expected = repr(s)[:13] + "..." + repr(s)[-14:] |
| 65 |
eq(r(s), expected) |
| 66 |
|
| 67 |
def test_tuple(self): |
| 68 |
eq = self.assertEqual |
| 69 |
eq(r((1,)), "(1,)") |
| 70 |
|
| 71 |
t3 = (1, 2, 3) |
| 72 |
eq(r(t3), "(1, 2, 3)") |
| 73 |
|
| 74 |
r2 = Repr() |
| 75 |
r2.maxtuple = 2 |
| 76 |
expected = repr(t3)[:-2] + "...)" |
| 77 |
eq(r2.repr(t3), expected) |
| 78 |
|
| 79 |
# modified fillvalue: |
| 80 |
r3 = Repr() |
| 81 |
r3.fillvalue = '+++' |
| 82 |
r3.maxtuple = 2 |
| 83 |
expected = repr(t3)[:-2] + "+++)" |
| 84 |
eq(r3.repr(t3), expected) |
| 85 |
|
| 86 |
def test_container(self): |
| 87 |
from array import array |
| 88 |
from collections import deque |
| 89 |
|
| 90 |
eq = self.assertEqual |
| 91 |
# Tuples give up after 6 elements |
| 92 |
eq(r(()), "()") |
| 93 |
eq(r((1,)), "(1,)") |
| 94 |
eq(r((1, 2, 3)), "(1, 2, 3)") |
| 95 |
eq(r((1, 2, 3, 4, 5, 6)), "(1, 2, 3, 4, 5, 6)") |
| 96 |
eq(r((1, 2, 3, 4, 5, 6, 7)), "(1, 2, 3, 4, 5, 6, ...)") |
| 97 |
|
| 98 |
# Lists give up after 6 as well |
| 99 |
eq(r([]), "[]") |
| 100 |
eq(r([1]), "[1]") |
| 101 |
eq(r([1, 2, 3]), "[1, 2, 3]") |
| 102 |
eq(r([1, 2, 3, 4, 5, 6]), "[1, 2, 3, 4, 5, 6]") |
| 103 |
eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]") |
| 104 |
|
| 105 |
# Sets give up after 6 as well |
| 106 |
eq(r(set([])), "set()") |
| 107 |
eq(r(set([1])), "{1}") |
| 108 |
eq(r(set([1, 2, 3])), "{1, 2, 3}") |
| 109 |
eq(r(set([1, 2, 3, 4, 5, 6])), "{1, 2, 3, 4, 5, 6}") |
| 110 |
eq(r(set([1, 2, 3, 4, 5, 6, 7])), "{1, 2, 3, 4, 5, 6, ...}") |
| 111 |
|
| 112 |
# Frozensets give up after 6 as well |
| 113 |
eq(r(frozenset([])), "frozenset()") |
| 114 |
eq(r(frozenset([1])), "frozenset({1})") |
| 115 |
eq(r(frozenset([1, 2, 3])), "frozenset({1, 2, 3})") |
| 116 |
eq(r(frozenset([1, 2, 3, 4, 5, 6])), "frozenset({1, 2, 3, 4, 5, 6})") |
| 117 |
eq(r(frozenset([1, 2, 3, 4, 5, 6, 7])), "frozenset({1, 2, 3, 4, 5, 6, ...})") |
| 118 |
|
| 119 |
# collections.deque after 6 |
| 120 |
eq(r(deque([1, 2, 3, 4, 5, 6, 7])), "deque([1, 2, 3, 4, 5, 6, ...])") |
| 121 |
|
| 122 |
# Dictionaries give up after 4. |
| 123 |
eq(r({}), "{}") |
| 124 |
d = {'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4} |
| 125 |
eq(r(d), "{'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}") |
| 126 |
d['arthur'] = 1 |
| 127 |
eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}") |
| 128 |
|
| 129 |
# array.array after 5. |
| 130 |
eq(r(array('i')), "array('i')") |
| 131 |
eq(r(array('i', [1])), "array('i', [1])") |
| 132 |
eq(r(array('i', [1, 2])), "array('i', [1, 2])") |
| 133 |
eq(r(array('i', [1, 2, 3])), "array('i', [1, 2, 3])") |
| 134 |
eq(r(array('i', [1, 2, 3, 4])), "array('i', [1, 2, 3, 4])") |
| 135 |
eq(r(array('i', [1, 2, 3, 4, 5])), "array('i', [1, 2, 3, 4, 5])") |
| 136 |
eq(r(array('i', [1, 2, 3, 4, 5, 6])), |
| 137 |
"array('i', [1, 2, 3, 4, 5, ...])") |
| 138 |
|
| 139 |
def test_set_literal(self): |
| 140 |
eq = self.assertEqual |
| 141 |
eq(r({1}), "{1}") |
| 142 |
eq(r({1, 2, 3}), "{1, 2, 3}") |
| 143 |
eq(r({1, 2, 3, 4, 5, 6}), "{1, 2, 3, 4, 5, 6}") |
| 144 |
eq(r({1, 2, 3, 4, 5, 6, 7}), "{1, 2, 3, 4, 5, 6, ...}") |
| 145 |
|
| 146 |
def test_frozenset(self): |
| 147 |
eq = self.assertEqual |
| 148 |
eq(r(frozenset({1})), "frozenset({1})") |
| 149 |
eq(r(frozenset({1, 2, 3})), "frozenset({1, 2, 3})") |
| 150 |
eq(r(frozenset({1, 2, 3, 4, 5, 6})), "frozenset({1, 2, 3, 4, 5, 6})") |
| 151 |
eq(r(frozenset({1, 2, 3, 4, 5, 6, 7})), "frozenset({1, 2, 3, 4, 5, 6, ...})") |
| 152 |
|
| 153 |
def test_numbers(self): |
| 154 |
for x in [123, 1.0 / 3]: |
| 155 |
self.assertEqual(r(x), repr(x)) |
| 156 |
|
| 157 |
max_digits = sys.get_int_max_str_digits() |
| 158 |
for k in [100, max_digits - 1]: |
| 159 |
with self.subTest(f'10 ** {k}', k=k): |
| 160 |
n = 10 ** k |
| 161 |
expected = repr(n)[:18] + "..." + repr(n)[-19:] |
| 162 |
self.assertEqual(r(n), expected) |
| 163 |
|
| 164 |
def re_msg(n, d): |
| 165 |
return (rf'<{n.__class__.__name__} instance with roughly {d} ' |
| 166 |
rf'digits \(limit at {max_digits}\) at 0x[a-f0-9]+>') |
| 167 |
|
| 168 |
k = max_digits |
| 169 |
with self.subTest(f'10 ** {k}', k=k): |
| 170 |
n = 10 ** k |
| 171 |
self.assertRaises(ValueError, repr, n) |
| 172 |
self.assertRegex(r(n), re_msg(n, k + 1)) |
| 173 |
|
| 174 |
for k in [max_digits + 1, 2 * max_digits]: |
| 175 |
self.assertGreater(k, 100) |
| 176 |
with self.subTest(f'10 ** {k}', k=k): |
| 177 |
n = 10 ** k |
| 178 |
self.assertRaises(ValueError, repr, n) |
| 179 |
self.assertRegex(r(n), re_msg(n, k + 1)) |
| 180 |
with self.subTest(f'10 ** {k} - 1', k=k): |
| 181 |
n = 10 ** k - 1 |
| 182 |
# Here, since math.log10(n) == math.log10(n-1), |
| 183 |
# the number of digits of n - 1 is overestimated. |
| 184 |
self.assertRaises(ValueError, repr, n) |
| 185 |
self.assertRegex(r(n), re_msg(n, k + 1)) |
| 186 |
|
| 187 |
def test_instance(self): |
| 188 |
eq = self.assertEqual |
| 189 |
i1 = ClassWithRepr("a") |
| 190 |
eq(r(i1), repr(i1)) |
| 191 |
|
| 192 |
i2 = ClassWithRepr("x"*1000) |
| 193 |
expected = repr(i2)[:13] + "..." + repr(i2)[-14:] |
| 194 |
eq(r(i2), expected) |
| 195 |
|
| 196 |
i3 = ClassWithFailingRepr() |
| 197 |
eq(r(i3), ("<ClassWithFailingRepr instance at %#x>"%id(i3))) |
| 198 |
|
| 199 |
s = r(ClassWithFailingRepr) |
| 200 |
self.assertStartsWith(s, "<class ") |
| 201 |
self.assertEndsWith(s, ">") |
| 202 |
self.assertIn(s.find("..."), [12, 13]) |
| 203 |
|
| 204 |
def test_lambda(self): |
| 205 |
r = repr(lambda x: x) |
| 206 |
self.assertStartsWith(r, "<function ReprTests.test_lambda.<locals>.<lambda") |
| 207 |
# XXX anonymous functions? see func_repr |
| 208 |
|
| 209 |
def test_builtin_function(self): |
| 210 |
eq = self.assertEqual |
| 211 |
# Functions |
| 212 |
eq(repr(hash), '<built-in function hash>') |
| 213 |
# Methods |
| 214 |
self.assertStartsWith(repr(''.split), |
| 215 |
'<built-in method split of str object at 0x') |
| 216 |
|
| 217 |
def test_range(self): |
| 218 |
eq = self.assertEqual |
| 219 |
eq(repr(range(1)), 'range(0, 1)') |
| 220 |
eq(repr(range(1, 2)), 'range(1, 2)') |
| 221 |
eq(repr(range(1, 4, 3)), 'range(1, 4, 3)') |
| 222 |
|
| 223 |
def test_nesting(self): |
| 224 |
eq = self.assertEqual |
| 225 |
# everything is meant to give up after 6 levels. |
| 226 |
eq(r([[[[[[[]]]]]]]), "[[[[[[[]]]]]]]") |
| 227 |
eq(r([[[[[[[[]]]]]]]]), "[[[[[[[...]]]]]]]") |
| 228 |
|
| 229 |
eq(r(nestedTuple(6)), "(((((((),),),),),),)") |
| 230 |
eq(r(nestedTuple(7)), "(((((((...),),),),),),)") |
| 231 |
|
| 232 |
eq(r({ nestedTuple(5) : nestedTuple(5) }), |
| 233 |
"{((((((),),),),),): ((((((),),),),),)}") |
| 234 |
eq(r({ nestedTuple(6) : nestedTuple(6) }), |
| 235 |
"{((((((...),),),),),): ((((((...),),),),),)}") |
| 236 |
|
| 237 |
eq(r([[[[[[{}]]]]]]), "[[[[[[{}]]]]]]") |
| 238 |
eq(r([[[[[[[{}]]]]]]]), "[[[[[[[...]]]]]]]") |
| 239 |
|
| 240 |
def test_cell(self): |
| 241 |
def get_cell(): |
| 242 |
x = 42 |
| 243 |
def inner(): |
| 244 |
return x |
| 245 |
return inner |
| 246 |
x = get_cell().__closure__[0] |
| 247 |
self.assertRegex(repr(x), r'<cell at 0x[0-9A-Fa-f]+: ' |
| 248 |
r'int object at 0x[0-9A-Fa-f]+>') |
| 249 |
self.assertRegex(r(x), r'<cell at 0x.*\.\.\..*>') |
| 250 |
|
| 251 |
def test_descriptors(self): |
| 252 |
eq = self.assertEqual |
| 253 |
# method descriptors |
| 254 |
eq(repr(dict.items), "<method 'items' of 'dict' objects>") |
| 255 |
# XXX member descriptors |
| 256 |
# XXX attribute descriptors |
| 257 |
# XXX slot descriptors |
| 258 |
# static and class methods |
| 259 |
class C: |
| 260 |
def foo(cls): pass |
| 261 |
x = staticmethod(C.foo) |
| 262 |
self.assertEqual(repr(x), f'<staticmethod({C.foo!r})>') |
| 263 |
x = classmethod(C.foo) |
| 264 |
self.assertEqual(repr(x), f'<classmethod({C.foo!r})>') |
| 265 |
|
| 266 |
def test_unsortable(self): |
| 267 |
# Repr.repr() used to call sorted() on sets, frozensets and dicts |
| 268 |
# without taking into account that not all objects are comparable |
| 269 |
x = set([1j, 2j, 3j]) |
| 270 |
y = frozenset(x) |
| 271 |
z = {1j: 1, 2j: 2} |
| 272 |
r(x) |
| 273 |
r(y) |
| 274 |
r(z) |
| 275 |
|
| 276 |
def test_valid_indent(self): |
| 277 |
test_cases = [ |
| 278 |
{ |
| 279 |
'object': (), |
| 280 |
'tests': ( |
| 281 |
(dict(indent=None), '()'), |
| 282 |
(dict(indent=False), '()'), |
| 283 |
(dict(indent=True), '()'), |
| 284 |
(dict(indent=0), '()'), |
| 285 |
(dict(indent=1), '()'), |
| 286 |
(dict(indent=4), '()'), |
| 287 |
(dict(indent=4, maxlevel=2), '()'), |
| 288 |
(dict(indent=''), '()'), |
| 289 |
(dict(indent='-->'), '()'), |
| 290 |
(dict(indent='....'), '()'), |
| 291 |
), |
| 292 |
}, |
| 293 |
{ |
| 294 |
'object': '', |
| 295 |
'tests': ( |
| 296 |
(dict(indent=None), "''"), |
| 297 |
(dict(indent=False), "''"), |
| 298 |
(dict(indent=True), "''"), |
| 299 |
(dict(indent=0), "''"), |
| 300 |
(dict(indent=1), "''"), |
| 301 |
(dict(indent=4), "''"), |
| 302 |
(dict(indent=4, maxlevel=2), "''"), |
| 303 |
(dict(indent=''), "''"), |
| 304 |
(dict(indent='-->'), "''"), |
| 305 |
(dict(indent='....'), "''"), |
| 306 |
), |
| 307 |
}, |
| 308 |
{ |
| 309 |
'object': [1, 'spam', {'eggs': True, 'ham': []}], |
| 310 |
'tests': ( |
| 311 |
(dict(indent=None), '''\ |
| 312 |
[1, 'spam', {'eggs': True, 'ham': []}]'''), |
| 313 |
(dict(indent=False), '''\ |
| 314 |
[ |
| 315 |
1, |
| 316 |
'spam', |
| 317 |
{ |
| 318 |
'eggs': True, |
| 319 |
'ham': [], |
| 320 |
}, |
| 321 |
]'''), |
| 322 |
(dict(indent=True), '''\ |
| 323 |
[ |
| 324 |
1, |
| 325 |
'spam', |
| 326 |
{ |
| 327 |
'eggs': True, |
| 328 |
'ham': [], |
| 329 |
}, |
| 330 |
]'''), |
| 331 |
(dict(indent=0), '''\ |
| 332 |
[ |
| 333 |
1, |
| 334 |
'spam', |
| 335 |
{ |
| 336 |
'eggs': True, |
| 337 |
'ham': [], |
| 338 |
}, |
| 339 |
]'''), |
| 340 |
(dict(indent=1), '''\ |
| 341 |
[ |
| 342 |
1, |
| 343 |
'spam', |
| 344 |
{ |
| 345 |
'eggs': True, |
| 346 |
'ham': [], |
| 347 |
}, |
| 348 |
]'''), |
| 349 |
(dict(indent=4), '''\ |
| 350 |
[ |
| 351 |
1, |
| 352 |
'spam', |
| 353 |
{ |
| 354 |
'eggs': True, |
| 355 |
'ham': [], |
| 356 |
}, |
| 357 |
]'''), |
| 358 |
(dict(indent=4, maxlevel=2), '''\ |
| 359 |
[ |
| 360 |
1, |
| 361 |
'spam', |
| 362 |
{ |
| 363 |
'eggs': True, |
| 364 |
'ham': [], |
| 365 |
}, |
| 366 |
]'''), |
| 367 |
(dict(indent=''), '''\ |
| 368 |
[ |
| 369 |
1, |
| 370 |
'spam', |
| 371 |
{ |
| 372 |
'eggs': True, |
| 373 |
'ham': [], |
| 374 |
}, |
| 375 |
]'''), |
| 376 |
(dict(indent='-->'), '''\ |
| 377 |
[ |
| 378 |
-->1, |
| 379 |
-->'spam', |
| 380 |
-->{ |
| 381 |
-->-->'eggs': True, |
| 382 |
-->-->'ham': [], |
| 383 |
-->}, |
| 384 |
]'''), |
| 385 |
(dict(indent='....'), '''\ |
| 386 |
[ |
| 387 |
....1, |
| 388 |
....'spam', |
| 389 |
....{ |
| 390 |
........'eggs': True, |
| 391 |
........'ham': [], |
| 392 |
....}, |
| 393 |
]'''), |
| 394 |
), |
| 395 |
}, |
| 396 |
{ |
| 397 |
'object': { |
| 398 |
1: 'two', |
| 399 |
b'three': [ |
| 400 |
(4.5, 6.25), |
| 401 |
[set((8, 9)), frozenset((10, 11))], |
| 402 |
], |
| 403 |
}, |
| 404 |
'tests': ( |
| 405 |
(dict(indent=None), '''\ |
| 406 |
{1: 'two', b'three': [(4.5, 6.25), [{8, 9}, frozenset({10, 11})]]}'''), |
| 407 |
(dict(indent=False), '''\ |
| 408 |
{ |
| 409 |
1: 'two', |
| 410 |
b'three': [ |
| 411 |
( |
| 412 |
4.5, |
| 413 |
6.25, |
| 414 |
), |
| 415 |
[ |
| 416 |
{ |
| 417 |
8, |
| 418 |
9, |
| 419 |
}, |
| 420 |
frozenset({ |
| 421 |
10, |
| 422 |
11, |
| 423 |
}), |
| 424 |
], |
| 425 |
], |
| 426 |
}'''), |
| 427 |
(dict(indent=True), '''\ |
| 428 |
{ |
| 429 |
1: 'two', |
| 430 |
b'three': [ |
| 431 |
( |
| 432 |
4.5, |
| 433 |
6.25, |
| 434 |
), |
| 435 |
[ |
| 436 |
{ |
| 437 |
8, |
| 438 |
9, |
| 439 |
}, |
| 440 |
frozenset({ |
| 441 |
10, |
| 442 |
11, |
| 443 |
}), |
| 444 |
], |
| 445 |
], |
| 446 |
}'''), |
| 447 |
(dict(indent=0), '''\ |
| 448 |
{ |
| 449 |
1: 'two', |
| 450 |
b'three': [ |
| 451 |
( |
| 452 |
4.5, |
| 453 |
6.25, |
| 454 |
), |
| 455 |
[ |
| 456 |
{ |
| 457 |
8, |
| 458 |
9, |
| 459 |
}, |
| 460 |
frozenset({ |
| 461 |
10, |
| 462 |
11, |
| 463 |
}), |
| 464 |
], |
| 465 |
], |
| 466 |
}'''), |
| 467 |
(dict(indent=1), '''\ |
| 468 |
{ |
| 469 |
1: 'two', |
| 470 |
b'three': [ |
| 471 |
( |
| 472 |
4.5, |
| 473 |
6.25, |
| 474 |
), |
| 475 |
[ |
| 476 |
{ |
| 477 |
8, |
| 478 |
9, |
| 479 |
}, |
| 480 |
frozenset({ |
| 481 |
10, |
| 482 |
11, |
| 483 |
}), |
| 484 |
], |
| 485 |
], |
| 486 |
}'''), |
| 487 |
(dict(indent=4), '''\ |
| 488 |
{ |
| 489 |
1: 'two', |
| 490 |
b'three': [ |
| 491 |
( |
| 492 |
4.5, |
| 493 |
6.25, |
| 494 |
), |
| 495 |
[ |
| 496 |
{ |
| 497 |
8, |
| 498 |
9, |
| 499 |
}, |
| 500 |
frozenset({ |
| 501 |
10, |
| 502 |
11, |
| 503 |
}), |
| 504 |
], |
| 505 |
], |
| 506 |
}'''), |
| 507 |
(dict(indent=4, maxlevel=2), '''\ |
| 508 |
{ |
| 509 |
1: 'two', |
| 510 |
b'three': [ |
| 511 |
(...), |
| 512 |
[...], |
| 513 |
], |
| 514 |
}'''), |
| 515 |
(dict(indent=''), '''\ |
| 516 |
{ |
| 517 |
1: 'two', |
| 518 |
b'three': [ |
| 519 |
( |
| 520 |
4.5, |
| 521 |
6.25, |
| 522 |
), |
| 523 |
[ |
| 524 |
{ |
| 525 |
8, |
| 526 |
9, |
| 527 |
}, |
| 528 |
frozenset({ |
| 529 |
10, |
| 530 |
11, |
| 531 |
}), |
| 532 |
], |
| 533 |
], |
| 534 |
}'''), |
| 535 |
(dict(indent='-->'), '''\ |
| 536 |
{ |
| 537 |
-->1: 'two', |
| 538 |
-->b'three': [ |
| 539 |
-->-->( |
| 540 |
-->-->-->4.5, |
| 541 |
-->-->-->6.25, |
| 542 |
-->-->), |
| 543 |
-->-->[ |
| 544 |
-->-->-->{ |
| 545 |
-->-->-->-->8, |
| 546 |
-->-->-->-->9, |
| 547 |
-->-->-->}, |
| 548 |
-->-->-->frozenset({ |
| 549 |
-->-->-->-->10, |
| 550 |
-->-->-->-->11, |
| 551 |
-->-->-->}), |
| 552 |
-->-->], |
| 553 |
-->], |
| 554 |
}'''), |
| 555 |
(dict(indent='....'), '''\ |
| 556 |
{ |
| 557 |
....1: 'two', |
| 558 |
....b'three': [ |
| 559 |
........( |
| 560 |
............4.5, |
| 561 |
............6.25, |
| 562 |
........), |
| 563 |
........[ |
| 564 |
............{ |
| 565 |
................8, |
| 566 |
................9, |
| 567 |
............}, |
| 568 |
............frozenset({ |
| 569 |
................10, |
| 570 |
................11, |
| 571 |
............}), |
| 572 |
........], |
| 573 |
....], |
| 574 |
}'''), |
| 575 |
), |
| 576 |
}, |
| 577 |
] |
| 578 |
for test_case in test_cases: |
| 579 |
with self.subTest(test_object=test_case['object']): |
| 580 |
for repr_settings, expected_repr in test_case['tests']: |
| 581 |
with self.subTest(repr_settings=repr_settings): |
| 582 |
r = Repr() |
| 583 |
for attribute, value in repr_settings.items(): |
| 584 |
setattr(r, attribute, value) |
| 585 |
resulting_repr = r.repr(test_case['object']) |
| 586 |
expected_repr = textwrap.dedent(expected_repr) |
| 587 |
self.assertEqual(resulting_repr, expected_repr) |
| 588 |
|
| 589 |
def test_invalid_indent(self): |
| 590 |
test_object = [1, 'spam', {'eggs': True, 'ham': []}] |
| 591 |
test_cases = [ |
| 592 |
(-1, (ValueError, '[Nn]egative|[Pp]ositive')), |
| 593 |
(-4, (ValueError, '[Nn]egative|[Pp]ositive')), |
| 594 |
((), (TypeError, None)), |
| 595 |
([], (TypeError, None)), |
| 596 |
((4,), (TypeError, None)), |
| 597 |
([4,], (TypeError, None)), |
| 598 |
(object(), (TypeError, None)), |
| 599 |
] |
| 600 |
for indent, (expected_error, expected_msg) in test_cases: |
| 601 |
with self.subTest(indent=indent): |
| 602 |
r = Repr() |
| 603 |
r.indent = indent |
| 604 |
expected_msg = expected_msg or f'{type(indent)}' |
| 605 |
with self.assertRaisesRegex(expected_error, expected_msg): |
| 606 |
r.repr(test_object) |
| 607 |
|
| 608 |
def test_shadowed_stdlib_array(self): |
| 609 |
# Issue #113570: repr() should not be fooled by an array |
| 610 |
class array: |
| 611 |
def __repr__(self): |
| 612 |
return "not array.array" |
| 613 |
|
| 614 |
self.assertEqual(r(array()), "not array.array") |
| 615 |
|
| 616 |
def test_shadowed_builtin(self): |
| 617 |
# Issue #113570: repr() should not be fooled |
| 618 |
# by a shadowed builtin function |
| 619 |
class list: |
| 620 |
def __repr__(self): |
| 621 |
return "not builtins.list" |
| 622 |
|
| 623 |
self.assertEqual(r(list()), "not builtins.list") |
| 624 |
|
| 625 |
def test_custom_repr(self): |
| 626 |
class MyRepr(Repr): |
| 627 |
|
| 628 |
def repr_TextIOWrapper(self, obj, level): |
| 629 |
if obj.name in {'<stdin>', '<stdout>', '<stderr>'}: |
| 630 |
return obj.name |
| 631 |
return repr(obj) |
| 632 |
|
| 633 |
aRepr = MyRepr() |
| 634 |
self.assertEqual(aRepr.repr(sys.stdin), "<stdin>") |
| 635 |
|
| 636 |
def test_custom_repr_class_with_spaces(self): |
| 637 |
class TypeWithSpaces: |
| 638 |
pass |
| 639 |
|
| 640 |
t = TypeWithSpaces() |
| 641 |
type(t).__name__ = "type with spaces" |
| 642 |
self.assertEqual(type(t).__name__, "type with spaces") |
| 643 |
|
| 644 |
class MyRepr(Repr): |
| 645 |
def repr_type_with_spaces(self, obj, level): |
| 646 |
return "Type With Spaces" |
| 647 |
|
| 648 |
|
| 649 |
aRepr = MyRepr() |
| 650 |
self.assertEqual(aRepr.repr(t), "Type With Spaces") |
| 651 |
|
| 652 |
def write_file(path, text): |
| 653 |
with open(path, 'w', encoding='ASCII') as fp: |
| 654 |
fp.write(text) |
| 655 |
|
| 656 |
class LongReprTest(unittest.TestCase): |
| 657 |
longname = 'areallylongpackageandmodulenametotestreprtruncation' |
| 658 |
|
| 659 |
def setUp(self): |
| 660 |
self.pkgname = os.path.join(self.longname) |
| 661 |
self.subpkgname = os.path.join(self.longname, self.longname) |
| 662 |
# Make the package and subpackage |
| 663 |
shutil.rmtree(self.pkgname, ignore_errors=True) |
| 664 |
os.mkdir(self.pkgname) |
| 665 |
create_empty_file(os.path.join(self.pkgname, '__init__.py')) |
| 666 |
shutil.rmtree(self.subpkgname, ignore_errors=True) |
| 667 |
os.mkdir(self.subpkgname) |
| 668 |
create_empty_file(os.path.join(self.subpkgname, '__init__.py')) |
| 669 |
# Remember where we are |
| 670 |
self.here = os.getcwd() |
| 671 |
sys.path.insert(0, self.here) |
| 672 |
# When regrtest is run with its -j option, this command alone is not |
| 673 |
# enough. |
| 674 |
importlib.invalidate_caches() |
| 675 |
|
| 676 |
def tearDown(self): |
| 677 |
actions = [] |
| 678 |
for dirpath, dirnames, filenames in os.walk(self.pkgname): |
| 679 |
for name in dirnames + filenames: |
| 680 |
actions.append(os.path.join(dirpath, name)) |
| 681 |
actions.append(self.pkgname) |
| 682 |
actions.sort() |
| 683 |
actions.reverse() |
| 684 |
for p in actions: |
| 685 |
if os.path.isdir(p): |
| 686 |
os.rmdir(p) |
| 687 |
else: |
| 688 |
os.remove(p) |
| 689 |
del sys.path[0] |
| 690 |
|
| 691 |
def _check_path_limitations(self, module_name): |
| 692 |
# base directory |
| 693 |
source_path_len = len(self.here) |
| 694 |
# a path separator + `longname` (twice) |
| 695 |
source_path_len += 2 * (len(self.longname) + 1) |
| 696 |
# a path separator + `module_name` + ".py" |
| 697 |
source_path_len += len(module_name) + 1 + len(".py") |
| 698 |
cached_path_len = (source_path_len + |
| 699 |
len(importlib.util.cache_from_source("x.py")) - len("x.py")) |
| 700 |
if os.name == 'nt' and cached_path_len >= 258: |
| 701 |
# Under Windows, the max path len is 260 including C's terminating |
| 702 |
# NUL character. |
| 703 |
# (see http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx#maxpath) |
| 704 |
self.skipTest("test paths too long (%d characters) for Windows' 260 character limit" |
| 705 |
% cached_path_len) |
| 706 |
elif os.name == 'nt' and verbose: |
| 707 |
print("cached_path_len =", cached_path_len) |
| 708 |
|
| 709 |
def test_module(self): |
| 710 |
self.maxDiff = None |
| 711 |
self._check_path_limitations(self.pkgname) |
| 712 |
create_empty_file(os.path.join(self.subpkgname, self.pkgname + '.py')) |
| 713 |
importlib.invalidate_caches() |
| 714 |
from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation |
| 715 |
module = areallylongpackageandmodulenametotestreprtruncation |
| 716 |
self.assertEqual(repr(module), "<module %r from %r>" % (module.__name__, module.__file__)) |
| 717 |
self.assertEqual(repr(sys), "<module 'sys' (built-in)>") |
| 718 |
|
| 719 |
def test_type(self): |
| 720 |
self._check_path_limitations('foo') |
| 721 |
eq = self.assertEqual |
| 722 |
write_file(os.path.join(self.subpkgname, 'foo.py'), '''\ |
| 723 |
class foo(object): |
| 724 |
pass |
| 725 |
''') |
| 726 |
importlib.invalidate_caches() |
| 727 |
from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import foo |
| 728 |
eq(repr(foo.foo), |
| 729 |
"<class '%s.foo'>" % foo.__name__) |
| 730 |
|
| 731 |
@unittest.skip('need a suitable object') |
| 732 |
def test_object(self): |
| 733 |
# XXX Test the repr of a type with a really long tp_name but with no |
| 734 |
# tp_repr. WIBNI we had ::Inline? :) |
| 735 |
pass |
| 736 |
|
| 737 |
def test_class(self): |
| 738 |
self._check_path_limitations('bar') |
| 739 |
write_file(os.path.join(self.subpkgname, 'bar.py'), '''\ |
| 740 |
class bar: |
| 741 |
pass |
| 742 |
''') |
| 743 |
importlib.invalidate_caches() |
| 744 |
from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar |
| 745 |
# Module name may be prefixed with "test.", depending on how run. |
| 746 |
self.assertEqual(repr(bar.bar), "<class '%s.bar'>" % bar.__name__) |
| 747 |
|
| 748 |
def test_instance(self): |
| 749 |
self._check_path_limitations('baz') |
| 750 |
write_file(os.path.join(self.subpkgname, 'baz.py'), '''\ |
| 751 |
class baz: |
| 752 |
pass |
| 753 |
''') |
| 754 |
importlib.invalidate_caches() |
| 755 |
from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz |
| 756 |
ibaz = baz.baz() |
| 757 |
self.assertStartsWith(repr(ibaz), |
| 758 |
"<%s.baz object at 0x" % baz.__name__) |
| 759 |
|
| 760 |
def test_method(self): |
| 761 |
self._check_path_limitations('qux') |
| 762 |
eq = self.assertEqual |
| 763 |
write_file(os.path.join(self.subpkgname, 'qux.py'), '''\ |
| 764 |
class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: |
| 765 |
def amethod(self): pass |
| 766 |
''') |
| 767 |
importlib.invalidate_caches() |
| 768 |
from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import qux |
| 769 |
# Unbound methods first |
| 770 |
r = repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod) |
| 771 |
self.assertStartsWith(r, '<function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod') |
| 772 |
# Bound method next |
| 773 |
iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() |
| 774 |
r = repr(iqux.amethod) |
| 775 |
self.assertStartsWith(r, |
| 776 |
'<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa object at 0x' \ |
| 777 |
% (qux.__name__,) ) |
| 778 |
|
| 779 |
@unittest.skip('needs a built-in function with a really long name') |
| 780 |
def test_builtin_function(self): |
| 781 |
# XXX test built-in functions and methods with really long names |
| 782 |
pass |
| 783 |
|
| 784 |
class ClassWithRepr: |
| 785 |
def __init__(self, s): |
| 786 |
self.s = s |
| 787 |
def __repr__(self): |
| 788 |
return "ClassWithRepr(%r)" % self.s |
| 789 |
|
| 790 |
|
| 791 |
class ClassWithFailingRepr: |
| 792 |
def __repr__(self): |
| 793 |
raise Exception("This should be caught by Repr.repr_instance") |
| 794 |
|
| 795 |
class MyContainer: |
| 796 |
'Helper class for TestRecursiveRepr' |
| 797 |
def __init__(self, values): |
| 798 |
self.values = list(values) |
| 799 |
def append(self, value): |
| 800 |
self.values.append(value) |
| 801 |
@recursive_repr() |
| 802 |
def __repr__(self): |
| 803 |
return '<' + ', '.join(map(str, self.values)) + '>' |
| 804 |
|
| 805 |
class MyContainer2(MyContainer): |
| 806 |
@recursive_repr('+++') |
| 807 |
def __repr__(self): |
| 808 |
return '<' + ', '.join(map(str, self.values)) + '>' |
| 809 |
|
| 810 |
class MyContainer3: |
| 811 |
def __repr__(self): |
| 812 |
'Test document content' |
| 813 |
pass |
| 814 |
wrapped = __repr__ |
| 815 |
wrapper = recursive_repr()(wrapped) |
| 816 |
|
| 817 |
class TestRecursiveRepr(unittest.TestCase): |
| 818 |
def test_recursive_repr(self): |
| 819 |
m = MyContainer(list('abcde')) |
| 820 |
m.append(m) |
| 821 |
m.append('x') |
| 822 |
m.append(m) |
| 823 |
self.assertEqual(repr(m), '<a, b, c, d, e, ..., x, ...>') |
| 824 |
m = MyContainer2(list('abcde')) |
| 825 |
m.append(m) |
| 826 |
m.append('x') |
| 827 |
m.append(m) |
| 828 |
self.assertEqual(repr(m), '<a, b, c, d, e, +++, x, +++>') |
| 829 |
|
| 830 |
def test_assigned_attributes(self): |
| 831 |
from functools import WRAPPER_ASSIGNMENTS as assigned |
| 832 |
wrapped = MyContainer3.wrapped |
| 833 |
wrapper = MyContainer3.wrapper |
| 834 |
for name in assigned: |
| 835 |
self.assertIs(getattr(wrapper, name), getattr(wrapped, name)) |
| 836 |
|
| 837 |
def test__wrapped__(self): |
| 838 |
class X: |
| 839 |
def __repr__(self): |
| 840 |
return 'X()' |
| 841 |
f = __repr__ # save reference to check it later |
| 842 |
__repr__ = recursive_repr()(__repr__) |
| 843 |
|
| 844 |
self.assertIs(X.f, X.__repr__.__wrapped__) |
| 845 |
|
| 846 |
def test__type_params__(self): |
| 847 |
class My: |
| 848 |
@recursive_repr() |
| 849 |
def __repr__[T: str](self, default: T = '') -> str: |
| 850 |
return default |
| 851 |
|
| 852 |
type_params = My().__repr__.__type_params__ |
| 853 |
self.assertEqual(len(type_params), 1) |
| 854 |
self.assertEqual(type_params[0].__name__, 'T') |
| 855 |
self.assertEqual(type_params[0].__bound__, str) |
| 856 |
|
| 857 |
def test_annotations(self): |
| 858 |
class My: |
| 859 |
@recursive_repr() |
| 860 |
def __repr__(self, default: undefined = ...): |
| 861 |
return default |
| 862 |
|
| 863 |
annotations = annotationlib.get_annotations( |
| 864 |
My.__repr__, format=annotationlib.Format.FORWARDREF |
| 865 |
) |
| 866 |
self.assertEqual( |
| 867 |
annotations, |
| 868 |
{'default': EqualToForwardRef("undefined", owner=My.__repr__)} |
| 869 |
) |
| 870 |
|
| 871 |
if __name__ == "__main__": |
| 872 |
unittest.main() |