diff options
Diffstat (limited to 'Lib/test/test_code.py')
-rw-r--r-- | Lib/test/test_code.py | 45 |
1 files changed, 43 insertions, 2 deletions
diff --git a/Lib/test/test_code.py b/Lib/test/test_code.py index c8fa2a1..e1c7a78 100644 --- a/Lib/test/test_code.py +++ b/Lib/test/test_code.py @@ -102,6 +102,11 @@ consts: ('None',) """ +import unittest +import weakref +import _testcapi + + def consts(t): """Yield a doctest-safe sequence of object reprs.""" for elt in t: @@ -118,11 +123,47 @@ def dump(co): print("%s: %s" % (attr, getattr(co, "co_" + attr))) print("consts:", tuple(consts(co.co_consts))) + +class CodeTest(unittest.TestCase): + + def test_newempty(self): + co = _testcapi.code_newempty("filename", "funcname", 15) + self.assertEqual(co.co_filename, "filename") + self.assertEqual(co.co_name, "funcname") + self.assertEqual(co.co_firstlineno, 15) + + +class CodeWeakRefTest(unittest.TestCase): + + def test_basic(self): + # Create a code object in a clean environment so that we know we have + # the only reference to it left. + namespace = {} + exec("def f(): pass", globals(), namespace) + f = namespace["f"] + del namespace + + self.called = False + def callback(code): + self.called = True + + # f is now the last reference to the function, and through it, the code + # object. While we hold it, check that we can create a weakref and + # deref it. Then delete it, and check that the callback gets called and + # the reference dies. + coderef = weakref.ref(f.__code__, callback) + self.assertTrue(bool(coderef())) + del f + self.assertFalse(bool(coderef())) + self.assertTrue(self.called) + + def test_main(verbose=None): - from test.support import run_doctest + from test.support import run_doctest, run_unittest from test import test_code run_doctest(test_code, verbose) + run_unittest(CodeTest, CodeWeakRefTest) -if __name__ == '__main__': +if __name__ == "__main__": test_main() |