| 1 |
import copy |
| 2 |
import gc |
| 3 |
import operator |
| 4 |
import re |
| 5 |
import sys |
| 6 |
import textwrap |
| 7 |
import threading |
| 8 |
import types |
| 9 |
import unittest |
| 10 |
import weakref |
| 11 |
try: |
| 12 |
import _testcapi |
| 13 |
except ImportError: |
| 14 |
_testcapi = None |
| 15 |
|
| 16 |
from collections.abc import Mapping |
| 17 |
from test import support |
| 18 |
from test.support import import_helper, threading_helper, Py_GIL_DISABLED |
| 19 |
from test.support.script_helper import assert_python_ok |
| 20 |
from test import mapping_tests |
| 21 |
|
| 22 |
|
| 23 |
class ClearTest(unittest.TestCase): |
| 24 |
""" |
| 25 |
Tests for frame.clear(). |
| 26 |
""" |
| 27 |
|
| 28 |
def inner(self, x=5, **kwargs): |
| 29 |
1/0 |
| 30 |
|
| 31 |
def outer(self, **kwargs): |
| 32 |
try: |
| 33 |
self.inner(**kwargs) |
| 34 |
except ZeroDivisionError as e: |
| 35 |
exc = e |
| 36 |
return exc |
| 37 |
|
| 38 |
def clear_traceback_frames(self, tb): |
| 39 |
""" |
| 40 |
Clear all frames in a traceback. |
| 41 |
""" |
| 42 |
while tb is not None: |
| 43 |
tb.tb_frame.clear() |
| 44 |
tb = tb.tb_next |
| 45 |
|
| 46 |
def test_clear_locals(self): |
| 47 |
class C: |
| 48 |
pass |
| 49 |
c = C() |
| 50 |
wr = weakref.ref(c) |
| 51 |
exc = self.outer(c=c) |
| 52 |
del c |
| 53 |
support.gc_collect() |
| 54 |
# A reference to c is held through the frames |
| 55 |
self.assertIsNot(None, wr()) |
| 56 |
self.clear_traceback_frames(exc.__traceback__) |
| 57 |
support.gc_collect() |
| 58 |
# The reference was released by .clear() |
| 59 |
self.assertIs(None, wr()) |
| 60 |
|
| 61 |
def test_clear_locals_after_f_locals_access(self): |
| 62 |
# see gh-113939 |
| 63 |
class C: |
| 64 |
pass |
| 65 |
|
| 66 |
wr = None |
| 67 |
def inner(): |
| 68 |
nonlocal wr |
| 69 |
c = C() |
| 70 |
wr = weakref.ref(c) |
| 71 |
1/0 |
| 72 |
|
| 73 |
try: |
| 74 |
inner() |
| 75 |
except ZeroDivisionError as exc: |
| 76 |
support.gc_collect() |
| 77 |
self.assertIsNotNone(wr()) |
| 78 |
exc.__traceback__.tb_next.tb_frame.clear() |
| 79 |
support.gc_collect() |
| 80 |
self.assertIsNone(wr()) |
| 81 |
|
| 82 |
def test_clear_does_not_clear_specials(self): |
| 83 |
class C: |
| 84 |
pass |
| 85 |
c = C() |
| 86 |
exc = self.outer(c=c) |
| 87 |
del c |
| 88 |
f = exc.__traceback__.tb_frame |
| 89 |
f.clear() |
| 90 |
self.assertIsNot(f.f_code, None) |
| 91 |
self.assertIsNot(f.f_locals, None) |
| 92 |
self.assertIsNot(f.f_builtins, None) |
| 93 |
self.assertIsNot(f.f_globals, None) |
| 94 |
|
| 95 |
def test_clear_generator(self): |
| 96 |
endly = False |
| 97 |
def g(): |
| 98 |
nonlocal endly |
| 99 |
try: |
| 100 |
yield |
| 101 |
self.inner() |
| 102 |
finally: |
| 103 |
endly = True |
| 104 |
gen = g() |
| 105 |
next(gen) |
| 106 |
self.assertFalse(endly) |
| 107 |
|
| 108 |
# Cannot clear a suspended frame |
| 109 |
with self.assertRaisesRegex(RuntimeError, r'suspended frame'): |
| 110 |
gen.gi_frame.clear() |
| 111 |
self.assertFalse(endly) |
| 112 |
|
| 113 |
def test_clear_executing(self): |
| 114 |
# Attempting to clear an executing frame is forbidden. |
| 115 |
try: |
| 116 |
1/0 |
| 117 |
except ZeroDivisionError as e: |
| 118 |
f = e.__traceback__.tb_frame |
| 119 |
with self.assertRaises(RuntimeError): |
| 120 |
f.clear() |
| 121 |
with self.assertRaises(RuntimeError): |
| 122 |
f.f_back.clear() |
| 123 |
|
| 124 |
def test_clear_executing_generator(self): |
| 125 |
# Attempting to clear an executing generator frame is forbidden. |
| 126 |
endly = False |
| 127 |
def g(): |
| 128 |
nonlocal endly |
| 129 |
try: |
| 130 |
1/0 |
| 131 |
except ZeroDivisionError as e: |
| 132 |
f = e.__traceback__.tb_frame |
| 133 |
with self.assertRaises(RuntimeError): |
| 134 |
f.clear() |
| 135 |
with self.assertRaises(RuntimeError): |
| 136 |
f.f_back.clear() |
| 137 |
yield f |
| 138 |
finally: |
| 139 |
endly = True |
| 140 |
gen = g() |
| 141 |
f = next(gen) |
| 142 |
self.assertFalse(endly) |
| 143 |
# Cannot clear a suspended frame |
| 144 |
with self.assertRaisesRegex(RuntimeError, 'suspended frame'): |
| 145 |
f.clear() |
| 146 |
self.assertFalse(endly) |
| 147 |
|
| 148 |
def test_lineno_with_tracing(self): |
| 149 |
def record_line(): |
| 150 |
f = sys._getframe(1) |
| 151 |
lines.append(f.f_lineno-f.f_code.co_firstlineno) |
| 152 |
|
| 153 |
def test(trace): |
| 154 |
record_line() |
| 155 |
if trace: |
| 156 |
sys._getframe(0).f_trace = True |
| 157 |
record_line() |
| 158 |
record_line() |
| 159 |
|
| 160 |
expected_lines = [1, 4, 5] |
| 161 |
lines = [] |
| 162 |
test(False) |
| 163 |
self.assertEqual(lines, expected_lines) |
| 164 |
lines = [] |
| 165 |
test(True) |
| 166 |
self.assertEqual(lines, expected_lines) |
| 167 |
|
| 168 |
@support.cpython_only |
| 169 |
def test_clear_refcycles(self): |
| 170 |
# .clear() doesn't leave any refcycle behind |
| 171 |
with support.disable_gc(): |
| 172 |
class C: |
| 173 |
pass |
| 174 |
c = C() |
| 175 |
wr = weakref.ref(c) |
| 176 |
exc = self.outer(c=c) |
| 177 |
del c |
| 178 |
self.assertIsNot(None, wr()) |
| 179 |
self.clear_traceback_frames(exc.__traceback__) |
| 180 |
self.assertIs(None, wr()) |
| 181 |
|
| 182 |
|
| 183 |
class FrameAttrsTest(unittest.TestCase): |
| 184 |
|
| 185 |
def make_frames(self): |
| 186 |
def outer(): |
| 187 |
x = 5 |
| 188 |
y = 6 |
| 189 |
def inner(): |
| 190 |
z = x + 2 |
| 191 |
1/0 |
| 192 |
t = 9 |
| 193 |
return inner() |
| 194 |
try: |
| 195 |
outer() |
| 196 |
except ZeroDivisionError as e: |
| 197 |
tb = e.__traceback__ |
| 198 |
frames = [] |
| 199 |
while tb: |
| 200 |
frames.append(tb.tb_frame) |
| 201 |
tb = tb.tb_next |
| 202 |
return frames |
| 203 |
|
| 204 |
def test_clear_locals(self): |
| 205 |
# Test f_locals after clear() (issue #21897) |
| 206 |
f, outer, inner = self.make_frames() |
| 207 |
outer.clear() |
| 208 |
inner.clear() |
| 209 |
self.assertEqual(outer.f_locals, {}) |
| 210 |
self.assertEqual(inner.f_locals, {}) |
| 211 |
|
| 212 |
def test_locals_clear_locals(self): |
| 213 |
# Test f_locals before and after clear() (to exercise caching) |
| 214 |
f, outer, inner = self.make_frames() |
| 215 |
self.assertNotEqual(outer.f_locals, {}) |
| 216 |
self.assertNotEqual(inner.f_locals, {}) |
| 217 |
outer.clear() |
| 218 |
inner.clear() |
| 219 |
self.assertEqual(outer.f_locals, {}) |
| 220 |
self.assertEqual(inner.f_locals, {}) |
| 221 |
|
| 222 |
def test_f_lineno_del_segfault(self): |
| 223 |
f, _, _ = self.make_frames() |
| 224 |
with self.assertRaises(AttributeError): |
| 225 |
del f.f_lineno |
| 226 |
|
| 227 |
|
| 228 |
class ReprTest(unittest.TestCase): |
| 229 |
""" |
| 230 |
Tests for repr(frame). |
| 231 |
""" |
| 232 |
|
| 233 |
def test_repr(self): |
| 234 |
def outer(): |
| 235 |
x = 5 |
| 236 |
y = 6 |
| 237 |
def inner(): |
| 238 |
z = x + 2 |
| 239 |
1/0 |
| 240 |
t = 9 |
| 241 |
return inner() |
| 242 |
|
| 243 |
offset = outer.__code__.co_firstlineno |
| 244 |
try: |
| 245 |
outer() |
| 246 |
except ZeroDivisionError as e: |
| 247 |
tb = e.__traceback__ |
| 248 |
frames = [] |
| 249 |
while tb: |
| 250 |
frames.append(tb.tb_frame) |
| 251 |
tb = tb.tb_next |
| 252 |
else: |
| 253 |
self.fail("should have raised") |
| 254 |
|
| 255 |
f_this, f_outer, f_inner = frames |
| 256 |
file_repr = re.escape(repr(__file__)) |
| 257 |
self.assertRegex(repr(f_this), |
| 258 |
r"^<frame at 0x[0-9a-fA-F]+, file %s, line %d, code test_repr>$" |
| 259 |
% (file_repr, offset + 23)) |
| 260 |
self.assertRegex(repr(f_outer), |
| 261 |
r"^<frame at 0x[0-9a-fA-F]+, file %s, line %d, code outer>$" |
| 262 |
% (file_repr, offset + 7)) |
| 263 |
self.assertRegex(repr(f_inner), |
| 264 |
r"^<frame at 0x[0-9a-fA-F]+, file %s, line %d, code inner>$" |
| 265 |
% (file_repr, offset + 5)) |
| 266 |
|
| 267 |
class TestFrameLocals(unittest.TestCase): |
| 268 |
def test_scope(self): |
| 269 |
class A: |
| 270 |
x = 1 |
| 271 |
sys._getframe().f_locals['x'] = 2 |
| 272 |
sys._getframe().f_locals['y'] = 2 |
| 273 |
|
| 274 |
self.assertEqual(A.x, 2) |
| 275 |
self.assertEqual(A.y, 2) |
| 276 |
|
| 277 |
def f(): |
| 278 |
x = 1 |
| 279 |
sys._getframe().f_locals['x'] = 2 |
| 280 |
sys._getframe().f_locals['y'] = 2 |
| 281 |
self.assertEqual(x, 2) |
| 282 |
self.assertEqual(locals()['y'], 2) |
| 283 |
f() |
| 284 |
|
| 285 |
def test_closure(self): |
| 286 |
x = 1 |
| 287 |
y = 2 |
| 288 |
|
| 289 |
def f(): |
| 290 |
z = x + y |
| 291 |
d = sys._getframe().f_locals |
| 292 |
self.assertEqual(d['x'], 1) |
| 293 |
self.assertEqual(d['y'], 2) |
| 294 |
d['x'] = 2 |
| 295 |
d['y'] = 3 |
| 296 |
|
| 297 |
f() |
| 298 |
self.assertEqual(x, 2) |
| 299 |
self.assertEqual(y, 3) |
| 300 |
|
| 301 |
def test_closure_with_inline_comprehension(self): |
| 302 |
lambda: k |
| 303 |
k = 1 |
| 304 |
lst = [locals() for k in [0]] |
| 305 |
self.assertEqual(lst[0]['k'], 0) |
| 306 |
|
| 307 |
def test_as_dict(self): |
| 308 |
x = 1 |
| 309 |
y = 2 |
| 310 |
d = sys._getframe().f_locals |
| 311 |
# self, x, y, d |
| 312 |
self.assertEqual(len(d), 4) |
| 313 |
self.assertIs(d['d'], d) |
| 314 |
self.assertEqual(set(d.keys()), set(['x', 'y', 'd', 'self'])) |
| 315 |
self.assertEqual(len(d.values()), 4) |
| 316 |
self.assertIn(1, d.values()) |
| 317 |
self.assertEqual(len(d.items()), 4) |
| 318 |
self.assertIn(('x', 1), d.items()) |
| 319 |
self.assertEqual(d.__getitem__('x'), 1) |
| 320 |
d.__setitem__('x', 2) |
| 321 |
self.assertEqual(d['x'], 2) |
| 322 |
self.assertEqual(d.get('x'), 2) |
| 323 |
self.assertIs(d.get('non_exist', None), None) |
| 324 |
self.assertEqual(d.__len__(), 4) |
| 325 |
self.assertEqual(set([key for key in d]), set(['x', 'y', 'd', 'self'])) |
| 326 |
self.assertIn('x', d) |
| 327 |
self.assertTrue(d.__contains__('x')) |
| 328 |
|
| 329 |
self.assertEqual(reversed(d), list(reversed(d.keys()))) |
| 330 |
|
| 331 |
d.update({'x': 3, 'z': 4}) |
| 332 |
self.assertEqual(d['x'], 3) |
| 333 |
self.assertEqual(d['z'], 4) |
| 334 |
|
| 335 |
with self.assertRaises(TypeError): |
| 336 |
d.update([1, 2]) |
| 337 |
|
| 338 |
self.assertEqual(d.setdefault('x', 5), 3) |
| 339 |
self.assertEqual(d.setdefault('new', 5), 5) |
| 340 |
self.assertEqual(d['new'], 5) |
| 341 |
|
| 342 |
with self.assertRaises(KeyError): |
| 343 |
d['non_exist'] |
| 344 |
|
| 345 |
def test_as_number(self): |
| 346 |
x = 1 |
| 347 |
y = 2 |
| 348 |
d = sys._getframe().f_locals |
| 349 |
self.assertIn('z', d | {'z': 3}) |
| 350 |
d |= {'z': 3} |
| 351 |
self.assertEqual(d['z'], 3) |
| 352 |
d |= {'y': 3} |
| 353 |
self.assertEqual(d['y'], 3) |
| 354 |
with self.assertRaises(TypeError): |
| 355 |
d |= 3 |
| 356 |
with self.assertRaises(TypeError): |
| 357 |
_ = d | [3] |
| 358 |
|
| 359 |
def test_non_string_key(self): |
| 360 |
d = sys._getframe().f_locals |
| 361 |
d[1] = 2 |
| 362 |
self.assertEqual(d[1], 2) |
| 363 |
|
| 364 |
def test_write_with_hidden(self): |
| 365 |
def f(): |
| 366 |
f_locals = [sys._getframe().f_locals for b in [0]][0] |
| 367 |
f_locals['b'] = 2 |
| 368 |
f_locals['c'] = 3 |
| 369 |
self.assertEqual(b, 2) |
| 370 |
self.assertEqual(c, 3) |
| 371 |
b = 0 |
| 372 |
c = 0 |
| 373 |
f() |
| 374 |
|
| 375 |
def test_local_objects(self): |
| 376 |
o = object() |
| 377 |
k = '.'.join(['a', 'b', 'c']) |
| 378 |
f_locals = sys._getframe().f_locals |
| 379 |
f_locals['o'] = f_locals['k'] |
| 380 |
self.assertEqual(o, 'a.b.c') |
| 381 |
|
| 382 |
def test_copy(self): |
| 383 |
x = 0 |
| 384 |
d = sys._getframe().f_locals |
| 385 |
d_copy = d.copy() |
| 386 |
self.assertIsInstance(d_copy, dict) |
| 387 |
self.assertEqual(d_copy['x'], 0) |
| 388 |
d_copy['x'] = 1 |
| 389 |
self.assertEqual(x, 0) |
| 390 |
|
| 391 |
def test_update_with_self(self): |
| 392 |
def f(): |
| 393 |
f_locals = sys._getframe().f_locals |
| 394 |
f_locals.update(f_locals) |
| 395 |
f_locals.update(f_locals) |
| 396 |
f_locals.update(f_locals) |
| 397 |
f() |
| 398 |
|
| 399 |
def test_repr(self): |
| 400 |
x = 1 |
| 401 |
# Introduce a reference cycle |
| 402 |
frame = sys._getframe() |
| 403 |
self.assertEqual(repr(frame.f_locals), repr(dict(frame.f_locals))) |
| 404 |
|
| 405 |
def test_delete(self): |
| 406 |
x = 1 |
| 407 |
d = sys._getframe().f_locals |
| 408 |
|
| 409 |
# This needs to be tested before f_extra_locals is created |
| 410 |
with self.assertRaisesRegex(KeyError, 'non_exist'): |
| 411 |
del d['non_exist'] |
| 412 |
|
| 413 |
with self.assertRaises(KeyError): |
| 414 |
d.pop('non_exist') |
| 415 |
|
| 416 |
with self.assertRaisesRegex(ValueError, 'local variables'): |
| 417 |
del d['x'] |
| 418 |
|
| 419 |
with self.assertRaises(AttributeError): |
| 420 |
d.clear() |
| 421 |
|
| 422 |
with self.assertRaises(ValueError): |
| 423 |
d.pop('x') |
| 424 |
|
| 425 |
with self.assertRaises(ValueError): |
| 426 |
d.pop('x', None) |
| 427 |
|
| 428 |
# 'm', 'n' is stored in f_extra_locals |
| 429 |
d['m'] = 1 |
| 430 |
d['n'] = 1 |
| 431 |
|
| 432 |
with self.assertRaises(KeyError): |
| 433 |
d.pop('non_exist') |
| 434 |
|
| 435 |
del d['m'] |
| 436 |
self.assertEqual(d.pop('n'), 1) |
| 437 |
|
| 438 |
self.assertNotIn('m', d) |
| 439 |
self.assertNotIn('n', d) |
| 440 |
|
| 441 |
self.assertEqual(d.pop('n', 2), 2) |
| 442 |
|
| 443 |
@support.cpython_only |
| 444 |
def test_sizeof(self): |
| 445 |
proxy = sys._getframe().f_locals |
| 446 |
support.check_sizeof(self, proxy, support.calcobjsize("P")) |
| 447 |
|
| 448 |
def test_unsupport(self): |
| 449 |
x = 1 |
| 450 |
d = sys._getframe().f_locals |
| 451 |
with self.assertRaises(TypeError): |
| 452 |
copy.copy(d) |
| 453 |
|
| 454 |
with self.assertRaises(TypeError): |
| 455 |
copy.deepcopy(d) |
| 456 |
|
| 457 |
def test_is_mapping(self): |
| 458 |
x = 1 |
| 459 |
d = sys._getframe().f_locals |
| 460 |
self.assertIsInstance(d, Mapping) |
| 461 |
match d: |
| 462 |
case {"x": value}: |
| 463 |
self.assertEqual(value, 1) |
| 464 |
kind = "mapping" |
| 465 |
case _: |
| 466 |
kind = "other" |
| 467 |
self.assertEqual(kind, "mapping") |
| 468 |
|
| 469 |
def _x_stringlikes(self): |
| 470 |
class StringSubclass(str): |
| 471 |
pass |
| 472 |
|
| 473 |
class ImpostorX: |
| 474 |
def __hash__(self): |
| 475 |
return hash('x') |
| 476 |
|
| 477 |
def __eq__(self, other): |
| 478 |
return other == 'x' |
| 479 |
|
| 480 |
return StringSubclass('x'), ImpostorX(), 'x' |
| 481 |
|
| 482 |
def test_proxy_key_stringlikes_overwrite(self): |
| 483 |
def f(obj): |
| 484 |
x = 1 |
| 485 |
proxy = sys._getframe().f_locals |
| 486 |
proxy[obj] = 2 |
| 487 |
return ( |
| 488 |
list(proxy.keys()), |
| 489 |
dict(proxy), |
| 490 |
proxy |
| 491 |
) |
| 492 |
|
| 493 |
for obj in self._x_stringlikes(): |
| 494 |
with self.subTest(cls=type(obj).__name__): |
| 495 |
|
| 496 |
keys_snapshot, proxy_snapshot, proxy = f(obj) |
| 497 |
expected_keys = ['obj', 'x', 'proxy'] |
| 498 |
expected_dict = {'obj': 'x', 'x': 2, 'proxy': proxy} |
| 499 |
self.assertEqual(proxy.keys(), expected_keys) |
| 500 |
self.assertEqual(proxy, expected_dict) |
| 501 |
self.assertEqual(keys_snapshot, expected_keys) |
| 502 |
self.assertEqual(proxy_snapshot, expected_dict) |
| 503 |
|
| 504 |
def test_proxy_key_stringlikes_ftrst_write(self): |
| 505 |
def f(obj): |
| 506 |
proxy = sys._getframe().f_locals |
| 507 |
proxy[obj] = 2 |
| 508 |
self.assertEqual(x, 2) |
| 509 |
x = 1 |
| 510 |
|
| 511 |
for obj in self._x_stringlikes(): |
| 512 |
with self.subTest(cls=type(obj).__name__): |
| 513 |
f(obj) |
| 514 |
|
| 515 |
def test_proxy_key_unhashables(self): |
| 516 |
class StringSubclass(str): |
| 517 |
__hash__ = None |
| 518 |
|
| 519 |
class ObjectSubclass: |
| 520 |
__hash__ = None |
| 521 |
|
| 522 |
proxy = sys._getframe().f_locals |
| 523 |
|
| 524 |
for obj in StringSubclass('x'), ObjectSubclass(): |
| 525 |
with self.subTest(cls=type(obj).__name__): |
| 526 |
with self.assertRaises(TypeError): |
| 527 |
proxy[obj] |
| 528 |
with self.assertRaises(TypeError): |
| 529 |
proxy[obj] = 0 |
| 530 |
|
| 531 |
def test_constructor(self): |
| 532 |
FrameLocalsProxy = type([sys._getframe().f_locals |
| 533 |
for x in range(1)][0]) |
| 534 |
self.assertEqual(FrameLocalsProxy.__name__, 'FrameLocalsProxy') |
| 535 |
|
| 536 |
def make_frame(): |
| 537 |
x = 1 |
| 538 |
y = 2 |
| 539 |
return sys._getframe() |
| 540 |
|
| 541 |
proxy = FrameLocalsProxy(make_frame()) |
| 542 |
self.assertEqual(proxy, {'x': 1, 'y': 2}) |
| 543 |
|
| 544 |
# constructor expects 1 frame argument |
| 545 |
with self.assertRaises(TypeError): |
| 546 |
FrameLocalsProxy() # no arguments |
| 547 |
with self.assertRaises(TypeError): |
| 548 |
FrameLocalsProxy(123) # wrong type |
| 549 |
with self.assertRaises(TypeError): |
| 550 |
FrameLocalsProxy(frame=sys._getframe()) # no keyword arguments |
| 551 |
|
| 552 |
|
| 553 |
class FrameLocalsProxyMappingTests(mapping_tests.TestHashMappingProtocol): |
| 554 |
"""Test that FrameLocalsProxy behaves like a Mapping (with exceptions)""" |
| 555 |
|
| 556 |
def _f(*args, **kwargs): |
| 557 |
def _f(): |
| 558 |
return sys._getframe().f_locals |
| 559 |
return _f() |
| 560 |
type2test = _f |
| 561 |
|
| 562 |
@unittest.skipIf(True, 'Locals proxies for different frames never compare as equal') |
| 563 |
def test_constructor(self): |
| 564 |
pass |
| 565 |
|
| 566 |
@unittest.skipIf(True, 'Unlike a mapping: del proxy[key] fails') |
| 567 |
def test_write(self): |
| 568 |
pass |
| 569 |
|
| 570 |
@unittest.skipIf(True, 'Unlike a mapping: no proxy.popitem') |
| 571 |
def test_popitem(self): |
| 572 |
pass |
| 573 |
|
| 574 |
@unittest.skipIf(True, 'Unlike a mapping: no proxy.pop') |
| 575 |
def test_pop(self): |
| 576 |
pass |
| 577 |
|
| 578 |
@unittest.skipIf(True, 'Unlike a mapping: no proxy.clear') |
| 579 |
def test_clear(self): |
| 580 |
pass |
| 581 |
|
| 582 |
@unittest.skipIf(True, 'Unlike a mapping: no proxy.fromkeys') |
| 583 |
def test_fromkeys(self): |
| 584 |
pass |
| 585 |
|
| 586 |
# no del |
| 587 |
def test_getitem(self): |
| 588 |
mapping_tests.BasicTestMappingProtocol.test_getitem(self) |
| 589 |
d = self._full_mapping({'a': 1, 'b': 2}) |
| 590 |
self.assertEqual(d['a'], 1) |
| 591 |
self.assertEqual(d['b'], 2) |
| 592 |
d['c'] = 3 |
| 593 |
d['a'] = 4 |
| 594 |
self.assertEqual(d['c'], 3) |
| 595 |
self.assertEqual(d['a'], 4) |
| 596 |
|
| 597 |
@unittest.skipIf(True, 'Unlike a mapping: no proxy.update') |
| 598 |
def test_update(self): |
| 599 |
pass |
| 600 |
|
| 601 |
# proxy.copy returns a regular dict |
| 602 |
def test_copy(self): |
| 603 |
d = self._full_mapping({1:1, 2:2, 3:3}) |
| 604 |
self.assertEqual(d.copy(), {1:1, 2:2, 3:3}) |
| 605 |
d = self._empty_mapping() |
| 606 |
self.assertEqual(d.copy(), d) |
| 607 |
self.assertRaises(TypeError, d.copy, None) |
| 608 |
|
| 609 |
self.assertIsInstance(d.copy(), dict) |
| 610 |
|
| 611 |
@unittest.skipIf(True, 'Locals proxies for different frames never compare as equal') |
| 612 |
def test_eq(self): |
| 613 |
pass |
| 614 |
|
| 615 |
|
| 616 |
class TestFrameCApi(unittest.TestCase): |
| 617 |
def test_basic(self): |
| 618 |
x = 1 |
| 619 |
ctypes = import_helper.import_module('ctypes') |
| 620 |
PyEval_GetFrameLocals = ctypes.pythonapi.PyEval_GetFrameLocals |
| 621 |
PyEval_GetFrameLocals.restype = ctypes.py_object |
| 622 |
frame_locals = PyEval_GetFrameLocals() |
| 623 |
self.assertTrue(type(frame_locals), dict) |
| 624 |
self.assertEqual(frame_locals['x'], 1) |
| 625 |
frame_locals['x'] = 2 |
| 626 |
self.assertEqual(x, 1) |
| 627 |
|
| 628 |
PyEval_GetFrameGlobals = ctypes.pythonapi.PyEval_GetFrameGlobals |
| 629 |
PyEval_GetFrameGlobals.restype = ctypes.py_object |
| 630 |
frame_globals = PyEval_GetFrameGlobals() |
| 631 |
self.assertTrue(type(frame_globals), dict) |
| 632 |
self.assertIs(frame_globals, globals()) |
| 633 |
|
| 634 |
PyEval_GetFrameBuiltins = ctypes.pythonapi.PyEval_GetFrameBuiltins |
| 635 |
PyEval_GetFrameBuiltins.restype = ctypes.py_object |
| 636 |
frame_builtins = PyEval_GetFrameBuiltins() |
| 637 |
self.assertEqual(frame_builtins, __builtins__) |
| 638 |
|
| 639 |
PyFrame_GetLocals = ctypes.pythonapi.PyFrame_GetLocals |
| 640 |
PyFrame_GetLocals.argtypes = [ctypes.py_object] |
| 641 |
PyFrame_GetLocals.restype = ctypes.py_object |
| 642 |
frame = sys._getframe() |
| 643 |
f_locals = PyFrame_GetLocals(frame) |
| 644 |
self.assertTrue(f_locals['x'], 1) |
| 645 |
f_locals['x'] = 2 |
| 646 |
self.assertEqual(x, 2) |
| 647 |
|
| 648 |
|
| 649 |
class TestIncompleteFrameAreInvisible(unittest.TestCase): |
| 650 |
|
| 651 |
def test_issue95818(self): |
| 652 |
# See GH-95818 for details |
| 653 |
code = textwrap.dedent(f""" |
| 654 |
import gc |
| 655 |
|
| 656 |
gc.set_threshold(1,1,1) |
| 657 |
class GCHello: |
| 658 |
def __del__(self): |
| 659 |
print("Destroyed from gc") |
| 660 |
|
| 661 |
def gen(): |
| 662 |
yield |
| 663 |
|
| 664 |
fd = open({__file__!r}) |
| 665 |
l = [fd, GCHello()] |
| 666 |
l.append(l) |
| 667 |
del fd |
| 668 |
del l |
| 669 |
gen() |
| 670 |
""") |
| 671 |
assert_python_ok("-c", code) |
| 672 |
|
| 673 |
@support.cpython_only |
| 674 |
@threading_helper.requires_working_threading() |
| 675 |
def test_sneaky_frame_object_teardown(self): |
| 676 |
|
| 677 |
class SneakyDel: |
| 678 |
def __del__(self): |
| 679 |
""" |
| 680 |
Stash a reference to the entire stack for walking later. |
| 681 |
|
| 682 |
It may look crazy, but you'd be surprised how common this is |
| 683 |
when using a test runner (like pytest). The typical recipe is: |
| 684 |
ResourceWarning + -Werror + a custom sys.unraisablehook. |
| 685 |
""" |
| 686 |
nonlocal sneaky_frame_object |
| 687 |
sneaky_frame_object = sys._getframe() |
| 688 |
|
| 689 |
class SneakyThread(threading.Thread): |
| 690 |
""" |
| 691 |
A separate thread isn't needed to make this code crash, but it does |
| 692 |
make crashes more consistent, since it means sneaky_frame_object is |
| 693 |
backed by freed memory after the thread completes! |
| 694 |
""" |
| 695 |
|
| 696 |
def run(self): |
| 697 |
"""Run SneakyDel.__del__ as this frame is popped.""" |
| 698 |
ref = SneakyDel() |
| 699 |
|
| 700 |
sneaky_frame_object = None |
| 701 |
t = SneakyThread() |
| 702 |
t.start() |
| 703 |
t.join() |
| 704 |
# sneaky_frame_object can be anything, really, but it's crucial that |
| 705 |
# SneakyThread.run's frame isn't anywhere on the stack while it's being |
| 706 |
# torn down: |
| 707 |
self.assertIsNotNone(sneaky_frame_object) |
| 708 |
while sneaky_frame_object is not None: |
| 709 |
self.assertIsNot( |
| 710 |
sneaky_frame_object.f_code, SneakyThread.run.__code__ |
| 711 |
) |
| 712 |
sneaky_frame_object = sneaky_frame_object.f_back |
| 713 |
|
| 714 |
def test_entry_frames_are_invisible_during_teardown(self): |
| 715 |
class C: |
| 716 |
"""A weakref'able class.""" |
| 717 |
|
| 718 |
def f(): |
| 719 |
"""Try to find globals and locals as this frame is being cleared.""" |
| 720 |
ref = C() |
| 721 |
# Ignore the fact that exec(C()) is a nonsense callback. We're only |
| 722 |
# using exec here because it tries to access the current frame's |
| 723 |
# globals and locals. If it's trying to get those from a shim frame, |
| 724 |
# we'll crash before raising: |
| 725 |
return weakref.ref(ref, exec) |
| 726 |
|
| 727 |
with support.catch_unraisable_exception() as catcher: |
| 728 |
# Call from C, so there is a shim frame directly above f: |
| 729 |
weak = operator.call(f) # BOOM! |
| 730 |
# Cool, we didn't crash. Check that the callback actually happened: |
| 731 |
self.assertIs(catcher.unraisable.exc_type, TypeError) |
| 732 |
self.assertIsNone(weak()) |
| 733 |
|
| 734 |
@unittest.skipIf(_testcapi is None, 'need _testcapi') |
| 735 |
class TestCAPI(unittest.TestCase): |
| 736 |
def getframe(self): |
| 737 |
return sys._getframe() |
| 738 |
|
| 739 |
def test_frame_getters(self): |
| 740 |
frame = self.getframe() |
| 741 |
self.assertEqual(frame.f_locals, _testcapi.frame_getlocals(frame)) |
| 742 |
self.assertIs(frame.f_globals, _testcapi.frame_getglobals(frame)) |
| 743 |
self.assertIs(frame.f_builtins, _testcapi.frame_getbuiltins(frame)) |
| 744 |
self.assertEqual(frame.f_lasti, _testcapi.frame_getlasti(frame)) |
| 745 |
|
| 746 |
def test_getvar(self): |
| 747 |
current_frame = sys._getframe() |
| 748 |
x = 1 |
| 749 |
self.assertEqual(_testcapi.frame_getvar(current_frame, "x"), 1) |
| 750 |
self.assertEqual(_testcapi.frame_getvarstring(current_frame, b"x"), 1) |
| 751 |
with self.assertRaises(NameError): |
| 752 |
_testcapi.frame_getvar(current_frame, "y") |
| 753 |
with self.assertRaises(NameError): |
| 754 |
_testcapi.frame_getvarstring(current_frame, b"y") |
| 755 |
|
| 756 |
# wrong name type |
| 757 |
with self.assertRaises(TypeError): |
| 758 |
_testcapi.frame_getvar(current_frame, b'x') |
| 759 |
with self.assertRaises(TypeError): |
| 760 |
_testcapi.frame_getvar(current_frame, 123) |
| 761 |
|
| 762 |
def getgenframe(self): |
| 763 |
yield sys._getframe() |
| 764 |
|
| 765 |
def test_frame_get_generator(self): |
| 766 |
gen = self.getgenframe() |
| 767 |
frame = next(gen) |
| 768 |
self.assertIs(gen, _testcapi.frame_getgenerator(frame)) |
| 769 |
|
| 770 |
def test_frame_fback_api(self): |
| 771 |
"""Test that accessing `f_back` does not cause a segmentation fault on |
| 772 |
a frame created with `PyFrame_New` (GH-99110).""" |
| 773 |
def dummy(): |
| 774 |
pass |
| 775 |
|
| 776 |
frame = _testcapi.frame_new(dummy.__code__, globals(), locals()) |
| 777 |
# The following line should not cause a segmentation fault. |
| 778 |
self.assertIsNone(frame.f_back) |
| 779 |
|
| 780 |
if __name__ == "__main__": |
| 781 |
unittest.main() |