| 1 |
"Test the functionality of Python classes implementing operators." |
| 2 |
|
| 3 |
import unittest |
| 4 |
from test import support |
| 5 |
from test.support import cpython_only, import_helper, script_helper |
| 6 |
|
| 7 |
testmeths = [ |
| 8 |
|
| 9 |
# Binary operations |
| 10 |
"add", |
| 11 |
"radd", |
| 12 |
"sub", |
| 13 |
"rsub", |
| 14 |
"mul", |
| 15 |
"rmul", |
| 16 |
"matmul", |
| 17 |
"rmatmul", |
| 18 |
"truediv", |
| 19 |
"rtruediv", |
| 20 |
"floordiv", |
| 21 |
"rfloordiv", |
| 22 |
"mod", |
| 23 |
"rmod", |
| 24 |
"divmod", |
| 25 |
"rdivmod", |
| 26 |
"pow", |
| 27 |
"rpow", |
| 28 |
"rshift", |
| 29 |
"rrshift", |
| 30 |
"lshift", |
| 31 |
"rlshift", |
| 32 |
"and", |
| 33 |
"rand", |
| 34 |
"or", |
| 35 |
"ror", |
| 36 |
"xor", |
| 37 |
"rxor", |
| 38 |
|
| 39 |
# List/dict operations |
| 40 |
"contains", |
| 41 |
"getitem", |
| 42 |
"setitem", |
| 43 |
"delitem", |
| 44 |
|
| 45 |
# Unary operations |
| 46 |
"neg", |
| 47 |
"pos", |
| 48 |
"abs", |
| 49 |
|
| 50 |
# generic operations |
| 51 |
"init", |
| 52 |
] |
| 53 |
|
| 54 |
# These need to return something other than None |
| 55 |
# "hash", |
| 56 |
# "str", |
| 57 |
# "repr", |
| 58 |
# "int", |
| 59 |
# "float", |
| 60 |
|
| 61 |
# These are separate because they can influence the test of other methods. |
| 62 |
# "getattr", |
| 63 |
# "setattr", |
| 64 |
# "delattr", |
| 65 |
|
| 66 |
callLst = [] |
| 67 |
def trackCall(f): |
| 68 |
def track(*args, **kwargs): |
| 69 |
callLst.append((f.__name__, args)) |
| 70 |
return f(*args, **kwargs) |
| 71 |
return track |
| 72 |
|
| 73 |
statictests = """ |
| 74 |
@trackCall |
| 75 |
def __hash__(self, *args): |
| 76 |
return hash(id(self)) |
| 77 |
|
| 78 |
@trackCall |
| 79 |
def __str__(self, *args): |
| 80 |
return "AllTests" |
| 81 |
|
| 82 |
@trackCall |
| 83 |
def __repr__(self, *args): |
| 84 |
return "AllTests" |
| 85 |
|
| 86 |
@trackCall |
| 87 |
def __int__(self, *args): |
| 88 |
return 1 |
| 89 |
|
| 90 |
@trackCall |
| 91 |
def __index__(self, *args): |
| 92 |
return 1 |
| 93 |
|
| 94 |
@trackCall |
| 95 |
def __float__(self, *args): |
| 96 |
return 1.0 |
| 97 |
|
| 98 |
@trackCall |
| 99 |
def __eq__(self, *args): |
| 100 |
return True |
| 101 |
|
| 102 |
@trackCall |
| 103 |
def __ne__(self, *args): |
| 104 |
return False |
| 105 |
|
| 106 |
@trackCall |
| 107 |
def __lt__(self, *args): |
| 108 |
return False |
| 109 |
|
| 110 |
@trackCall |
| 111 |
def __le__(self, *args): |
| 112 |
return True |
| 113 |
|
| 114 |
@trackCall |
| 115 |
def __gt__(self, *args): |
| 116 |
return False |
| 117 |
|
| 118 |
@trackCall |
| 119 |
def __ge__(self, *args): |
| 120 |
return True |
| 121 |
""" |
| 122 |
|
| 123 |
# Synthesize all the other AllTests methods from the names in testmeths. |
| 124 |
|
| 125 |
method_template = """\ |
| 126 |
@trackCall |
| 127 |
def __%s__(self, *args): |
| 128 |
pass |
| 129 |
""" |
| 130 |
|
| 131 |
d = {} |
| 132 |
exec(statictests, globals(), d) |
| 133 |
for method in testmeths: |
| 134 |
exec(method_template % method, globals(), d) |
| 135 |
AllTests = type("AllTests", (object,), d) |
| 136 |
del d, statictests, method, method_template |
| 137 |
|
| 138 |
@support.thread_unsafe("callLst is shared between threads") |
| 139 |
class ClassTests(unittest.TestCase): |
| 140 |
def setUp(self): |
| 141 |
callLst[:] = [] |
| 142 |
|
| 143 |
def assertCallStack(self, expected_calls): |
| 144 |
actualCallList = callLst[:] # need to copy because the comparison below will add |
| 145 |
# additional calls to callLst |
| 146 |
if expected_calls != actualCallList: |
| 147 |
self.fail("Expected call list:\n %s\ndoes not match actual call list\n %s" % |
| 148 |
(expected_calls, actualCallList)) |
| 149 |
|
| 150 |
def testInit(self): |
| 151 |
foo = AllTests() |
| 152 |
self.assertCallStack([("__init__", (foo,))]) |
| 153 |
|
| 154 |
def testBinaryOps(self): |
| 155 |
testme = AllTests() |
| 156 |
# Binary operations |
| 157 |
|
| 158 |
callLst[:] = [] |
| 159 |
testme + 1 |
| 160 |
self.assertCallStack([("__add__", (testme, 1))]) |
| 161 |
|
| 162 |
callLst[:] = [] |
| 163 |
1 + testme |
| 164 |
self.assertCallStack([("__radd__", (testme, 1))]) |
| 165 |
|
| 166 |
callLst[:] = [] |
| 167 |
testme - 1 |
| 168 |
self.assertCallStack([("__sub__", (testme, 1))]) |
| 169 |
|
| 170 |
callLst[:] = [] |
| 171 |
1 - testme |
| 172 |
self.assertCallStack([("__rsub__", (testme, 1))]) |
| 173 |
|
| 174 |
callLst[:] = [] |
| 175 |
testme * 1 |
| 176 |
self.assertCallStack([("__mul__", (testme, 1))]) |
| 177 |
|
| 178 |
callLst[:] = [] |
| 179 |
1 * testme |
| 180 |
self.assertCallStack([("__rmul__", (testme, 1))]) |
| 181 |
|
| 182 |
callLst[:] = [] |
| 183 |
testme @ 1 |
| 184 |
self.assertCallStack([("__matmul__", (testme, 1))]) |
| 185 |
|
| 186 |
callLst[:] = [] |
| 187 |
1 @ testme |
| 188 |
self.assertCallStack([("__rmatmul__", (testme, 1))]) |
| 189 |
|
| 190 |
callLst[:] = [] |
| 191 |
testme / 1 |
| 192 |
self.assertCallStack([("__truediv__", (testme, 1))]) |
| 193 |
|
| 194 |
|
| 195 |
callLst[:] = [] |
| 196 |
1 / testme |
| 197 |
self.assertCallStack([("__rtruediv__", (testme, 1))]) |
| 198 |
|
| 199 |
callLst[:] = [] |
| 200 |
testme // 1 |
| 201 |
self.assertCallStack([("__floordiv__", (testme, 1))]) |
| 202 |
|
| 203 |
|
| 204 |
callLst[:] = [] |
| 205 |
1 // testme |
| 206 |
self.assertCallStack([("__rfloordiv__", (testme, 1))]) |
| 207 |
|
| 208 |
callLst[:] = [] |
| 209 |
testme % 1 |
| 210 |
self.assertCallStack([("__mod__", (testme, 1))]) |
| 211 |
|
| 212 |
callLst[:] = [] |
| 213 |
1 % testme |
| 214 |
self.assertCallStack([("__rmod__", (testme, 1))]) |
| 215 |
|
| 216 |
|
| 217 |
callLst[:] = [] |
| 218 |
divmod(testme,1) |
| 219 |
self.assertCallStack([("__divmod__", (testme, 1))]) |
| 220 |
|
| 221 |
callLst[:] = [] |
| 222 |
divmod(1, testme) |
| 223 |
self.assertCallStack([("__rdivmod__", (testme, 1))]) |
| 224 |
|
| 225 |
callLst[:] = [] |
| 226 |
testme ** 1 |
| 227 |
self.assertCallStack([("__pow__", (testme, 1))]) |
| 228 |
|
| 229 |
callLst[:] = [] |
| 230 |
1 ** testme |
| 231 |
self.assertCallStack([("__rpow__", (testme, 1))]) |
| 232 |
|
| 233 |
callLst[:] = [] |
| 234 |
testme >> 1 |
| 235 |
self.assertCallStack([("__rshift__", (testme, 1))]) |
| 236 |
|
| 237 |
callLst[:] = [] |
| 238 |
1 >> testme |
| 239 |
self.assertCallStack([("__rrshift__", (testme, 1))]) |
| 240 |
|
| 241 |
callLst[:] = [] |
| 242 |
testme << 1 |
| 243 |
self.assertCallStack([("__lshift__", (testme, 1))]) |
| 244 |
|
| 245 |
callLst[:] = [] |
| 246 |
1 << testme |
| 247 |
self.assertCallStack([("__rlshift__", (testme, 1))]) |
| 248 |
|
| 249 |
callLst[:] = [] |
| 250 |
testme & 1 |
| 251 |
self.assertCallStack([("__and__", (testme, 1))]) |
| 252 |
|
| 253 |
callLst[:] = [] |
| 254 |
1 & testme |
| 255 |
self.assertCallStack([("__rand__", (testme, 1))]) |
| 256 |
|
| 257 |
callLst[:] = [] |
| 258 |
testme | 1 |
| 259 |
self.assertCallStack([("__or__", (testme, 1))]) |
| 260 |
|
| 261 |
callLst[:] = [] |
| 262 |
1 | testme |
| 263 |
self.assertCallStack([("__ror__", (testme, 1))]) |
| 264 |
|
| 265 |
callLst[:] = [] |
| 266 |
testme ^ 1 |
| 267 |
self.assertCallStack([("__xor__", (testme, 1))]) |
| 268 |
|
| 269 |
callLst[:] = [] |
| 270 |
1 ^ testme |
| 271 |
self.assertCallStack([("__rxor__", (testme, 1))]) |
| 272 |
|
| 273 |
def testListAndDictOps(self): |
| 274 |
testme = AllTests() |
| 275 |
|
| 276 |
# List/dict operations |
| 277 |
|
| 278 |
class Empty: pass |
| 279 |
|
| 280 |
try: |
| 281 |
1 in Empty() |
| 282 |
self.fail('failed, should have raised TypeError') |
| 283 |
except TypeError: |
| 284 |
pass |
| 285 |
|
| 286 |
callLst[:] = [] |
| 287 |
1 in testme |
| 288 |
self.assertCallStack([('__contains__', (testme, 1))]) |
| 289 |
|
| 290 |
callLst[:] = [] |
| 291 |
testme[1] |
| 292 |
self.assertCallStack([('__getitem__', (testme, 1))]) |
| 293 |
|
| 294 |
callLst[:] = [] |
| 295 |
testme[1] = 1 |
| 296 |
self.assertCallStack([('__setitem__', (testme, 1, 1))]) |
| 297 |
|
| 298 |
callLst[:] = [] |
| 299 |
del testme[1] |
| 300 |
self.assertCallStack([('__delitem__', (testme, 1))]) |
| 301 |
|
| 302 |
callLst[:] = [] |
| 303 |
testme[:42] |
| 304 |
self.assertCallStack([('__getitem__', (testme, slice(None, 42)))]) |
| 305 |
|
| 306 |
callLst[:] = [] |
| 307 |
testme[:42] = "The Answer" |
| 308 |
self.assertCallStack([('__setitem__', (testme, slice(None, 42), |
| 309 |
"The Answer"))]) |
| 310 |
|
| 311 |
callLst[:] = [] |
| 312 |
del testme[:42] |
| 313 |
self.assertCallStack([('__delitem__', (testme, slice(None, 42)))]) |
| 314 |
|
| 315 |
callLst[:] = [] |
| 316 |
testme[2:1024:10] |
| 317 |
self.assertCallStack([('__getitem__', (testme, slice(2, 1024, 10)))]) |
| 318 |
|
| 319 |
callLst[:] = [] |
| 320 |
testme[2:1024:10] = "A lot" |
| 321 |
self.assertCallStack([('__setitem__', (testme, slice(2, 1024, 10), |
| 322 |
"A lot"))]) |
| 323 |
callLst[:] = [] |
| 324 |
del testme[2:1024:10] |
| 325 |
self.assertCallStack([('__delitem__', (testme, slice(2, 1024, 10)))]) |
| 326 |
|
| 327 |
callLst[:] = [] |
| 328 |
testme[:42, ..., :24:, 24, 100] |
| 329 |
self.assertCallStack([('__getitem__', (testme, (slice(None, 42, None), |
| 330 |
Ellipsis, |
| 331 |
slice(None, 24, None), |
| 332 |
24, 100)))]) |
| 333 |
callLst[:] = [] |
| 334 |
testme[:42, ..., :24:, 24, 100] = "Strange" |
| 335 |
self.assertCallStack([('__setitem__', (testme, (slice(None, 42, None), |
| 336 |
Ellipsis, |
| 337 |
slice(None, 24, None), |
| 338 |
24, 100), "Strange"))]) |
| 339 |
callLst[:] = [] |
| 340 |
del testme[:42, ..., :24:, 24, 100] |
| 341 |
self.assertCallStack([('__delitem__', (testme, (slice(None, 42, None), |
| 342 |
Ellipsis, |
| 343 |
slice(None, 24, None), |
| 344 |
24, 100)))]) |
| 345 |
|
| 346 |
def testUnaryOps(self): |
| 347 |
testme = AllTests() |
| 348 |
|
| 349 |
callLst[:] = [] |
| 350 |
-testme |
| 351 |
self.assertCallStack([('__neg__', (testme,))]) |
| 352 |
callLst[:] = [] |
| 353 |
+testme |
| 354 |
self.assertCallStack([('__pos__', (testme,))]) |
| 355 |
callLst[:] = [] |
| 356 |
abs(testme) |
| 357 |
self.assertCallStack([('__abs__', (testme,))]) |
| 358 |
callLst[:] = [] |
| 359 |
int(testme) |
| 360 |
self.assertCallStack([('__int__', (testme,))]) |
| 361 |
callLst[:] = [] |
| 362 |
float(testme) |
| 363 |
self.assertCallStack([('__float__', (testme,))]) |
| 364 |
callLst[:] = [] |
| 365 |
oct(testme) |
| 366 |
self.assertCallStack([('__index__', (testme,))]) |
| 367 |
callLst[:] = [] |
| 368 |
hex(testme) |
| 369 |
self.assertCallStack([('__index__', (testme,))]) |
| 370 |
|
| 371 |
|
| 372 |
def testMisc(self): |
| 373 |
testme = AllTests() |
| 374 |
|
| 375 |
callLst[:] = [] |
| 376 |
hash(testme) |
| 377 |
self.assertCallStack([('__hash__', (testme,))]) |
| 378 |
|
| 379 |
callLst[:] = [] |
| 380 |
repr(testme) |
| 381 |
self.assertCallStack([('__repr__', (testme,))]) |
| 382 |
|
| 383 |
callLst[:] = [] |
| 384 |
str(testme) |
| 385 |
self.assertCallStack([('__str__', (testme,))]) |
| 386 |
|
| 387 |
callLst[:] = [] |
| 388 |
testme == 1 |
| 389 |
self.assertCallStack([('__eq__', (testme, 1))]) |
| 390 |
|
| 391 |
callLst[:] = [] |
| 392 |
testme < 1 |
| 393 |
self.assertCallStack([('__lt__', (testme, 1))]) |
| 394 |
|
| 395 |
callLst[:] = [] |
| 396 |
testme > 1 |
| 397 |
self.assertCallStack([('__gt__', (testme, 1))]) |
| 398 |
|
| 399 |
callLst[:] = [] |
| 400 |
testme != 1 |
| 401 |
self.assertCallStack([('__ne__', (testme, 1))]) |
| 402 |
|
| 403 |
callLst[:] = [] |
| 404 |
1 == testme |
| 405 |
self.assertCallStack([('__eq__', (1, testme))]) |
| 406 |
|
| 407 |
callLst[:] = [] |
| 408 |
1 < testme |
| 409 |
self.assertCallStack([('__gt__', (1, testme))]) |
| 410 |
|
| 411 |
callLst[:] = [] |
| 412 |
1 > testme |
| 413 |
self.assertCallStack([('__lt__', (1, testme))]) |
| 414 |
|
| 415 |
callLst[:] = [] |
| 416 |
1 != testme |
| 417 |
self.assertCallStack([('__ne__', (1, testme))]) |
| 418 |
|
| 419 |
|
| 420 |
def testGetSetAndDel(self): |
| 421 |
# Interfering tests |
| 422 |
class ExtraTests(AllTests): |
| 423 |
@trackCall |
| 424 |
def __getattr__(self, *args): |
| 425 |
return "SomeVal" |
| 426 |
|
| 427 |
@trackCall |
| 428 |
def __setattr__(self, *args): |
| 429 |
pass |
| 430 |
|
| 431 |
@trackCall |
| 432 |
def __delattr__(self, *args): |
| 433 |
pass |
| 434 |
|
| 435 |
testme = ExtraTests() |
| 436 |
|
| 437 |
callLst[:] = [] |
| 438 |
testme.spam |
| 439 |
self.assertCallStack([('__getattr__', (testme, "spam"))]) |
| 440 |
|
| 441 |
callLst[:] = [] |
| 442 |
testme.eggs = "spam, spam, spam and ham" |
| 443 |
self.assertCallStack([('__setattr__', (testme, "eggs", |
| 444 |
"spam, spam, spam and ham"))]) |
| 445 |
|
| 446 |
callLst[:] = [] |
| 447 |
del testme.cardinal |
| 448 |
self.assertCallStack([('__delattr__', (testme, "cardinal"))]) |
| 449 |
|
| 450 |
def testHasAttrString(self): |
| 451 |
import sys |
| 452 |
from test.support import import_helper |
| 453 |
_testlimitedcapi = import_helper.import_module('_testlimitedcapi') |
| 454 |
|
| 455 |
class A: |
| 456 |
def __init__(self): |
| 457 |
self.attr = 1 |
| 458 |
|
| 459 |
a = A() |
| 460 |
self.assertEqual(_testlimitedcapi.object_hasattrstring(a, b"attr"), 1) |
| 461 |
self.assertEqual(_testlimitedcapi.object_hasattrstring(a, b"noattr"), 0) |
| 462 |
self.assertIsNone(sys.exception()) |
| 463 |
|
| 464 |
def testDel(self): |
| 465 |
x = [] |
| 466 |
|
| 467 |
class DelTest: |
| 468 |
def __del__(self): |
| 469 |
x.append("crab people, crab people") |
| 470 |
testme = DelTest() |
| 471 |
del testme |
| 472 |
import gc |
| 473 |
gc.collect() |
| 474 |
self.assertEqual(["crab people, crab people"], x) |
| 475 |
|
| 476 |
def testBadTypeReturned(self): |
| 477 |
# return values of some method are type-checked |
| 478 |
class BadTypeClass: |
| 479 |
def __int__(self): |
| 480 |
return None |
| 481 |
__float__ = __int__ |
| 482 |
__complex__ = __int__ |
| 483 |
__str__ = __int__ |
| 484 |
__repr__ = __int__ |
| 485 |
__bytes__ = __int__ |
| 486 |
__bool__ = __int__ |
| 487 |
__index__ = __int__ |
| 488 |
def index(x): |
| 489 |
return [][x] |
| 490 |
|
| 491 |
for f in [float, complex, str, repr, bytes, bin, oct, hex, bool, index]: |
| 492 |
self.assertRaises(TypeError, f, BadTypeClass()) |
| 493 |
|
| 494 |
def testHashStuff(self): |
| 495 |
# Test correct errors from hash() on objects with comparisons but |
| 496 |
# no __hash__ |
| 497 |
|
| 498 |
class C0: |
| 499 |
pass |
| 500 |
|
| 501 |
hash(C0()) # This should work; the next two should raise TypeError |
| 502 |
|
| 503 |
class C2: |
| 504 |
def __eq__(self, other): return 1 |
| 505 |
|
| 506 |
self.assertRaises(TypeError, hash, C2()) |
| 507 |
|
| 508 |
def testPredefinedAttrs(self): |
| 509 |
o = object() |
| 510 |
|
| 511 |
class Custom: |
| 512 |
pass |
| 513 |
|
| 514 |
c = Custom() |
| 515 |
|
| 516 |
methods = ( |
| 517 |
'__class__', '__delattr__', '__dir__', '__eq__', '__format__', |
| 518 |
'__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', |
| 519 |
'__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', |
| 520 |
'__new__', '__reduce__', '__reduce_ex__', '__repr__', |
| 521 |
'__setattr__', '__sizeof__', '__str__', '__subclasshook__' |
| 522 |
) |
| 523 |
for name in methods: |
| 524 |
with self.subTest(name): |
| 525 |
self.assertTrue(callable(getattr(object, name, None))) |
| 526 |
self.assertTrue(callable(getattr(o, name, None))) |
| 527 |
self.assertTrue(callable(getattr(Custom, name, None))) |
| 528 |
self.assertTrue(callable(getattr(c, name, None))) |
| 529 |
|
| 530 |
not_defined = [ |
| 531 |
'__abs__', '__aenter__', '__aexit__', '__aiter__', '__anext__', |
| 532 |
'__await__', '__bool__', '__bytes__', '__ceil__', |
| 533 |
'__complex__', '__contains__', '__del__', '__delete__', |
| 534 |
'__delitem__', '__divmod__', '__enter__', '__exit__', |
| 535 |
'__float__', '__floor__', '__get__', '__getattr__', '__getitem__', |
| 536 |
'__index__', '__int__', '__invert__', '__iter__', '__len__', |
| 537 |
'__length_hint__', '__missing__', '__neg__', '__next__', |
| 538 |
'__objclass__', '__pos__', '__rdivmod__', '__reversed__', |
| 539 |
'__round__', '__set__', '__setitem__', '__trunc__' |
| 540 |
] |
| 541 |
augment = ( |
| 542 |
'add', 'and', 'floordiv', 'lshift', 'matmul', 'mod', 'mul', 'pow', |
| 543 |
'rshift', 'sub', 'truediv', 'xor' |
| 544 |
) |
| 545 |
not_defined.extend(map("__{}__".format, augment)) |
| 546 |
not_defined.extend(map("__r{}__".format, augment)) |
| 547 |
not_defined.extend(map("__i{}__".format, augment)) |
| 548 |
for name in not_defined: |
| 549 |
with self.subTest(name): |
| 550 |
self.assertFalse(hasattr(object, name)) |
| 551 |
self.assertFalse(hasattr(o, name)) |
| 552 |
self.assertFalse(hasattr(Custom, name)) |
| 553 |
self.assertFalse(hasattr(c, name)) |
| 554 |
|
| 555 |
# __call__() is defined on the metaclass but not the class |
| 556 |
self.assertFalse(hasattr(o, "__call__")) |
| 557 |
self.assertFalse(hasattr(c, "__call__")) |
| 558 |
|
| 559 |
@support.skip_emscripten_stack_overflow() |
| 560 |
@support.skip_wasi_stack_overflow() |
| 561 |
def testSFBug532646(self): |
| 562 |
# Test for SF bug 532646 |
| 563 |
|
| 564 |
class A: |
| 565 |
pass |
| 566 |
A.__call__ = A() |
| 567 |
a = A() |
| 568 |
|
| 569 |
try: |
| 570 |
a() # This should not segfault |
| 571 |
except RecursionError: |
| 572 |
pass |
| 573 |
else: |
| 574 |
self.fail("Failed to raise RecursionError") |
| 575 |
|
| 576 |
def testForExceptionsRaisedInInstanceGetattr2(self): |
| 577 |
# Tests for exceptions raised in instance_getattr2(). |
| 578 |
|
| 579 |
def booh(self): |
| 580 |
raise AttributeError("booh") |
| 581 |
|
| 582 |
class A: |
| 583 |
a = property(booh) |
| 584 |
try: |
| 585 |
A().a # Raised AttributeError: A instance has no attribute 'a' |
| 586 |
except AttributeError as x: |
| 587 |
if str(x) != "booh": |
| 588 |
self.fail("attribute error for A().a got masked: %s" % x) |
| 589 |
|
| 590 |
class E: |
| 591 |
__eq__ = property(booh) |
| 592 |
E() == E() # In debug mode, caused a C-level assert() to fail |
| 593 |
|
| 594 |
class I: |
| 595 |
__init__ = property(booh) |
| 596 |
try: |
| 597 |
# In debug mode, printed XXX undetected error and |
| 598 |
# raises AttributeError |
| 599 |
I() |
| 600 |
except AttributeError: |
| 601 |
pass |
| 602 |
else: |
| 603 |
self.fail("attribute error for I.__init__ got masked") |
| 604 |
|
| 605 |
def assertNotOrderable(self, a, b): |
| 606 |
with self.assertRaises(TypeError): |
| 607 |
a < b |
| 608 |
with self.assertRaises(TypeError): |
| 609 |
a > b |
| 610 |
with self.assertRaises(TypeError): |
| 611 |
a <= b |
| 612 |
with self.assertRaises(TypeError): |
| 613 |
a >= b |
| 614 |
|
| 615 |
def testHashComparisonOfMethods(self): |
| 616 |
# Test comparison and hash of methods |
| 617 |
class A: |
| 618 |
def __init__(self, x): |
| 619 |
self.x = x |
| 620 |
def f(self): |
| 621 |
pass |
| 622 |
def g(self): |
| 623 |
pass |
| 624 |
def __eq__(self, other): |
| 625 |
return True |
| 626 |
def __hash__(self): |
| 627 |
raise TypeError |
| 628 |
class B(A): |
| 629 |
pass |
| 630 |
|
| 631 |
a1 = A(1) |
| 632 |
a2 = A(1) |
| 633 |
self.assertTrue(a1.f == a1.f) |
| 634 |
self.assertFalse(a1.f != a1.f) |
| 635 |
self.assertFalse(a1.f == a2.f) |
| 636 |
self.assertTrue(a1.f != a2.f) |
| 637 |
self.assertFalse(a1.f == a1.g) |
| 638 |
self.assertTrue(a1.f != a1.g) |
| 639 |
self.assertNotOrderable(a1.f, a1.f) |
| 640 |
self.assertEqual(hash(a1.f), hash(a1.f)) |
| 641 |
|
| 642 |
self.assertFalse(A.f == a1.f) |
| 643 |
self.assertTrue(A.f != a1.f) |
| 644 |
self.assertFalse(A.f == A.g) |
| 645 |
self.assertTrue(A.f != A.g) |
| 646 |
self.assertTrue(B.f == A.f) |
| 647 |
self.assertFalse(B.f != A.f) |
| 648 |
self.assertNotOrderable(A.f, A.f) |
| 649 |
self.assertEqual(hash(B.f), hash(A.f)) |
| 650 |
|
| 651 |
# the following triggers a SystemError in 2.4 |
| 652 |
a = A(hash(A.f)^(-1)) |
| 653 |
hash(a.f) |
| 654 |
|
| 655 |
def testSetattrWrapperNameIntern(self): |
| 656 |
# Issue #25794: __setattr__ should intern the attribute name |
| 657 |
class A: |
| 658 |
pass |
| 659 |
|
| 660 |
def add(self, other): |
| 661 |
return 'summa' |
| 662 |
|
| 663 |
name = str(b'__add__', 'ascii') # shouldn't be optimized |
| 664 |
self.assertIsNot(name, '__add__') # not interned |
| 665 |
type.__setattr__(A, name, add) |
| 666 |
self.assertEqual(A() + 1, 'summa') |
| 667 |
|
| 668 |
name2 = str(b'__add__', 'ascii') |
| 669 |
self.assertIsNot(name2, '__add__') |
| 670 |
self.assertIsNot(name2, name) |
| 671 |
type.__delattr__(A, name2) |
| 672 |
with self.assertRaises(TypeError): |
| 673 |
A() + 1 |
| 674 |
|
| 675 |
def testSetattrNonStringName(self): |
| 676 |
class A: |
| 677 |
pass |
| 678 |
|
| 679 |
with self.assertRaises(TypeError): |
| 680 |
type.__setattr__(A, b'x', None) |
| 681 |
|
| 682 |
def testTypeAttributeAccessErrorMessages(self): |
| 683 |
class A: |
| 684 |
pass |
| 685 |
|
| 686 |
error_msg = "type object 'A' has no attribute 'x'" |
| 687 |
with self.assertRaisesRegex(AttributeError, error_msg): |
| 688 |
A.x |
| 689 |
with self.assertRaisesRegex(AttributeError, error_msg): |
| 690 |
del A.x |
| 691 |
|
| 692 |
def testObjectAttributeAccessErrorMessages(self): |
| 693 |
class A: |
| 694 |
pass |
| 695 |
class B: |
| 696 |
y = 0 |
| 697 |
__slots__ = ('z',) |
| 698 |
class C: |
| 699 |
__slots__ = ("y",) |
| 700 |
|
| 701 |
def __setattr__(self, name, value) -> None: |
| 702 |
if name == "z": |
| 703 |
super().__setattr__("y", 1) |
| 704 |
else: |
| 705 |
super().__setattr__(name, value) |
| 706 |
|
| 707 |
error_msg = "'A' object has no attribute 'x'" |
| 708 |
with self.assertRaisesRegex(AttributeError, error_msg): |
| 709 |
A().x |
| 710 |
with self.assertRaisesRegex(AttributeError, error_msg): |
| 711 |
del A().x |
| 712 |
|
| 713 |
error_msg = "'B' object has no attribute 'x'" |
| 714 |
with self.assertRaisesRegex(AttributeError, error_msg): |
| 715 |
B().x |
| 716 |
with self.assertRaisesRegex(AttributeError, error_msg): |
| 717 |
del B().x |
| 718 |
with self.assertRaisesRegex( |
| 719 |
AttributeError, |
| 720 |
"'B' object has no attribute 'x' and no __dict__ for setting new attributes" |
| 721 |
): |
| 722 |
B().x = 0 |
| 723 |
with self.assertRaisesRegex( |
| 724 |
AttributeError, |
| 725 |
"'C' object has no attribute 'x'" |
| 726 |
): |
| 727 |
C().x = 0 |
| 728 |
|
| 729 |
error_msg = "'B' object attribute 'y' is read-only" |
| 730 |
with self.assertRaisesRegex(AttributeError, error_msg): |
| 731 |
del B().y |
| 732 |
with self.assertRaisesRegex(AttributeError, error_msg): |
| 733 |
B().y = 0 |
| 734 |
|
| 735 |
error_msg = 'z' |
| 736 |
with self.assertRaisesRegex(AttributeError, error_msg): |
| 737 |
B().z |
| 738 |
with self.assertRaisesRegex(AttributeError, error_msg): |
| 739 |
del B().z |
| 740 |
|
| 741 |
def testConstructorErrorMessages(self): |
| 742 |
# bpo-31506: Improves the error message logic for object_new & object_init |
| 743 |
|
| 744 |
# Class without any method overrides |
| 745 |
class C: |
| 746 |
pass |
| 747 |
|
| 748 |
error_msg = r'C.__init__\(\) takes exactly one argument \(the instance to initialize\)' |
| 749 |
|
| 750 |
with self.assertRaisesRegex(TypeError, r'C\(\) takes no arguments'): |
| 751 |
C(42) |
| 752 |
|
| 753 |
with self.assertRaisesRegex(TypeError, r'C\(\) takes no arguments'): |
| 754 |
C.__new__(C, 42) |
| 755 |
|
| 756 |
with self.assertRaisesRegex(TypeError, error_msg): |
| 757 |
C().__init__(42) |
| 758 |
|
| 759 |
with self.assertRaisesRegex(TypeError, r'C\(\) takes no arguments'): |
| 760 |
object.__new__(C, 42) |
| 761 |
|
| 762 |
with self.assertRaisesRegex(TypeError, error_msg): |
| 763 |
object.__init__(C(), 42) |
| 764 |
|
| 765 |
# Class with both `__init__` & `__new__` method overridden |
| 766 |
class D: |
| 767 |
def __new__(cls, *args, **kwargs): |
| 768 |
super().__new__(cls, *args, **kwargs) |
| 769 |
def __init__(self, *args, **kwargs): |
| 770 |
super().__init__(*args, **kwargs) |
| 771 |
|
| 772 |
error_msg = r'object.__new__\(\) takes exactly one argument \(the type to instantiate\)' |
| 773 |
|
| 774 |
with self.assertRaisesRegex(TypeError, error_msg): |
| 775 |
D(42) |
| 776 |
|
| 777 |
with self.assertRaisesRegex(TypeError, error_msg): |
| 778 |
D.__new__(D, 42) |
| 779 |
|
| 780 |
with self.assertRaisesRegex(TypeError, error_msg): |
| 781 |
object.__new__(D, 42) |
| 782 |
|
| 783 |
# Class that only overrides __init__ |
| 784 |
class E: |
| 785 |
def __init__(self, *args, **kwargs): |
| 786 |
super().__init__(*args, **kwargs) |
| 787 |
|
| 788 |
error_msg = r'object.__init__\(\) takes exactly one argument \(the instance to initialize\)' |
| 789 |
|
| 790 |
with self.assertRaisesRegex(TypeError, error_msg): |
| 791 |
E().__init__(42) |
| 792 |
|
| 793 |
with self.assertRaisesRegex(TypeError, error_msg): |
| 794 |
object.__init__(E(), 42) |
| 795 |
|
| 796 |
def testClassWithExtCall(self): |
| 797 |
class Meta(int): |
| 798 |
def __init__(*args, **kwargs): |
| 799 |
pass |
| 800 |
|
| 801 |
def __new__(cls, name, bases, attrs, **kwargs): |
| 802 |
return bases, kwargs |
| 803 |
|
| 804 |
d = {'metaclass': Meta} |
| 805 |
|
| 806 |
class A(**d): pass |
| 807 |
self.assertEqual(A, ((), {})) |
| 808 |
class A(0, 1, 2, 3, 4, 5, 6, 7, **d): pass |
| 809 |
self.assertEqual(A, (tuple(range(8)), {})) |
| 810 |
class A(0, *range(1, 8), **d, foo='bar'): pass |
| 811 |
self.assertEqual(A, (tuple(range(8)), {'foo': 'bar'})) |
| 812 |
|
| 813 |
def testClassCallRecursionLimit(self): |
| 814 |
class C: |
| 815 |
def __init__(self): |
| 816 |
self.c = C() |
| 817 |
|
| 818 |
with self.assertRaises(RecursionError): |
| 819 |
C() |
| 820 |
|
| 821 |
def add_one_level(): |
| 822 |
#Each call to C() consumes 2 levels, so offset by 1. |
| 823 |
C() |
| 824 |
|
| 825 |
with self.assertRaises(RecursionError): |
| 826 |
add_one_level() |
| 827 |
|
| 828 |
def testMetaclassCallOptimization(self): |
| 829 |
calls = 0 |
| 830 |
|
| 831 |
class TypeMetaclass(type): |
| 832 |
def __call__(cls, *args, **kwargs): |
| 833 |
nonlocal calls |
| 834 |
calls += 1 |
| 835 |
return type.__call__(cls, *args, **kwargs) |
| 836 |
|
| 837 |
class Type(metaclass=TypeMetaclass): |
| 838 |
def __init__(self, obj): |
| 839 |
self._obj = obj |
| 840 |
|
| 841 |
for i in range(100): |
| 842 |
Type(i) |
| 843 |
self.assertEqual(calls, 100) |
| 844 |
|
| 845 |
def test_specialization_class_call_doesnt_crash(self): |
| 846 |
# gh-123185 |
| 847 |
|
| 848 |
class Foo: |
| 849 |
def __init__(self, arg): |
| 850 |
pass |
| 851 |
|
| 852 |
for _ in range(8): |
| 853 |
try: |
| 854 |
Foo() |
| 855 |
except: |
| 856 |
pass |
| 857 |
|
| 858 |
|
| 859 |
from _testinternalcapi import has_inline_values |
| 860 |
|
| 861 |
Py_TPFLAGS_INLINE_VALUES = (1 << 2) |
| 862 |
Py_TPFLAGS_MANAGED_DICT = (1 << 4) |
| 863 |
|
| 864 |
class NoManagedDict: |
| 865 |
__slots__ = ('a',) |
| 866 |
|
| 867 |
|
| 868 |
class Plain: |
| 869 |
pass |
| 870 |
|
| 871 |
|
| 872 |
class WithAttrs: |
| 873 |
|
| 874 |
def __init__(self): |
| 875 |
self.a = 1 |
| 876 |
self.b = 2 |
| 877 |
self.c = 3 |
| 878 |
self.d = 4 |
| 879 |
|
| 880 |
|
| 881 |
class VarSizedSubclass(tuple): |
| 882 |
pass |
| 883 |
|
| 884 |
|
| 885 |
class TestInlineValues(unittest.TestCase): |
| 886 |
|
| 887 |
def test_no_flags_for_slots_class(self): |
| 888 |
flags = NoManagedDict.__flags__ |
| 889 |
self.assertEqual(flags & Py_TPFLAGS_MANAGED_DICT, 0) |
| 890 |
self.assertEqual(flags & Py_TPFLAGS_INLINE_VALUES, 0) |
| 891 |
self.assertFalse(has_inline_values(NoManagedDict())) |
| 892 |
|
| 893 |
def test_both_flags_for_regular_class(self): |
| 894 |
for cls in (Plain, WithAttrs): |
| 895 |
with self.subTest(cls=cls.__name__): |
| 896 |
flags = cls.__flags__ |
| 897 |
self.assertEqual(flags & Py_TPFLAGS_MANAGED_DICT, Py_TPFLAGS_MANAGED_DICT) |
| 898 |
self.assertEqual(flags & Py_TPFLAGS_INLINE_VALUES, Py_TPFLAGS_INLINE_VALUES) |
| 899 |
self.assertTrue(has_inline_values(cls())) |
| 900 |
|
| 901 |
def test_managed_dict_only_for_varsized_subclass(self): |
| 902 |
flags = VarSizedSubclass.__flags__ |
| 903 |
self.assertEqual(flags & Py_TPFLAGS_MANAGED_DICT, Py_TPFLAGS_MANAGED_DICT) |
| 904 |
self.assertEqual(flags & Py_TPFLAGS_INLINE_VALUES, 0) |
| 905 |
self.assertFalse(has_inline_values(VarSizedSubclass())) |
| 906 |
|
| 907 |
def test_has_inline_values(self): |
| 908 |
c = Plain() |
| 909 |
self.assertTrue(has_inline_values(c)) |
| 910 |
del c.__dict__ |
| 911 |
self.assertFalse(has_inline_values(c)) |
| 912 |
|
| 913 |
def test_instances(self): |
| 914 |
self.assertTrue(has_inline_values(Plain())) |
| 915 |
self.assertTrue(has_inline_values(WithAttrs())) |
| 916 |
|
| 917 |
def test_inspect_dict(self): |
| 918 |
for cls in (Plain, WithAttrs): |
| 919 |
c = cls() |
| 920 |
c.__dict__ |
| 921 |
self.assertTrue(has_inline_values(c)) |
| 922 |
|
| 923 |
def test_update_dict(self): |
| 924 |
d = { "e": 5, "f": 6 } |
| 925 |
for cls in (Plain, WithAttrs): |
| 926 |
c = cls() |
| 927 |
c.__dict__.update(d) |
| 928 |
self.assertTrue(has_inline_values(c)) |
| 929 |
|
| 930 |
@staticmethod |
| 931 |
def set_100(obj): |
| 932 |
for i in range(100): |
| 933 |
setattr(obj, f"a{i}", i) |
| 934 |
|
| 935 |
def check_100(self, obj): |
| 936 |
for i in range(100): |
| 937 |
self.assertEqual(getattr(obj, f"a{i}"), i) |
| 938 |
|
| 939 |
def test_many_attributes(self): |
| 940 |
class C: pass |
| 941 |
c = C() |
| 942 |
self.assertTrue(has_inline_values(c)) |
| 943 |
self.set_100(c) |
| 944 |
self.assertFalse(has_inline_values(c)) |
| 945 |
self.check_100(c) |
| 946 |
c = C() |
| 947 |
self.assertTrue(has_inline_values(c)) |
| 948 |
|
| 949 |
def test_many_attributes_with_dict(self): |
| 950 |
class C: pass |
| 951 |
c = C() |
| 952 |
d = c.__dict__ |
| 953 |
self.assertTrue(has_inline_values(c)) |
| 954 |
self.set_100(c) |
| 955 |
self.assertFalse(has_inline_values(c)) |
| 956 |
self.check_100(c) |
| 957 |
|
| 958 |
def test_bug_117750(self): |
| 959 |
"Aborted on 3.13a6" |
| 960 |
class C: |
| 961 |
def __init__(self): |
| 962 |
self.__dict__.clear() |
| 963 |
|
| 964 |
obj = C() |
| 965 |
self.assertEqual(obj.__dict__, {}) |
| 966 |
obj.foo = None # Aborted here |
| 967 |
self.assertEqual(obj.__dict__, {"foo":None}) |
| 968 |
|
| 969 |
def test_store_attr_deleted_dict(self): |
| 970 |
class Foo: |
| 971 |
pass |
| 972 |
|
| 973 |
f = Foo() |
| 974 |
del f.__dict__ |
| 975 |
f.a = 3 |
| 976 |
self.assertEqual(f.a, 3) |
| 977 |
|
| 978 |
def test_rematerialize_object_dict(self): |
| 979 |
# gh-121860: rematerializing an object's managed dictionary after it |
| 980 |
# had been deleted caused a crash. |
| 981 |
class Foo: pass |
| 982 |
f = Foo() |
| 983 |
f.__dict__["attr"] = 1 |
| 984 |
del f.__dict__ |
| 985 |
|
| 986 |
# Using a str subclass is a way to trigger the re-materialization |
| 987 |
class StrSubclass(str): pass |
| 988 |
self.assertFalse(hasattr(f, StrSubclass("attr"))) |
| 989 |
|
| 990 |
# Changing the __class__ also triggers the re-materialization |
| 991 |
class Bar: pass |
| 992 |
f.__class__ = Bar |
| 993 |
self.assertIsInstance(f, Bar) |
| 994 |
self.assertEqual(f.__dict__, {}) |
| 995 |
|
| 996 |
def test_store_attr_type_cache(self): |
| 997 |
"""Verifies that the type cache doesn't provide a value which is |
| 998 |
inconsistent from the dict.""" |
| 999 |
class X: |
| 1000 |
def __del__(inner_self): |
| 1001 |
v = C.a |
| 1002 |
self.assertEqual(v, C.__dict__['a']) |
| 1003 |
|
| 1004 |
class C: |
| 1005 |
a = X() |
| 1006 |
|
| 1007 |
# prime the cache |
| 1008 |
C.a |
| 1009 |
C.a |
| 1010 |
|
| 1011 |
# destructor shouldn't be able to see inconsistent state |
| 1012 |
C.a = X() |
| 1013 |
C.a = X() |
| 1014 |
|
| 1015 |
@cpython_only |
| 1016 |
def test_detach_materialized_dict_no_memory(self): |
| 1017 |
# Skip test if _testcapi is not available: |
| 1018 |
import_helper.import_module('_testcapi') |
| 1019 |
|
| 1020 |
code = """if 1: |
| 1021 |
import test.support |
| 1022 |
import _testcapi |
| 1023 |
|
| 1024 |
class A: |
| 1025 |
def __init__(self): |
| 1026 |
self.a = 1 |
| 1027 |
self.b = 2 |
| 1028 |
a = A() |
| 1029 |
d = a.__dict__ |
| 1030 |
with test.support.catch_unraisable_exception() as ex: |
| 1031 |
_testcapi.set_nomemory(0, 1) |
| 1032 |
del a |
| 1033 |
assert ex.unraisable.exc_type is MemoryError |
| 1034 |
try: |
| 1035 |
d["a"] |
| 1036 |
except KeyError: |
| 1037 |
pass |
| 1038 |
else: |
| 1039 |
assert False, "KeyError not raised" |
| 1040 |
""" |
| 1041 |
rc, out, err = script_helper.assert_python_ok("-c", code) |
| 1042 |
self.assertEqual(rc, 0) |
| 1043 |
self.assertFalse(out, msg=out.decode('utf-8')) |
| 1044 |
self.assertFalse(err, msg=err.decode('utf-8')) |
| 1045 |
|
| 1046 |
if __name__ == '__main__': |
| 1047 |
unittest.main() |