File: runtests.py

package info (click to toggle)
slepc4py 3.24.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,760 kB
  • sloc: python: 6,916; makefile: 129; ansic: 98; sh: 46
file content (246 lines) | stat: -rw-r--r-- 7,658 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import os
import sys
import optparse
import unittest

__unittest = True

components = [
    'PETSc',
    'SLEPc',
]


def getoptionparser():
    parser = optparse.OptionParser()

    parser.add_option("-q", "--quiet",
                      action="store_const", const=0, dest="verbose", default=1,
                      help="do not print status messages to stdout")
    parser.add_option("-v", "--verbose",
                      action="store_const", const=2, dest="verbose", default=1,
                      help="print status messages to stdout")
    parser.add_option("-i", "--include", type="string",
                      action="append",  dest="include", default=[],
                      help="include tests matching PATTERN", metavar="PATTERN")
    parser.add_option("-e", "--exclude", type="string",
                      action="append", dest="exclude", default=[],
                      help="exclude tests matching PATTERN", metavar="PATTERN")
    parser.add_option("-k", "--pattern", type="string",
                      action="append", dest="patterns", default=[],
                      help="only run tests which match the given substring")
    parser.add_option("-f", "--failfast",
                      action="store_true", dest="failfast", default=False,
                      help="Stop on first failure")
    parser.add_option("--no-builddir",
                      action="store_false", dest="builddir", default=True,
                      help="disable testing from build directory")
    parser.add_option("--path", type="string",
                      action="append", dest="path", default=[],
                      help="prepend PATH to sys.path", metavar="PATH")
    parser.add_option("--arch", type="string",
                      action="store", dest="arch", default=None,
                      help="use PETSC_ARCH",
                      metavar="PETSC_ARCH")
    parser.add_option("-s","--summary",
                      action="store_true", dest="summary", default=0,
                      help="print PETSc log summary")
    parser.add_option("--no-memdebug",
                      action="store_false", dest="memdebug", default=True,
                      help="Do not use PETSc memory debugging")
    return parser


def getbuilddir():
    try:
        try:
            from setuptools.dist import Distribution
        except ImportError:
            from distutils.dist import Distribution
        try:
            from setuptools.command.build import build
        except ImportError:
            from distutils.command.build import build
        cmd_obj = build(Distribution())
        cmd_obj.finalize_options()
        return cmd_obj.build_platlib
    except Exception:
        return None


def getprocessorinfo():
    try:
        name = os.uname()[1]
    except:
        import platform
        name = platform.uname()[1]
    from petsc4py.PETSc import COMM_WORLD
    rank = COMM_WORLD.getRank()
    return (rank, name)


def getlibraryinfo(name):
    modname = "%s4py.%s" % (name.lower(), name)
    module = __import__(modname, fromlist=[name])
    (major, minor, micro), devel = module.Sys.getVersion(devel=True)
    r = not devel
    if r: release = 'release'
    else: release = 'development'
    arch = module.__arch__
    return (
        "%s %d.%d.%d %s (conf: '%s')" %
        (name, major, minor, micro, release, arch)
    )


def getpythoninfo():
    x, y, z = sys.version_info[:3]
    return ("Python %d.%d.%d (%s)" % (x, y, z, sys.executable))


def getpackageinfo(pkg):
    try:
        pkg = __import__(pkg)
    except ImportError:
        return None
    name = pkg.__name__
    version = pkg.__version__
    path = pkg.__path__[0]
    return ("%s %s (%s)" % (name, version, path))


def setup_python(options):
    rootdir = os.path.dirname(os.path.dirname(__file__))
    builddir = os.path.join(rootdir, getbuilddir())
    if options.builddir and os.path.exists(builddir):
        sys.path.insert(0, builddir)
    if options.path:
        path = options.path[:]
        path.reverse()
        for p in path:
            sys.path.insert(0, p)


def setup_unittest(options):
    from unittest import TestSuite
    try:
        from unittest.runner import _WritelnDecorator
    except ImportError:
        from unittest import _WritelnDecorator
    #
    writeln_orig = _WritelnDecorator.writeln
    def writeln(self, message=''):
        try: self.stream.flush()
        except: pass
        writeln_orig(self, message)
        try: self.stream.flush()
        except: pass
    _WritelnDecorator.writeln = writeln


def import_package(options, pkgname):
    args = [sys.argv[0]]
    if options.memdebug:
        args.append('-malloc_debug')
        args.append('-malloc_dump')
    if options.summary:
        args.append('-log_view')
    package = __import__(pkgname)
    package.init(args, arch=options.arch)


def print_banner(options):
    r, n = getprocessorinfo()
    prefix = "[%d@%s]" % (r, n)

    def writeln(message='', endl='\n'):
        if message is None:
            return
        from petsc4py.PETSc import Sys
        message = "%s %s" % (prefix, message)
        Sys.syncPrint(message, endl=endl, flush=True)

    if options.verbose:
        writeln(getpythoninfo())
        writeln(getpackageinfo('numpy'))
        for entry in components:
            writeln(getlibraryinfo(entry))
            writeln(getpackageinfo('%s4py' % entry.lower()))


def load_tests(options, args):
    from glob import glob
    import re
    testsuitedir = os.path.dirname(__file__)
    sys.path.insert(0, testsuitedir)
    pattern = 'test_*.py'
    wildcard = os.path.join(testsuitedir, pattern)
    testfiles = glob(wildcard)
    testfiles.sort()
    testsuite = unittest.TestSuite()
    testloader = unittest.TestLoader()
    if options.patterns:
        testloader.testNamePatterns = [ # novermin
            ('*%s*' % p) if ('*' not in p) else p
            for p in options.patterns
        ]
    include = exclude = None
    if options.include:
        include = re.compile('|'.join(options.include)).search
    if options.exclude:
        exclude = re.compile('|'.join(options.exclude)).search
    for testfile in testfiles:
        filename = os.path.basename(testfile)
        testname = os.path.splitext(filename)[0]
        if ((exclude and exclude(testname)) or
            (include and not include(testname))):
            continue
        module = __import__(testname)
        for arg in args:
            try:
                cases = testloader.loadTestsFromNames((arg,), module)
                testsuite.addTests(cases)
            except AttributeError:
                pass
        if not args:
            cases = testloader.loadTestsFromModule(module)
            testsuite.addTests(cases)
    return testsuite


def run_tests(options, testsuite, runner=None):
    if runner is None:
        runner = unittest.TextTestRunner(verbosity=options.verbose)
        runner.failfast = options.failfast
    result = runner.run(testsuite)
    return result.wasSuccessful()



def abort(code=1):
    os.abort()


def shutdown(success):
    pass


def main(args=None):
    pkgname = '%s4py' % components[-1].lower()
    parser = getoptionparser()
    (options, args) = parser.parse_args(args)
    setup_python(options)
    setup_unittest(options)
    import_package(options, pkgname)
    print_banner(options)
    testsuite = load_tests(options, args)
    success = run_tests(options, testsuite)
    if not success and options.failfast: abort()
    shutdown(success)
    return not success


if __name__ == '__main__':
    import sys
    sys.dont_write_bytecode = True
    sys.exit(main())