xref: /petsc/src/binding/petsc4py/test/runtests.py (revision 3a9118455f13b94ce2a527ac4fd5d4d086f4f1f7)
1import sys, os
2import optparse
3import unittest
4
5def getoptionparser():
6    parser = optparse.OptionParser()
7
8    parser.add_option("-q", "--quiet",
9                      action="store_const", const=0, dest="verbose", default=1,
10                      help="do not print status messages to stdout")
11    parser.add_option("-v", "--verbose",
12                      action="store_const", const=2, dest="verbose", default=1,
13                      help="print status messages to stdout")
14    parser.add_option("-i", "--include", type="string",
15                      action="append",  dest="include", default=[],
16                      help="include tests matching PATTERN", metavar="PATTERN")
17    parser.add_option("-e", "--exclude", type="string",
18                      action="append", dest="exclude", default=[],
19                      help="exclude tests matching PATTERN", metavar="PATTERN")
20    parser.add_option("-f", "--failfast",
21                      action="store_true", dest="failfast", default=False,
22                      help="Stop on first failure")
23    parser.add_option("--no-builddir",
24                      action="store_false", dest="builddir", default=True,
25                      help="disable testing from build directory")
26    parser.add_option("--path", type="string",
27                      action="append", dest="path", default=[],
28                      help="prepend PATH to sys.path", metavar="PATH")
29    parser.add_option("--refleaks", type="int",
30                      action="store", dest="repeats", default=3,
31                      help="run tests REPEAT times in a loop to catch leaks",
32                      metavar="REPEAT")
33    parser.add_option("--arch", type="string",
34                      action="store", dest="arch", default=None,
35                      help="use PETSC_ARCH",
36                      metavar="PETSC_ARCH")
37    parser.add_option("-s","--summary",
38                      action="store_true", dest="summary", default=0,
39                      help="print PETSc log summary")
40    return parser
41
42def getbuilddir():
43    from distutils.util import get_platform
44    s = os.path.join("build", "lib.%s-%.3s" % (get_platform(), sys.version))
45    if hasattr(sys, 'gettotalrefcount'): s += '-pydebug'
46    return s
47
48def setup_python(options):
49    rootdir = os.path.dirname(os.path.dirname(__file__))
50    builddir = os.path.join(rootdir, getbuilddir())
51    if options.builddir and os.path.exists(builddir):
52        sys.path.insert(0, builddir)
53    if options.path:
54        path = options.path[:]
55        path.reverse()
56        for p in path:
57            sys.path.insert(0, p)
58
59def setup_unittest(options):
60    from unittest import TestSuite
61    try:
62        from unittest.runner import _WritelnDecorator
63    except ImportError:
64        from unittest import _WritelnDecorator
65    #
66    writeln_orig = _WritelnDecorator.writeln
67    def writeln(self, message=''):
68        try: self.stream.flush()
69        except: pass
70        writeln_orig(self, message)
71        try: self.stream.flush()
72        except: pass
73    _WritelnDecorator.writeln = writeln
74
75def import_package(options, pkgname):
76    args = [
77        sys.argv[0],
78        '-malloc',
79        '-malloc_debug',
80        '-malloc_dump',
81    ]
82    if options.summary:
83        args.append('-log_view')
84    package = __import__(pkgname)
85    package.init(args, arch=options.arch)
86    return package
87
88def getprocessorinfo():
89    from platform import uname
90    from petsc4py.PETSc import COMM_WORLD
91    rank = COMM_WORLD.getRank()
92    name = uname()[1]
93    return (rank, name)
94
95def getlibraryinfo():
96    from petsc4py import PETSc
97    (major, minor, micro) = PETSc.Sys.getVersion()
98    r = PETSc.Sys.getVersionInfo()['release']
99    if r: release = 'release'
100    else: release = 'development'
101    arch = PETSc.__arch__
102    return ("PETSc %d.%d.%d %s (conf: '%s')"
103            % (major, minor, micro, release, arch) )
104
105def getpythoninfo():
106    x, y = sys.version_info[:2]
107    return ("Python %d.%d (%s)" % (x, y, sys.executable))
108
109def getpackageinfo(pkg):
110    return ("%s %s (%s)" % (pkg.__name__,
111                            pkg.__version__,
112                            pkg.__path__[0]))
113
114def writeln(message='', endl='\n'):
115    from petsc4py.PETSc import Sys
116    Sys.syncPrint(message, endl=endl, flush=True)
117
118def print_banner(options, package):
119    r, n = getprocessorinfo()
120    fmt = "[%d@%s] %s"
121    if options.verbose:
122        writeln(fmt % (r, n, getpythoninfo()))
123        writeln(fmt % (r, n, getlibraryinfo()))
124        writeln(fmt % (r, n, getpackageinfo(package)))
125
126def load_tests(options, args):
127    from glob import glob
128    import re
129    testsuitedir = os.path.dirname(__file__)
130    sys.path.insert(0, testsuitedir)
131    pattern = 'test_*.py'
132    wildcard = os.path.join(testsuitedir, pattern)
133    testfiles = glob(wildcard)
134    testfiles.sort()
135    testsuite = unittest.TestSuite()
136    testloader = unittest.TestLoader()
137    include = exclude = None
138    if options.include:
139        include = re.compile('|'.join(options.include)).search
140    if options.exclude:
141        exclude = re.compile('|'.join(options.exclude)).search
142    for testfile in testfiles:
143        filename = os.path.basename(testfile)
144        testname = os.path.splitext(filename)[0]
145        if ((exclude and exclude(testname)) or
146            (include and not include(testname))):
147            continue
148        module = __import__(testname)
149        for arg in args:
150            try:
151                cases = testloader.loadTestsFromNames((arg,), module)
152                testsuite.addTests(cases)
153            except AttributeError:
154                pass
155        if not args:
156            cases = testloader.loadTestsFromModule(module)
157            testsuite.addTests(cases)
158    return testsuite
159
160def run_tests(options, testsuite, runner=None):
161    if runner is None:
162        runner = unittest.TextTestRunner(verbosity=options.verbose)
163        runner.failfast = options.failfast
164    result = runner.run(testsuite)
165    return result.wasSuccessful()
166
167def test_refleaks(options, args):
168    from sys import gettotalrefcount
169    from gc import collect
170    from copy import deepcopy
171    testsuite = load_tests(options, args)
172    class EmptyIO(object):
173        def write(self, *args):
174            pass
175    runner = unittest.TextTestRunner(stream=EmptyIO(), verbosity=0)
176    rank, name = getprocessorinfo()
177    r1 = r2 = 0
178    repeats = options.repeats
179    while repeats:
180        collect()
181        r1 = gettotalrefcount()
182        run_tests(options, deepcopy(testsuite), runner)
183        collect()
184        r2 = gettotalrefcount()
185        leaks = r2-r1
186        if leaks and repeats < options.repeats:
187            writeln('[%d@%s] refleaks:  (%d - %d) --> %d'
188                    % (rank, name, r2, r1, leaks))
189        repeats -= 1
190
191def abort(code=1):
192    os.abort()
193
194def shutdown(success):
195    pass
196
197def main(args=None):
198    pkgname = 'petsc4py'
199    parser = getoptionparser()
200    (options, args) = parser.parse_args(args)
201    setup_python(options)
202    setup_unittest(options)
203    package = import_package(options, pkgname)
204    print_banner(options, package)
205    testsuite = load_tests(options, args)
206    success = run_tests(options, testsuite)
207    if not success and options.failfast: abort()
208    if success and hasattr(sys, 'gettotalrefcount'):
209        test_refleaks(options, args)
210    shutdown(success)
211    return not success
212
213if __name__ == '__main__':
214    import sys
215    sys.dont_write_bytecode = True
216    sys.exit(main())
217