Salome HOME
legere difference ds VARIABLES_TO_BE...
[tools/eficas.git] / Tests / run.py
1 """
2 This program executes all unitest tests that are found in 
3     - directories with name test* or Test*
4     - files with name test* or Test*
5
6 unitest tests are :
7     - functions and class with names test* or Test*
8     - methods with name test* or Test* from classes with name test* or Test*
9
10 Typical uses are :
11    
12     - execute all tests with text output : python2.4 run.py 
13     - execute all tests with html output : python2.4 run.py --html
14     - execute some tests with text output : python2.4 run.py testelem
15     - execute one test with text output : python2.4 run.py testelem/testsimp1.py
16     - execute all tests with verbosity and html output : python2.4 run.py -v --html
17 """
18
19 import sys,types,os
20 import sre
21 import unittest
22 from optparse import OptionParser
23
24 import config
25
26 testMatch = sre.compile(r'^[Tt]est')
27
28 class TestSuite(unittest.TestSuite):
29     ignore=[]
30     loader = unittest.defaultTestLoader
31
32     def __init__(self, names=[]):
33         self.names=names
34         super(TestSuite,self).__init__()
35         tests=self.collectTests()
36         self.addTests(tests)
37
38     def _import(self,name):
39         mod = __import__(name,{},{})
40         components = name.split('.')
41         for comp in components[1:]:
42             mod = getattr(mod,comp)
43         return mod
44
45     def importdir(self,rep,path):
46         init = os.path.abspath(os.path.join(path,'__init__.py'))
47         if os.path.isfile(init):
48            package=self._import(rep)
49            if package:
50               return TestPackageSuite(package)
51         else:
52            return TestDirectorySuite(path)
53
54     def importfile(self,item,path):
55         root, ext = os.path.splitext(item)
56         if ext != '.py':
57            return  
58         if root.find('/') >= 0:
59            dirname, file = os.path.split(path)
60            root, ext = os.path.splitext(file)
61            sys.path.insert(0,dirname)
62            mod=self._import(root)
63            sys.path.remove(dirname)
64         else:
65            mod=self._import(root)
66         return ModuleTestSuite(mod)
67
68     def collectTests(self):
69         if self.names:
70            entries=self.names
71         else:
72            entries = [ item for item in os.listdir(os.getcwd())
73                         if item.lower().find('test') >= 0 ]
74         self.path=os.getcwd()
75         return self._collectTests(entries)
76
77     def _collectTests(self,entries):
78         tests=[]
79         for item in entries:
80             if (item[0] == '.'
81                 or item in self.ignore
82                 or not testMatch.search(item)):
83                 continue
84             path=os.path.abspath(os.path.join(self.path,item))
85             if os.path.isfile(path):
86                t=self.importfile(item,path)
87                if t:tests.append(t)
88             elif os.path.isdir(path):
89                tests.append(self.importdir(item,path))
90         return tests
91
92 class TestDirectorySuite(TestSuite):
93     def __init__(self,path):
94         self.path=path
95         super(TestDirectorySuite,self).__init__()
96
97     def collectTests(self):
98         tests=[]
99         if self.path:
100             sys.path.insert(0,self.path)
101             entries = os.listdir(self.path)
102             entries.sort()
103             tests=self._collectTests(entries)
104             sys.path.remove(self.path)
105         return tests
106
107 class TestPackageSuite(TestDirectorySuite):
108     def __init__(self,package):
109         self.package=package
110         path=os.path.abspath(os.path.dirname(self.package.__file__))
111         super(TestPackageSuite,self).__init__(path)
112
113     def importdir(self,item,path):
114         init = os.path.abspath(os.path.join(path,'__init__.py'))
115         if os.path.isfile(init):
116            name="%s.%s" % (self.package.__name__,item)
117            package=self._import(name)
118            if package:
119               return TestPackageSuite(package)
120         else:
121            return TestDirectorySuite(path)
122
123     def importfile(self,item,path):
124         root, ext = os.path.splitext(item)
125         if ext != '.py':
126            return
127         name="%s.%s" % (self.package.__name__,root)
128         mod=self._import(name)
129         return ModuleTestSuite(mod)
130
131 class ModuleTestSuite(TestSuite):
132
133     def __init__(self, module):
134         self.module = module
135         super(ModuleTestSuite,self).__init__()
136
137     def collectTests(self):
138         def cmpLineNo(a,b):
139             a_ln = a.func_code.co_firstlineno
140             b_ln = b.func_code.co_firstlineno
141             return cmp(a_ln,b_ln)
142
143         entries = dir(self.module)
144         tests = []
145         func_tests = []
146         for item in entries:
147             test = getattr(self.module,item)
148             if (isinstance(test, (type, types.ClassType))
149                 and issubclass(test,unittest.TestCase)):
150                 if testMatch.search(item):
151                     [ tests.append(case) for case in
152                       self.loader.loadTestsFromTestCase(test)._tests ]
153             elif callable(test) and testMatch.search(item):
154                 # simple functional test
155                 func_tests.append(test)
156
157         # run functional tests in the order in which they are defined
158         func_tests.sort(cmpLineNo)
159         [ tests.append(unittest.FunctionTestCase(test))
160           for test in func_tests ]
161         return tests
162
163
164 class TestProgram(unittest.TestProgram):
165     USAGE="""
166 """
167     def __init__(self):
168         self.testRunner = None
169         self.verbosity = 1
170         self.html=0
171         self.parseArgs(sys.argv)
172         if self.html:
173            import HTMLTestRunner
174            self.testRunner = HTMLTestRunner.HTMLTestRunner(verbosity=self.verbosity)
175         self.createTests()
176         self.runTests()
177
178     def parseArgs(self,argv):
179         parser = OptionParser(usage=self.USAGE)
180         parser.add_option("-v","--verbose",action="count",
181                           dest="verbosity",default=1,
182                           help="Be more verbose. ")
183         parser.add_option("--html",action="store_true",
184                           dest="html",default=0,
185                           help="Produce HTML output ")
186
187         options, args = parser.parse_args(argv)
188         self.verbosity = options.verbosity
189         self.html=options.html
190
191         if args:
192             self.names = list(args)
193             if self.names[0] == 'run.py':
194                 self.names = self.names[1:]
195
196     def createTests(self):
197         self.test = TestSuite(self.names)
198
199 if __name__ == "__main__":
200     TestProgram()
201