Back to index

python3.2  3.2.2
test_code.py
Go to the documentation of this file.
00001 """This module includes tests of the code object representation.
00002 
00003 >>> def f(x):
00004 ...     def g(y):
00005 ...         return x + y
00006 ...     return g
00007 ...
00008 
00009 >>> dump(f.__code__)
00010 name: f
00011 argcount: 1
00012 kwonlyargcount: 0
00013 names: ()
00014 varnames: ('x', 'g')
00015 cellvars: ('x',)
00016 freevars: ()
00017 nlocals: 2
00018 flags: 3
00019 consts: ('None', '<code object g>')
00020 
00021 >>> dump(f(4).__code__)
00022 name: g
00023 argcount: 1
00024 kwonlyargcount: 0
00025 names: ()
00026 varnames: ('y',)
00027 cellvars: ()
00028 freevars: ('x',)
00029 nlocals: 1
00030 flags: 19
00031 consts: ('None',)
00032 
00033 >>> def h(x, y):
00034 ...     a = x + y
00035 ...     b = x - y
00036 ...     c = a * b
00037 ...     return c
00038 ...
00039 
00040 >>> dump(h.__code__)
00041 name: h
00042 argcount: 2
00043 kwonlyargcount: 0
00044 names: ()
00045 varnames: ('x', 'y', 'a', 'b', 'c')
00046 cellvars: ()
00047 freevars: ()
00048 nlocals: 5
00049 flags: 67
00050 consts: ('None',)
00051 
00052 >>> def attrs(obj):
00053 ...     print(obj.attr1)
00054 ...     print(obj.attr2)
00055 ...     print(obj.attr3)
00056 
00057 >>> dump(attrs.__code__)
00058 name: attrs
00059 argcount: 1
00060 kwonlyargcount: 0
00061 names: ('print', 'attr1', 'attr2', 'attr3')
00062 varnames: ('obj',)
00063 cellvars: ()
00064 freevars: ()
00065 nlocals: 1
00066 flags: 67
00067 consts: ('None',)
00068 
00069 >>> def optimize_away():
00070 ...     'doc string'
00071 ...     'not a docstring'
00072 ...     53
00073 ...     0x53
00074 
00075 >>> dump(optimize_away.__code__)
00076 name: optimize_away
00077 argcount: 0
00078 kwonlyargcount: 0
00079 names: ()
00080 varnames: ()
00081 cellvars: ()
00082 freevars: ()
00083 nlocals: 0
00084 flags: 67
00085 consts: ("'doc string'", 'None')
00086 
00087 >>> def keywordonly_args(a,b,*,k1):
00088 ...     return a,b,k1
00089 ...
00090 
00091 >>> dump(keywordonly_args.__code__)
00092 name: keywordonly_args
00093 argcount: 2
00094 kwonlyargcount: 1
00095 names: ()
00096 varnames: ('a', 'b', 'k1')
00097 cellvars: ()
00098 freevars: ()
00099 nlocals: 3
00100 flags: 67
00101 consts: ('None',)
00102 
00103 """
00104 
00105 import unittest
00106 import weakref
00107 import _testcapi
00108 
00109 
00110 def consts(t):
00111     """Yield a doctest-safe sequence of object reprs."""
00112     for elt in t:
00113         r = repr(elt)
00114         if r.startswith("<code object"):
00115             yield "<code object %s>" % elt.co_name
00116         else:
00117             yield r
00118 
00119 def dump(co):
00120     """Print out a text representation of a code object."""
00121     for attr in ["name", "argcount", "kwonlyargcount", "names", "varnames",
00122                  "cellvars", "freevars", "nlocals", "flags"]:
00123         print("%s: %s" % (attr, getattr(co, "co_" + attr)))
00124     print("consts:", tuple(consts(co.co_consts)))
00125 
00126 
00127 class CodeTest(unittest.TestCase):
00128 
00129     def test_newempty(self):
00130         co = _testcapi.code_newempty("filename", "funcname", 15)
00131         self.assertEqual(co.co_filename, "filename")
00132         self.assertEqual(co.co_name, "funcname")
00133         self.assertEqual(co.co_firstlineno, 15)
00134 
00135 
00136 class CodeWeakRefTest(unittest.TestCase):
00137 
00138     def test_basic(self):
00139         # Create a code object in a clean environment so that we know we have
00140         # the only reference to it left.
00141         namespace = {}
00142         exec("def f(): pass", globals(), namespace)
00143         f = namespace["f"]
00144         del namespace
00145 
00146         self.called = False
00147         def callback(code):
00148             self.called = True
00149 
00150         # f is now the last reference to the function, and through it, the code
00151         # object.  While we hold it, check that we can create a weakref and
00152         # deref it.  Then delete it, and check that the callback gets called and
00153         # the reference dies.
00154         coderef = weakref.ref(f.__code__, callback)
00155         self.assertTrue(bool(coderef()))
00156         del f
00157         self.assertFalse(bool(coderef()))
00158         self.assertTrue(self.called)
00159 
00160 
00161 def test_main(verbose=None):
00162     from test.support import run_doctest, run_unittest
00163     from test import test_code
00164     run_doctest(test_code, verbose)
00165     run_unittest(CodeTest, CodeWeakRefTest)
00166 
00167 
00168 if __name__ == "__main__":
00169     test_main()