~ubuntu-branches/ubuntu/maverick/python3.1/maverick

« back to all changes in this revision

Viewing changes to Lib/test/test_pyclbr.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-03-23 00:01:27 UTC
  • Revision ID: james.westby@ubuntu.com-20090323000127-5fstfxju4ufrhthq
Tags: upstream-3.1~a1+20090322
ImportĀ upstreamĀ versionĀ 3.1~a1+20090322

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
'''
 
2
   Test cases for pyclbr.py
 
3
   Nick Mathewson
 
4
'''
 
5
from test.support import run_unittest
 
6
import sys
 
7
from types import FunctionType, MethodType, BuiltinFunctionType
 
8
import pyclbr
 
9
from unittest import TestCase
 
10
 
 
11
StaticMethodType = type(staticmethod(lambda: None))
 
12
ClassMethodType = type(classmethod(lambda c: None))
 
13
 
 
14
# Here we test the python class browser code.
 
15
#
 
16
# The main function in this suite, 'testModule', compares the output
 
17
# of pyclbr with the introspected members of a module.  Because pyclbr
 
18
# is imperfect (as designed), testModule is called with a set of
 
19
# members to ignore.
 
20
 
 
21
class PyclbrTest(TestCase):
 
22
 
 
23
    def assertListEq(self, l1, l2, ignore):
 
24
        ''' succeed iff {l1} - {ignore} == {l2} - {ignore} '''
 
25
        missing = (set(l1) ^ set(l2)) - set(ignore)
 
26
        if missing:
 
27
            print("l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore), file=sys.stderr)
 
28
            self.fail("%r missing" % missing.pop())
 
29
 
 
30
    def assertHasattr(self, obj, attr, ignore):
 
31
        ''' succeed iff hasattr(obj,attr) or attr in ignore. '''
 
32
        if attr in ignore: return
 
33
        if not hasattr(obj, attr): print("???", attr)
 
34
        self.failUnless(hasattr(obj, attr),
 
35
                        'expected hasattr(%r, %r)' % (obj, attr))
 
36
 
 
37
 
 
38
    def assertHaskey(self, obj, key, ignore):
 
39
        ''' succeed iff key in obj or key in ignore. '''
 
40
        if key in ignore: return
 
41
        if key not in obj:
 
42
            print("***",key, file=sys.stderr)
 
43
        self.failUnless(key in obj, "%r in %r" % (key, obj))
 
44
 
 
45
    def assertEqualsOrIgnored(self, a, b, ignore):
 
46
        ''' succeed iff a == b or a in ignore or b in ignore '''
 
47
        if a not in ignore and b not in ignore:
 
48
            self.assertEquals(a, b)
 
49
 
 
50
    def checkModule(self, moduleName, module=None, ignore=()):
 
51
        ''' succeed iff pyclbr.readmodule_ex(modulename) corresponds
 
52
            to the actual module object, module.  Any identifiers in
 
53
            ignore are ignored.   If no module is provided, the appropriate
 
54
            module is loaded with __import__.'''
 
55
 
 
56
        ignore = set(ignore) | set(['object'])
 
57
 
 
58
        if module is None:
 
59
            # Import it.
 
60
            # ('<silly>' is to work around an API silliness in __import__)
 
61
            module = __import__(moduleName, globals(), {}, ['<silly>'])
 
62
 
 
63
        dict = pyclbr.readmodule_ex(moduleName)
 
64
 
 
65
        def ismethod(oclass, obj, name):
 
66
            classdict = oclass.__dict__
 
67
            if isinstance(obj, MethodType):
 
68
                # could be a classmethod
 
69
                if (not isinstance(classdict[name], ClassMethodType) or
 
70
                    obj.__self__ is not oclass):
 
71
                    return False
 
72
            elif not isinstance(obj, FunctionType):
 
73
                return False
 
74
 
 
75
            objname = obj.__name__
 
76
            if objname.startswith("__") and not objname.endswith("__"):
 
77
                objname = "_%s%s" % (oclass.__name__, objname)
 
78
            return objname == name
 
79
 
 
80
        # Make sure the toplevel functions and classes are the same.
 
81
        for name, value in dict.items():
 
82
            if name in ignore:
 
83
                continue
 
84
            self.assertHasattr(module, name, ignore)
 
85
            py_item = getattr(module, name)
 
86
            if isinstance(value, pyclbr.Function):
 
87
                self.assert_(isinstance(py_item, (FunctionType, BuiltinFunctionType)))
 
88
                if py_item.__module__ != moduleName:
 
89
                    continue   # skip functions that came from somewhere else
 
90
                self.assertEquals(py_item.__module__, value.module)
 
91
            else:
 
92
                self.failUnless(isinstance(py_item, type))
 
93
                if py_item.__module__ != moduleName:
 
94
                    continue   # skip classes that came from somewhere else
 
95
 
 
96
                real_bases = [base.__name__ for base in py_item.__bases__]
 
97
                pyclbr_bases = [ getattr(base, 'name', base)
 
98
                                 for base in value.super ]
 
99
 
 
100
                try:
 
101
                    self.assertListEq(real_bases, pyclbr_bases, ignore)
 
102
                except:
 
103
                    print("class=%s" % py_item, file=sys.stderr)
 
104
                    raise
 
105
 
 
106
                actualMethods = []
 
107
                for m in py_item.__dict__.keys():
 
108
                    if ismethod(py_item, getattr(py_item, m), m):
 
109
                        actualMethods.append(m)
 
110
                foundMethods = []
 
111
                for m in value.methods.keys():
 
112
                    if m[:2] == '__' and m[-2:] != '__':
 
113
                        foundMethods.append('_'+name+m)
 
114
                    else:
 
115
                        foundMethods.append(m)
 
116
 
 
117
                try:
 
118
                    self.assertListEq(foundMethods, actualMethods, ignore)
 
119
                    self.assertEquals(py_item.__module__, value.module)
 
120
 
 
121
                    self.assertEqualsOrIgnored(py_item.__name__, value.name,
 
122
                                               ignore)
 
123
                    # can't check file or lineno
 
124
                except:
 
125
                    print("class=%s" % py_item, file=sys.stderr)
 
126
                    raise
 
127
 
 
128
        # Now check for missing stuff.
 
129
        def defined_in(item, module):
 
130
            if isinstance(item, type):
 
131
                return item.__module__ == module.__name__
 
132
            if isinstance(item, FunctionType):
 
133
                return item.__globals__ is module.__dict__
 
134
            return False
 
135
        for name in dir(module):
 
136
            item = getattr(module, name)
 
137
            if isinstance(item,  (type, FunctionType)):
 
138
                if defined_in(item, module):
 
139
                    self.assertHaskey(dict, name, ignore)
 
140
 
 
141
    def test_easy(self):
 
142
        self.checkModule('pyclbr')
 
143
        self.checkModule('ast')
 
144
        self.checkModule('doctest', ignore=("TestResults", "_SpoofOut"))
 
145
        self.checkModule('difflib', ignore=("Match",))
 
146
 
 
147
    def test_decorators(self):
 
148
        # XXX: See comment in pyclbr_input.py for a test that would fail
 
149
        #      if it were not commented out.
 
150
        #
 
151
        self.checkModule('test.pyclbr_input', ignore=['om'])
 
152
 
 
153
    def test_others(self):
 
154
        cm = self.checkModule
 
155
 
 
156
        # These were once about the 10 longest modules
 
157
        cm('random', ignore=('Random',))  # from _random import Random as CoreGenerator
 
158
        cm('cgi', ignore=('log',))      # set with = in module
 
159
        cm('pickle')
 
160
        cm('aifc', ignore=('openfp',))  # set with = in module
 
161
        cm('sre_parse', ignore=('dump',)) # from sre_constants import *
 
162
        cm('pdb')
 
163
        cm('pydoc')
 
164
 
 
165
        # Tests for modules inside packages
 
166
        cm('email.parser')
 
167
        cm('test.test_pyclbr')
 
168
 
 
169
 
 
170
def test_main():
 
171
    run_unittest(PyclbrTest)
 
172
 
 
173
 
 
174
if __name__ == "__main__":
 
175
    test_main()