| 1 |
import sys |
| 2 |
import unittest |
| 3 |
from test.support import import_helper |
| 4 |
|
| 5 |
|
| 6 |
_testcapi = import_helper.import_module('_testcapi') |
| 7 |
|
| 8 |
|
| 9 |
class FrameTest(unittest.TestCase): |
| 10 |
def getframe(self): |
| 11 |
return sys._getframe() |
| 12 |
|
| 13 |
def test_frame_getters(self): |
| 14 |
frame = self.getframe() |
| 15 |
self.assertEqual(frame.f_locals, _testcapi.frame_getlocals(frame)) |
| 16 |
self.assertIs(frame.f_globals, _testcapi.frame_getglobals(frame)) |
| 17 |
self.assertIs(frame.f_builtins, _testcapi.frame_getbuiltins(frame)) |
| 18 |
self.assertEqual(frame.f_lasti, _testcapi.frame_getlasti(frame)) |
| 19 |
|
| 20 |
def test_getvar(self): |
| 21 |
current_frame = sys._getframe() |
| 22 |
x = 1 |
| 23 |
self.assertEqual(_testcapi.frame_getvar(current_frame, "x"), 1) |
| 24 |
self.assertEqual(_testcapi.frame_getvarstring(current_frame, b"x"), 1) |
| 25 |
with self.assertRaises(NameError): |
| 26 |
_testcapi.frame_getvar(current_frame, "y") |
| 27 |
with self.assertRaises(NameError): |
| 28 |
_testcapi.frame_getvarstring(current_frame, b"y") |
| 29 |
|
| 30 |
# wrong name type |
| 31 |
with self.assertRaises(TypeError): |
| 32 |
_testcapi.frame_getvar(current_frame, b'x') |
| 33 |
with self.assertRaises(TypeError): |
| 34 |
_testcapi.frame_getvar(current_frame, 123) |
| 35 |
|
| 36 |
def getgenframe(self): |
| 37 |
yield sys._getframe() |
| 38 |
|
| 39 |
def test_frame_get_generator(self): |
| 40 |
gen = self.getgenframe() |
| 41 |
frame = next(gen) |
| 42 |
self.assertIs(gen, _testcapi.frame_getgenerator(frame)) |
| 43 |
|
| 44 |
def test_frame_fback_api(self): |
| 45 |
"""Test that accessing `f_back` does not cause a segmentation fault on |
| 46 |
a frame created with `PyFrame_New` (GH-99110).""" |
| 47 |
def dummy(): |
| 48 |
pass |
| 49 |
|
| 50 |
frame = _testcapi.frame_new(dummy.__code__, globals(), locals()) |
| 51 |
# The following line should not cause a segmentation fault. |
| 52 |
self.assertIsNone(frame.f_back) |
| 53 |
|
| 54 |
|
| 55 |
if __name__ == "__main__": |
| 56 |
unittest.main() |