home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 July / maximum-cd-2011-07.iso / DiscContents / LibO_3.3.2_Win_x86_install_multi.exe / libreoffice1.cab / test_inspect.py < prev    next >
Encoding:
Python Source  |  2011-03-15  |  19.2 KB  |  499 lines

  1. import sys
  2. import types
  3. import unittest
  4. import inspect
  5. import datetime
  6.  
  7. from test.test_support import TESTFN, run_unittest
  8.  
  9. from test import inspect_fodder as mod
  10. from test import inspect_fodder2 as mod2
  11.  
  12. # Functions tested in this suite:
  13. # ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode,
  14. # isbuiltin, isroutine, isgenerator, isgeneratorfunction, getmembers,
  15. # getdoc, getfile, getmodule, getsourcefile, getcomments, getsource,
  16. # getclasstree, getargspec, getargvalues, formatargspec, formatargvalues,
  17. # currentframe, stack, trace, isdatadescriptor
  18.  
  19. modfile = mod.__file__
  20. if modfile.endswith(('c', 'o')):
  21.     modfile = modfile[:-1]
  22.  
  23. import __builtin__
  24.  
  25. try:
  26.     1/0
  27. except:
  28.     tb = sys.exc_traceback
  29.  
  30. git = mod.StupidGit()
  31.  
  32. class IsTestBase(unittest.TestCase):
  33.     predicates = set([inspect.isbuiltin, inspect.isclass, inspect.iscode,
  34.                       inspect.isframe, inspect.isfunction, inspect.ismethod,
  35.                       inspect.ismodule, inspect.istraceback,
  36.                       inspect.isgenerator, inspect.isgeneratorfunction])
  37.  
  38.     def istest(self, predicate, exp):
  39.         obj = eval(exp)
  40.         self.failUnless(predicate(obj), '%s(%s)' % (predicate.__name__, exp))
  41.  
  42.         for other in self.predicates - set([predicate]):
  43.             if predicate == inspect.isgeneratorfunction and\
  44.                other == inspect.isfunction:
  45.                 continue
  46.             self.failIf(other(obj), 'not %s(%s)' % (other.__name__, exp))
  47.  
  48. def generator_function_example(self):
  49.     for i in xrange(2):
  50.         yield i
  51.  
  52. class TestPredicates(IsTestBase):
  53.     def test_sixteen(self):
  54.         count = len(filter(lambda x:x.startswith('is'), dir(inspect)))
  55.         # This test is here for remember you to update Doc/library/inspect.rst
  56.         # which claims there are 16 such functions
  57.         expected = 16
  58.         err_msg = "There are %d (not %d) is* functions" % (count, expected)
  59.         self.assertEqual(count, expected, err_msg)
  60.  
  61.  
  62.     def test_excluding_predicates(self):
  63.         self.istest(inspect.isbuiltin, 'sys.exit')
  64.         self.istest(inspect.isbuiltin, '[].append')
  65.         self.istest(inspect.isclass, 'mod.StupidGit')
  66.         self.istest(inspect.iscode, 'mod.spam.func_code')
  67.         self.istest(inspect.isframe, 'tb.tb_frame')
  68.         self.istest(inspect.isfunction, 'mod.spam')
  69.         self.istest(inspect.ismethod, 'mod.StupidGit.abuse')
  70.         self.istest(inspect.ismethod, 'git.argue')
  71.         self.istest(inspect.ismodule, 'mod')
  72.         self.istest(inspect.istraceback, 'tb')
  73.         self.istest(inspect.isdatadescriptor, '__builtin__.file.closed')
  74.         self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace')
  75.         self.istest(inspect.isgenerator, '(x for x in xrange(2))')
  76.         self.istest(inspect.isgeneratorfunction, 'generator_function_example')
  77.         if hasattr(types, 'GetSetDescriptorType'):
  78.             self.istest(inspect.isgetsetdescriptor,
  79.                         'type(tb.tb_frame).f_locals')
  80.         else:
  81.             self.failIf(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
  82.         if hasattr(types, 'MemberDescriptorType'):
  83.             self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
  84.         else:
  85.             self.failIf(inspect.ismemberdescriptor(datetime.timedelta.days))
  86.  
  87.     def test_isroutine(self):
  88.         self.assert_(inspect.isroutine(mod.spam))
  89.         self.assert_(inspect.isroutine([].count))
  90.  
  91. class TestInterpreterStack(IsTestBase):
  92.     def __init__(self, *args, **kwargs):
  93.         unittest.TestCase.__init__(self, *args, **kwargs)
  94.  
  95.         git.abuse(7, 8, 9)
  96.  
  97.     def test_abuse_done(self):
  98.         self.istest(inspect.istraceback, 'git.ex[2]')
  99.         self.istest(inspect.isframe, 'mod.fr')
  100.  
  101.     def test_stack(self):
  102.         self.assert_(len(mod.st) >= 5)
  103.         self.assertEqual(mod.st[0][1:],
  104.              (modfile, 16, 'eggs', ['    st = inspect.stack()\n'], 0))
  105.         self.assertEqual(mod.st[1][1:],
  106.              (modfile, 9, 'spam', ['    eggs(b + d, c + f)\n'], 0))
  107.         self.assertEqual(mod.st[2][1:],
  108.              (modfile, 43, 'argue', ['            spam(a, b, c)\n'], 0))
  109.         self.assertEqual(mod.st[3][1:],
  110.              (modfile, 39, 'abuse', ['        self.argue(a, b, c)\n'], 0))
  111.  
  112.     def test_trace(self):
  113.         self.assertEqual(len(git.tr), 3)
  114.         self.assertEqual(git.tr[0][1:], (modfile, 43, 'argue',
  115.                                          ['            spam(a, b, c)\n'], 0))
  116.         self.assertEqual(git.tr[1][1:], (modfile, 9, 'spam',
  117.                                          ['    eggs(b + d, c + f)\n'], 0))
  118.         self.assertEqual(git.tr[2][1:], (modfile, 18, 'eggs',
  119.                                          ['    q = y / 0\n'], 0))
  120.  
  121.     def test_frame(self):
  122.         args, varargs, varkw, locals = inspect.getargvalues(mod.fr)
  123.         self.assertEqual(args, ['x', 'y'])
  124.         self.assertEqual(varargs, None)
  125.         self.assertEqual(varkw, None)
  126.         self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14})
  127.         self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
  128.                          '(x=11, y=14)')
  129.  
  130.     def test_previous_frame(self):
  131.         args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back)
  132.         self.assertEqual(args, ['a', 'b', 'c', 'd', ['e', ['f']]])
  133.         self.assertEqual(varargs, 'g')
  134.         self.assertEqual(varkw, 'h')
  135.         self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
  136.              '(a=7, b=8, c=9, d=3, (e=4, (f=5,)), *g=(), **h={})')
  137.  
  138. class GetSourceBase(unittest.TestCase):
  139.     # Subclasses must override.
  140.     fodderFile = None
  141.  
  142.     def __init__(self, *args, **kwargs):
  143.         unittest.TestCase.__init__(self, *args, **kwargs)
  144.  
  145.         self.source = file(inspect.getsourcefile(self.fodderFile)).read()
  146.  
  147.     def sourcerange(self, top, bottom):
  148.         lines = self.source.split("\n")
  149.         return "\n".join(lines[top-1:bottom]) + "\n"
  150.  
  151.     def assertSourceEqual(self, obj, top, bottom):
  152.         self.assertEqual(inspect.getsource(obj),
  153.                          self.sourcerange(top, bottom))
  154.  
  155. class TestRetrievingSourceCode(GetSourceBase):
  156.     fodderFile = mod
  157.  
  158.     def test_getclasses(self):
  159.         classes = inspect.getmembers(mod, inspect.isclass)
  160.         self.assertEqual(classes,
  161.                          [('FesteringGob', mod.FesteringGob),
  162.                           ('MalodorousPervert', mod.MalodorousPervert),
  163.                           ('ParrotDroppings', mod.ParrotDroppings),
  164.                           ('StupidGit', mod.StupidGit)])
  165.         tree = inspect.getclasstree([cls[1] for cls in classes], 1)
  166.         self.assertEqual(tree,
  167.                          [(mod.ParrotDroppings, ()),
  168.                           (mod.StupidGit, ()),
  169.                           [(mod.MalodorousPervert, (mod.StupidGit,)),
  170.                            [(mod.FesteringGob, (mod.MalodorousPervert,
  171.                                                    mod.ParrotDroppings))
  172.                             ]
  173.                            ]
  174.                           ])
  175.  
  176.     def test_getfunctions(self):
  177.         functions = inspect.getmembers(mod, inspect.isfunction)
  178.         self.assertEqual(functions, [('eggs', mod.eggs),
  179.                                      ('spam', mod.spam)])
  180.  
  181.     def test_getdoc(self):
  182.         self.assertEqual(inspect.getdoc(mod), 'A module docstring.')
  183.         self.assertEqual(inspect.getdoc(mod.StupidGit),
  184.                          'A longer,\n\nindented\n\ndocstring.')
  185.         self.assertEqual(inspect.getdoc(git.abuse),
  186.                          'Another\n\ndocstring\n\ncontaining\n\ntabs')
  187.  
  188.     def test_cleandoc(self):
  189.         self.assertEqual(inspect.cleandoc('An\n    indented\n    docstring.'),
  190.                          'An\nindented\ndocstring.')
  191.  
  192.     def test_getcomments(self):
  193.         self.assertEqual(inspect.getcomments(mod), '# line 1\n')
  194.         self.assertEqual(inspect.getcomments(mod.StupidGit), '# line 20\n')
  195.  
  196.     def test_getmodule(self):
  197.         # Check actual module
  198.         self.assertEqual(inspect.getmodule(mod), mod)
  199.         # Check class (uses __module__ attribute)
  200.         self.assertEqual(inspect.getmodule(mod.StupidGit), mod)
  201.         # Check a method (no __module__ attribute, falls back to filename)
  202.         self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod)
  203.         # Do it again (check the caching isn't broken)
  204.         self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod)
  205.         # Check a builtin
  206.         self.assertEqual(inspect.getmodule(str), sys.modules["__builtin__"])
  207.         # Check filename override
  208.         self.assertEqual(inspect.getmodule(None, modfile), mod)
  209.  
  210.     def test_getsource(self):
  211.         self.assertSourceEqual(git.abuse, 29, 39)
  212.         self.assertSourceEqual(mod.StupidGit, 21, 46)
  213.  
  214.     def test_getsourcefile(self):
  215.         self.assertEqual(inspect.getsourcefile(mod.spam), modfile)
  216.         self.assertEqual(inspect.getsourcefile(git.abuse), modfile)
  217.  
  218.     def test_getfile(self):
  219.         self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__)
  220.  
  221.     def test_getmodule_recursion(self):
  222.         from types import ModuleType
  223.         name = '__inspect_dummy'
  224.         m = sys.modules[name] = ModuleType(name)
  225.         m.__file__ = "<string>" # hopefully not a real filename...
  226.         m.__loader__ = "dummy"  # pretend the filename is understood by a loader
  227.         exec "def x(): pass" in m.__dict__
  228.         self.assertEqual(inspect.getsourcefile(m.x.func_code), '<string>')
  229.         del sys.modules[name]
  230.         inspect.getmodule(compile('a=10','','single'))
  231.  
  232. class TestDecorators(GetSourceBase):
  233.     fodderFile = mod2
  234.  
  235.     def test_wrapped_decorator(self):
  236.         self.assertSourceEqual(mod2.wrapped, 14, 17)
  237.  
  238.     def test_replacing_decorator(self):
  239.         self.assertSourceEqual(mod2.gone, 9, 10)
  240.  
  241. class TestOneliners(GetSourceBase):
  242.     fodderFile = mod2
  243.     def test_oneline_lambda(self):
  244.         # Test inspect.getsource with a one-line lambda function.
  245.         self.assertSourceEqual(mod2.oll, 25, 25)
  246.  
  247.     def test_threeline_lambda(self):
  248.         # Test inspect.getsource with a three-line lambda function,
  249.         # where the second and third lines are _not_ indented.
  250.         self.assertSourceEqual(mod2.tll, 28, 30)
  251.  
  252.     def test_twoline_indented_lambda(self):
  253.         # Test inspect.getsource with a two-line lambda function,
  254.         # where the second line _is_ indented.
  255.         self.assertSourceEqual(mod2.tlli, 33, 34)
  256.  
  257.     def test_onelinefunc(self):
  258.         # Test inspect.getsource with a regular one-line function.
  259.         self.assertSourceEqual(mod2.onelinefunc, 37, 37)
  260.  
  261.     def test_manyargs(self):
  262.         # Test inspect.getsource with a regular function where
  263.         # the arguments are on two lines and _not_ indented and
  264.         # the body on the second line with the last arguments.
  265.         self.assertSourceEqual(mod2.manyargs, 40, 41)
  266.  
  267.     def test_twolinefunc(self):
  268.         # Test inspect.getsource with a regular function where
  269.         # the body is on two lines, following the argument list and
  270.         # continued on the next line by a \\.
  271.         self.assertSourceEqual(mod2.twolinefunc, 44, 45)
  272.  
  273.     def test_lambda_in_list(self):
  274.         # Test inspect.getsource with a one-line lambda function
  275.         # defined in a list, indented.
  276.         self.assertSourceEqual(mod2.a[1], 49, 49)
  277.  
  278.     def test_anonymous(self):
  279.         # Test inspect.getsource with a lambda function defined
  280.         # as argument to another function.
  281.         self.assertSourceEqual(mod2.anonymous, 55, 55)
  282.  
  283. class TestBuggyCases(GetSourceBase):
  284.     fodderFile = mod2
  285.  
  286.     def test_with_comment(self):
  287.         self.assertSourceEqual(mod2.with_comment, 58, 59)
  288.  
  289.     def test_multiline_sig(self):
  290.         self.assertSourceEqual(mod2.multiline_sig[0], 63, 64)
  291.  
  292.     def test_nested_class(self):
  293.         self.assertSourceEqual(mod2.func69().func71, 71, 72)
  294.  
  295.     def test_one_liner_followed_by_non_name(self):
  296.         self.assertSourceEqual(mod2.func77, 77, 77)
  297.  
  298.     def test_one_liner_dedent_non_name(self):
  299.         self.assertSourceEqual(mod2.cls82.func83, 83, 83)
  300.  
  301.     def test_with_comment_instead_of_docstring(self):
  302.         self.assertSourceEqual(mod2.func88, 88, 90)
  303.  
  304.     def test_method_in_dynamic_class(self):
  305.         self.assertSourceEqual(mod2.method_in_dynamic_class, 95, 97)
  306.  
  307. # Helper for testing classify_class_attrs.
  308. def attrs_wo_objs(cls):
  309.     return [t[:3] for t in inspect.classify_class_attrs(cls)]
  310.  
  311. class TestClassesAndFunctions(unittest.TestCase):
  312.     def test_classic_mro(self):
  313.         # Test classic-class method resolution order.
  314.         class A:    pass
  315.         class B(A): pass
  316.         class C(A): pass
  317.         class D(B, C): pass
  318.  
  319.         expected = (D, B, A, C)
  320.         got = inspect.getmro(D)
  321.         self.assertEqual(expected, got)
  322.  
  323.     def test_newstyle_mro(self):
  324.         # The same w/ new-class MRO.
  325.         class A(object):    pass
  326.         class B(A): pass
  327.         class C(A): pass
  328.         class D(B, C): pass
  329.  
  330.         expected = (D, B, C, A, object)
  331.         got = inspect.getmro(D)
  332.         self.assertEqual(expected, got)
  333.  
  334.     def assertArgSpecEquals(self, routine, args_e, varargs_e = None,
  335.                             varkw_e = None, defaults_e = None,
  336.                             formatted = None):
  337.         args, varargs, varkw, defaults = inspect.getargspec(routine)
  338.         self.assertEqual(args, args_e)
  339.         self.assertEqual(varargs, varargs_e)
  340.         self.assertEqual(varkw, varkw_e)
  341.         self.assertEqual(defaults, defaults_e)
  342.         if formatted is not None:
  343.             self.assertEqual(inspect.formatargspec(args, varargs, varkw, defaults),
  344.                              formatted)
  345.  
  346.     def test_getargspec(self):
  347.         self.assertArgSpecEquals(mod.eggs, ['x', 'y'], formatted = '(x, y)')
  348.  
  349.         self.assertArgSpecEquals(mod.spam,
  350.                                  ['a', 'b', 'c', 'd', ['e', ['f']]],
  351.                                  'g', 'h', (3, (4, (5,))),
  352.                                  '(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h)')
  353.  
  354.     def test_getargspec_method(self):
  355.         class A(object):
  356.             def m(self):
  357.                 pass
  358.         self.assertArgSpecEquals(A.m, ['self'])
  359.  
  360.     def test_getargspec_sublistofone(self):
  361.         def sublistOfOne((foo,)): return 1
  362.         self.assertArgSpecEquals(sublistOfOne, [['foo']])
  363.  
  364.         def fakeSublistOfOne((foo)): return 1
  365.         self.assertArgSpecEquals(fakeSublistOfOne, ['foo'])
  366.  
  367.     def test_classify_oldstyle(self):
  368.         class A:
  369.             def s(): pass
  370.             s = staticmethod(s)
  371.  
  372.             def c(cls): pass
  373.             c = classmethod(c)
  374.  
  375.             def getp(self): pass
  376.             p = property(getp)
  377.  
  378.             def m(self): pass
  379.  
  380.             def m1(self): pass
  381.  
  382.             datablob = '1'
  383.  
  384.         attrs = attrs_wo_objs(A)
  385.         self.assert_(('s', 'static method', A) in attrs, 'missing static method')
  386.         self.assert_(('c', 'class method', A) in attrs, 'missing class method')
  387.         self.assert_(('p', 'property', A) in attrs, 'missing property')
  388.         self.assert_(('m', 'method', A) in attrs, 'missing plain method')
  389.         self.assert_(('m1', 'method', A) in attrs, 'missing plain method')
  390.         self.assert_(('datablob', 'data', A) in attrs, 'missing data')
  391.  
  392.         class B(A):
  393.             def m(self): pass
  394.  
  395.         attrs = attrs_wo_objs(B)
  396.         self.assert_(('s', 'static method', A) in attrs, 'missing static method')
  397.         self.assert_(('c', 'class method', A) in attrs, 'missing class method')
  398.         self.assert_(('p', 'property', A) in attrs, 'missing property')
  399.         self.assert_(('m', 'method', B) in attrs, 'missing plain method')
  400.         self.assert_(('m1', 'method', A) in attrs, 'missing plain method')
  401.         self.assert_(('datablob', 'data', A) in attrs, 'missing data')
  402.  
  403.  
  404.         class C(A):
  405.             def m(self): pass
  406.             def c(self): pass
  407.  
  408.         attrs = attrs_wo_objs(C)
  409.         self.assert_(('s', 'static method', A) in attrs, 'missing static method')
  410.         self.assert_(('c', 'method', C) in attrs, 'missing plain method')
  411.         self.assert_(('p', 'property', A) in attrs, 'missing property')
  412.         self.assert_(('m', 'method', C) in attrs, 'missing plain method')
  413.         self.assert_(('m1', 'method', A) in attrs, 'missing plain method')
  414.         self.assert_(('datablob', 'data', A) in attrs, 'missing data')
  415.  
  416.         class D(B, C):
  417.             def m1(self): pass
  418.  
  419.         attrs = attrs_wo_objs(D)
  420.         self.assert_(('s', 'static method', A) in attrs, 'missing static method')
  421.         self.assert_(('c', 'class method', A) in attrs, 'missing class method')
  422.         self.assert_(('p', 'property', A) in attrs, 'missing property')
  423.         self.assert_(('m', 'method', B) in attrs, 'missing plain method')
  424.         self.assert_(('m1', 'method', D) in attrs, 'missing plain method')
  425.         self.assert_(('datablob', 'data', A) in attrs, 'missing data')
  426.  
  427.     # Repeat all that, but w/ new-style classes.
  428.     def test_classify_newstyle(self):
  429.         class A(object):
  430.  
  431.             def s(): pass
  432.             s = staticmethod(s)
  433.  
  434.             def c(cls): pass
  435.             c = classmethod(c)
  436.  
  437.             def getp(self): pass
  438.             p = property(getp)
  439.  
  440.             def m(self): pass
  441.  
  442.             def m1(self): pass
  443.  
  444.             datablob = '1'
  445.  
  446.         attrs = attrs_wo_objs(A)
  447.         self.assert_(('s', 'static method', A) in attrs, 'missing static method')
  448.         self.assert_(('c', 'class method', A) in attrs, 'missing class method')
  449.         self.assert_(('p', 'property', A) in attrs, 'missing property')
  450.         self.assert_(('m', 'method', A) in attrs, 'missing plain method')
  451.         self.assert_(('m1', 'method', A) in attrs, 'missing plain method')
  452.         self.assert_(('datablob', 'data', A) in attrs, 'missing data')
  453.  
  454.         class B(A):
  455.  
  456.             def m(self): pass
  457.  
  458.         attrs = attrs_wo_objs(B)
  459.         self.assert_(('s', 'static method', A) in attrs, 'missing static method')
  460.         self.assert_(('c', 'class method', A) in attrs, 'missing class method')
  461.         self.assert_(('p', 'property', A) in attrs, 'missing property')
  462.         self.assert_(('m', 'method', B) in attrs, 'missing plain method')
  463.         self.assert_(('m1', 'method', A) in attrs, 'missing plain method')
  464.         self.assert_(('datablob', 'data', A) in attrs, 'missing data')
  465.  
  466.  
  467.         class C(A):
  468.  
  469.             def m(self): pass
  470.             def c(self): pass
  471.  
  472.         attrs = attrs_wo_objs(C)
  473.         self.assert_(('s', 'static method', A) in attrs, 'missing static method')
  474.         self.assert_(('c', 'method', C) in attrs, 'missing plain method')
  475.         self.assert_(('p', 'property', A) in attrs, 'missing property')
  476.         self.assert_(('m', 'method', C) in attrs, 'missing plain method')
  477.         self.assert_(('m1', 'method', A) in attrs, 'missing plain method')
  478.         self.assert_(('datablob', 'data', A) in attrs, 'missing data')
  479.  
  480.         class D(B, C):
  481.  
  482.             def m1(self): pass
  483.  
  484.         attrs = attrs_wo_objs(D)
  485.         self.assert_(('s', 'static method', A) in attrs, 'missing static method')
  486.         self.assert_(('c', 'method', C) in attrs, 'missing plain method')
  487.         self.assert_(('p', 'property', A) in attrs, 'missing property')
  488.         self.assert_(('m', 'method', B) in attrs, 'missing plain method')
  489.         self.assert_(('m1', 'method', D) in attrs, 'missing plain method')
  490.         self.assert_(('datablob', 'data', A) in attrs, 'missing data')
  491.  
  492. def test_main():
  493.     run_unittest(TestDecorators, TestRetrievingSourceCode, TestOneliners,
  494.                  TestBuggyCases,
  495.                  TestInterpreterStack, TestClassesAndFunctions, TestPredicates)
  496.  
  497. if __name__ == "__main__":
  498.     test_main()
  499.