File: grouptest.py

package info (click to toggle)
python-escript 5.6-10
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 144,304 kB
  • sloc: python: 592,074; cpp: 136,909; ansic: 18,675; javascript: 9,411; xml: 3,384; sh: 738; makefile: 207
file content (326 lines) | stat: -rw-r--r-- 13,470 bytes parent folder | download | duplicates (3)
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
##############################################################################
#
# Copyright (c) 2003-2018 by The University of Queensland
# http://www.uq.edu.au
#
# Primary Business: Queensland, Australia
# Licensed under the Apache License, version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Development until 2012 by Earth Systems Science Computational Center (ESSCC)
# Development 2012-2013 by School of Earth Sciences
# Development from 2014 by Centre for Geoscience Computing (GeoComp)
#
##############################################################################

from __future__ import print_function, division
import os, re

__copyright__="""Copyright (c) 2003-2018 by The University of Queensland
http://www.uq.edu.au
Primary Business: Queensland, Australia"""
__license__="""Licensed under the Apache License, version 2.0
http://www.apache.org/licenses/LICENSE-2.0"""
__url__="https://launchpad.net/escript-finley"


IS_WINDOWS = (os.name == 'nt')

class GroupTest(object):
    _allfuncs = []
    repEnv = None

    def __init__(self, name, exec_cmd, evars, python_dir, working_dir, test_list, single_process_tests=[]):
        self.name=name
        self.python_dir=python_dir
        self.working_dir=working_dir
        self.test_list=test_list
        self.exec_cmd=exec_cmd
        self.evars=evars
        self.mkdirs=[]
        self.single_process_tests=single_process_tests
        self._allfuncs.append(name)
        if IS_WINDOWS:
            self.exec_cmd = self.setWinEnvs(self.exec_cmd)
            self.python_dir = self.setWinEnvs(self.python_dir)
            self.working_dir = self.setWinEnvs(self.working_dir)
            self.evars = [(e[0], self.setWinEnvs(e[1])) for e in self.evars]
            rep = re.compile(r'/')
            self.test_list = [rep.sub('\\'+os.sep, t) for t in self.test_list]
            rep = re.compile(r':')
            self.python_dir = rep.sub(os.pathsep, self.python_dir)
        
    def makeDir(self,dirname):
        if IS_WINDOWS:
            dirname = self.setWinEnvs(dirname)
        self.mkdirs.append(dirname)

    def setWinEnvs(self,path):
        if self.repEnv is None:
            self.repEnv = re.compile(r'[$]([a-zA-Z_][a-zA-Z0-9_]*)')
        return self.repEnv.sub(r'%\1%', path)

    #stdloc means that the files are in standard locations so don't use prefix
    def makeHeader(build_platform, prefix, stdloc):
        if IS_WINDOWS:
            return GroupTest._makeHeaderPy(build_platform, prefix, stdloc)
        res="""#!/bin/sh
#############################################
# This file is autogenerated by scons.
# It will be regenerated each time scons is run
#############################################

failed () {
    echo "Execution failed for $@"
    exit 1
}

if [ $# -lt 2 ]; then
    echo "Usage: $0 build_dir wrapper_options [groupname]"
    echo Runs all or a group of unit tests. Options must be a single string.
    exit 2
fi

case "$1" in
   /*) ;;
   *) echo "build_dir needs to be an absolute path"; exit 4;;
esac

NUMPROCS=1
NUMNODES=1
while getopts ':n:p:' option $2
do
    case "$option" in
        "n")  NUMNODES=$OPTARG ;;
        "p")  NUMPROCS=$OPTARG ;;
    esac
done
MPIPROD=$(($NUMPROCS * $NUMNODES))
"""
        res+="BUILD_DIR=$1"+"/"+build_platform
        res+="\nif [ ! -d $BUILD_DIR ]\nthen\n    echo Can not find build directory $BUILD_DIR\n     exit 2\nfi\n" 
        if stdloc:
            res+="""MPITYPE=`run-escript -c | grep mpi=`
export OLD_PYTHON=$PYTHONPATH
BATCH_ROOT=`pwd`
BINRUNNER="run-escript -b $2"
PYTHONRUNNER="run-escript $2"
PYTHONTESTRUNNER="run-escript $2 $BATCH_ROOT/tools/testrunner.py"
"""
        else:
            res+="""MPITYPE=`{0}/bin/run-escript -c | grep mpi=`
BATCH_ROOT=`pwd`            
export LD_LIBRARY_PATH={0}/lib:$LD_LIBRARY_PATH
export OLD_PYTHON={0}:$PYTHONPATH
BINRUNNER="{0}/bin/run-escript -b $2"
PYTHONRUNNER="{0}/bin/run-escript $2"
PYTHONTESTRUNNER="{0}/bin/run-escript $2 {0}/tools/testrunner.py"
""".format(prefix)
        if build_platform=='darwin':
            res+="export DYLD_LIBRARY_PATH=$LD_LIBRARY_PATH:$DYLD_LIBRARY_PATH\n"
        return res
    makeHeader=staticmethod(makeHeader)

    def makeString(self):
        if IS_WINDOWS:
            return self._makeStringPy()
        res="%s () {\n"%self.name
        tt="\t"
        build_dir = self.working_dir.replace("$BATCH_ROOT", "$BUILD_DIR")
        for d in self.mkdirs:
            res=res+tt+"if [ ! -d "+str(d)+" ]\n"+tt+"then\n"+tt+"\tmkdir -p "+str(d)+"\n"+tt+"fi\n"
        for v in self.evars:
            res=res+tt+"export "+str(v[0])+"="+str(v[1])+"\n"
        res=res+tt+"if [ ! -d "+str(self.working_dir)+" ]\n"+tt+"then\n"+tt+"\tmkdir -p "+str(self.working_dir)+"\n"+tt+"fi\n"
        if len(self.python_dir)>0:
            res=res+tt+"export PYTHONPATH="+self.python_dir+":$OLD_PYTHON"+"\n"+tt+"cd "+self.working_dir+"\n"
        else:
            res=res+tt+"export PYTHONPATH=$OLD_PYTHON"+"\n"+tt+"cd "+self.working_dir+"\n"
        if len(self.single_process_tests) > 0:
            res+=tt+"if [ $MPIPROD -le 1 ]; then\n"
            #res+=tt+'if [ "$MPITYPE" == "mpi=none" ]; then\n'
            tt+="\t"
            for t in self.single_process_tests:
                res=res+tt+"echo Starting "+t+"\n"+tt+"date\n"
                skipoutputfile = ""
                failoutputfile = ""
                cmd = self.exec_cmd
                exit_on_failure = " || failed %s"%t
                if "examples" not in build_dir and "PYTHONRUNNER" in self.exec_cmd \
                        and "/tools/" not in build_dir:
                    skipoutputfile = " -skipfile={0}/{1}".format(build_dir, t.replace(".py", ".skipped"))
                    failoutputfile = " -failfile={0}/{1}".format(build_dir, t.replace(".py", ".failed"))
                    cmd = cmd.replace("PYTHONRUNNER", "PYTHONTESTRUNNER")
                res += "".join([tt, cmd, t, failoutputfile, skipoutputfile, exit_on_failure, "\n"])
                res += tt+"echo Completed "+t+"\n"
            tt="\t"
            res+=tt+"fi\n"
        for t in self.test_list:
            res=res+tt+"echo Starting "+t+"\n"+tt+"date\n"
            skipoutputfile = ""
            failoutputfile = ""
            cmd = self.exec_cmd
            exit_on_failure = " || failed %s"%t
            if "examples" not in build_dir and "PYTHONRUNNER" in self.exec_cmd \
                    and "/tools/" not in build_dir:
                skipoutputfile = " -skipfile={0}/{1}".format(build_dir, t.replace(".py", ".skipped"))
                failoutputfile = " -failfile={0}/{1}".format(build_dir, t.replace(".py", ".failed"))
                cmd = cmd.replace("PYTHONRUNNER", "PYTHONTESTRUNNER")
            res += "".join([tt, cmd, t, failoutputfile, skipoutputfile, exit_on_failure, "\n"])
            res += tt+"echo Completed "+t+"\n"
        res=res+"}\n"
        return res
    
    def makeFooter(self):
        if IS_WINDOWS:
            return self._makeFooterPy()
        res="if [ $# -gt 2 ]; then\n\teval $3\nelse\n\t"
        res+="\n\t".join(self._allfuncs)
        res+="\nfi\nfind $BUILD_DIR -name '*.failed' | xargs cat; find $BUILD_DIR -name '*.failed' | xargs cat | diff -q - /dev/null >/dev/null\n"
        return res

    @staticmethod
    def _makeHeaderPy(build_platform, prefix, stdloc):
        res='''#!/usr/bin/env python
#############################################
# This file is autogenerated by scons.
# It will be regenerated each time scons is run
#############################################

import datetime, getopt, os, re, subprocess, sys

def failed(msg):
    print('Execution failed for {}'.format(msg))
    exit(1)

def now():
    return datetime.datetime.now().strftime('%%Y-%%m-%%d %%H:%%M:%%S')

opts, args = getopt.getopt(sys.argv[1:], ':np:')

if len(args) < 2:
    print('Usage: {} build_dir wrapper_options [groupname]'.format(sys.argv[0]))
    print('Runs all or a group of unit tests. Options must be a single string.')
    exit(2)

if os.name == 'nt':
    vols = subprocess.Popen('mountvol', stdout=subprocess.PIPE).stdout.read().decode(sys.stdout.encoding)
    path_prefix = re.findall(r'[A-Z]+:\\\\', vols, re.MULTILINE)
else:
    path_prefix = [os.sep]

path_prefix_match = False
for p in path_prefix:
    if sys.argv[1].startswith(p):
        path_prefix_match = True
if not path_prefix_match:
    print('build_dir needs to be an absolute path')
    exit(4)

build_platform = '%(bldplat)s'
prefix = r'%(prefix)s'
prefix_bin = r'%(prefix_bin)s'
prefix_lib = r'%(prefix_lib)s'

NUMPROCS = 1
NUMNODES = 1
for opt, arg in opts:
    if opt == '-n':
        NUMNODES = int(arg)
    elif opt == '-p':
        NUMPROCS = int(arg)
    else:
        print("unknown option")
        exit(5)
MPIPROD = NUMPROCS * NUMNODES
build_dir = os.path.join(args[0], build_platform)
if not os.path.isdir(build_dir):
    print("Can not find build directory "+build_dir)
    exit(2)

os.environ['BUILD_DIR'] = build_dir
os.environ['BATCH_ROOT'] = os.getcwd()
run_args = '' if len(args) < 2 else args[1]
os.environ['BINRUNNER'] = os.path.join(prefix_bin, 'run-escript -b '+run_args)
os.environ['PYTHONRUNNER'] = os.path.join(prefix_bin, 'run-escript '+run_args)

if len(prefix) > 0:
    os.environ['PYTHONTESTRUNNER'] = os.path.join(prefix_bin, 'run-escript '+run_args)+' '+os.path.join(
        prefix, 'tools', 'testrunner.py')
    os.environ['LD_LIBRARY_PATH'] = prefix_lib+os.pathsep+os.environ.get('LD_LIBRARY_PATH', '')
    os.environ['OLD_PYTHON'] = prefix+os.pathsep+os.environ.get('PYTHONPATH', '')
else:
    os.environ['PYTHONTESTRUNNER'] = 'run-escript '+run_args+' '+os.path.join(os.getcwd(), 'tools', 'testrunner.py')
    os.environ['OLD_PYTHON'] = os.environ.get('PYTHONPATH', '')

'''
        if stdloc:
            prefix_bin = ''
            prefix_lib = ''
        else:
            prefix_bin = os.path.join(prefix, 'bin')
            prefix_lib = os.path.join(prefix, 'lib')
        return res % { 'bldplat': build_platform, 'prefix': prefix, 'prefix_bin': prefix_bin,
            'prefix_lib': prefix_lib }

    def _makeStringPy(self):
        res = 'def %s():\n'%self.name
        tt = '    '
        build_dir = self.working_dir.replace('BATCH_ROOT', 'BUILD_DIR')
        for d in self.mkdirs:
            res += tt+"if not os.path.isdir(os.path.expandvars(r'"+d+"')):\n"+tt+tt+ \
                "os.makedirs(os.path.expandvars(r'"+d+"'))\n"
        for v in self.evars:
            res += tt+"os.environ['"+str(v[0])+"'] = os.path.expandvars(r'"+str(v[1])+"')\n"
        res += tt+"if not os.path.isdir(os.path.expandvars(r'"+self.working_dir+"')):\n"+tt+tt+ \
            "os.makedirs(os.path.expandvars(r'"+self.working_dir+"'))\n"
        if len(self.python_dir) > 0:
            res += tt+"os.environ['PYTHONPATH'] = os.path.expandvars(r'"+self.python_dir+"')+os.pathsep+os.environ.get('OLD_PYTHON', '')\n"
        else:
            res += tt+"os.environ['PYTHONPATH'] = os.environ.get('OLD_PYTHON', '')\n"
        res += tt+"os.chdir(os.path.expandvars(r'"+self.working_dir+"'))\n"
        if len(self.single_process_tests) > 0:
            res += tt+'if MPIPROD <= 1:\n'
            tt += '    '
            for t in self.single_process_tests:
                res += tt+"print('Starting "+t+"\\n'+now())\n"+tt+"sys.stdout.flush()\n"
                skipoutputfile = ''
                failoutputfile = ''
                cmd = self.exec_cmd
                if 'examples' not in build_dir and 'PYTHONRUNNER' in self.exec_cmd \
                        and '/tools/' not in build_dir:
                    skipoutputfile = ' -skipfile={0}{1}'.format(build_dir, t.replace('.py', '.skipped'))
                    failoutputfile = ' -failfile={0}{1}'.format(build_dir, t.replace('.py', '.failed'))
                    cmd = cmd.replace('PYTHONRUNNER', 'PYTHONTESTRUNNER')
                res += tt+"if subprocess.call(r'"+cmd+t+failoutputfile+skipoutputfile+"', shell=True) != 0:\n"
                res += tt+tt+"failed(r'"+t+"')\n"
                res += tt+"print('Completed "+t+"')\n"
            tt = '    '
        for t in self.test_list:
            res += tt+"print('Starting "+t+"\\n'+now())\n"+tt+"sys.stdout.flush()\n"
            skipoutputfile = ''
            failoutputfile = ''
            cmd = self.exec_cmd
            if 'examples' not in build_dir and 'PYTHONRUNNER' in self.exec_cmd \
                    and '/tools/' not in build_dir:
                skipoutputfile = ' -skipfile={0}{1}'.format(build_dir, t.replace('.py', '.skipped'))
                failoutputfile = ' -failfile={0}{1}'.format(build_dir, t.replace('.py', '.failed'))
                cmd = cmd.replace('PYTHONRUNNER', 'PYTHONTESTRUNNER')
            res += tt+"if subprocess.call(r'"+cmd+t+failoutputfile+skipoutputfile+"', shell=True) != 0:\n"
            res += tt+tt+"failed(r'"+t+"')\n"
            res += tt+"print('Completed "+t+"')\n"
        res += '\n'
        return res

    def _makeFooterPy(self):
        res = "if len(args) > 2:\n    globals()[args[2]]()\nelse:\n"
        for f in self._allfuncs:
            res += '    '+f+'()\n'
        #TODO:
        #res+="\nfind $BUILD_DIR -name '*.failed' | xargs cat; find $BUILD_DIR -name '*.failed' | xargs cat | diff -q - /dev/null >/dev/null\n"
        return res
        #try this
        #for root, dirs, files in os.walk('.'):
        #    for f in files:
        #        if f.endswith('.py'):
        #            print(os.path.join(root, f))