summaryrefslogtreecommitdiffstats
path: root/etc/TestCmd.py
blob: 17d520bd0e31c898abffad0f7ff08567475d59f7 (plain)
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
"""
TestCmd.py:  a testing framework for commands and scripts.

The TestCmd module provides a framework for portable automated testing
of executable commands and scripts (in any language, not just Python),
especially commands and scripts that require file system interaction.

In addition to running tests and evaluating conditions, the TestCmd module
manages and cleans up one or more temporary workspace directories, and
provides methods for creating files and directories in those workspace
directories from in-line data, here-documents), allowing tests to be
completely self-contained.

A TestCmd environment object is created via the usual invocation:

    test = TestCmd()

The TestCmd module provides pass_test(), fail_test(), and no_result()
unbound methods that report test results for use with the Aegis change
management system.  These methods terminate the test immediately,
reporting PASSED, FAILED, or NO RESULT respectively, and exiting with
status 0 (success), 1 or 2 respectively.  This allows for a distinction
between an actual failed test and a test that could not be properly
evaluated because of an external condition (such as a full file system
or incorrect permissions).
"""

# Copyright 2000 Steven Knight
# This module is free software, and you may redistribute it and/or modify
# it under the same terms as Python itself, so long as this copyright message
# and disclaimer are retained in their original form.
#
# IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
# SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
# THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.
#
# THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
# AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
# SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

__author__ = "Steven Knight <knight@baldmt.com>"
__revision__ = "TestCmd.py 0.D002 2001/08/31 14:56:12 software"
__version__ = "0.02"

import os
import os.path
import popen2
import re
import shutil
import stat
import string
import sys
import tempfile
import traceback
import types

try:
    from UserString import UserString
except ImportError:
    class UserString:
        pass

if hasattr(types, 'UnicodeType'):
    def is_String(e):
        return type(e) is types.StringType \
            or type(e) is types.UnicodeType \
            or isinstance(e, UserString)
else:
    def is_String(e):
        return type(e) is types.StringType or isinstance(e, UserString)

tempfile.template = 'testcmd.'

_Cleanup = []

def _clean():
    global _Cleanup
    list = _Cleanup[:]
    _Cleanup = []
    list.reverse()
    for test in list:
	test.cleanup()

sys.exitfunc = _clean

def _caller(tblist, skip):
    string = ""
    arr = []
    for file, line, name, text in tblist:
	if file[-10:] == "TestCmd.py":
		break
	arr = [(file, line, name, text)] + arr
    atfrom = "at"
    for file, line, name, text in arr[skip:]:
	if name == "?":
	    name = ""
	else:
	    name = " (" + name + ")"
	string = string + ("%s line %d of %s%s\n" % (atfrom, line, file, name))
	atfrom = "\tfrom"
    return string

def fail_test(self = None, condition = 1, function = None, skip = 0):
    """Cause the test to fail.

    By default, the fail_test() method reports that the test FAILED
    and exits with a status of 1.  If a condition argument is supplied,
    the test fails only if the condition is true.
    """
    if not condition:
	return
    if not function is None:
	function()
    of = ""
    desc = ""
    sep = " "
    if not self is None:
	if self.program:
	    of = " of " + self.program
	    sep = "\n\t"
	if self.description:
	    desc = " [" + self.description + "]"
	    sep = "\n\t"

    at = _caller(traceback.extract_stack(), skip)
    sys.stderr.write("FAILED test" + of + desc + sep + at)

    sys.exit(1)

def no_result(self = None, condition = 1, function = None, skip = 0):
    """Causes a test to exit with no valid result.

    By default, the no_result() method reports NO RESULT for the test
    and exits with a status of 2.  If a condition argument is supplied,
    the test fails only if the condition is true.
    """
    if not condition:
	return
    if not function is None:
	function()
    of = ""
    desc = ""
    sep = " "
    if not self is None:
	if self.program:
	    of = " of " + self.program
	    sep = "\n\t"
	if self.description:
	    desc = " [" + self.description + "]"
	    sep = "\n\t"

    at = _caller(traceback.extract_stack(), skip)
    sys.stderr.write("NO RESULT for test" + of + desc + sep + at)

    sys.exit(2)

def pass_test(self = None, condition = 1, function = None):
    """Causes a test to pass.

    By default, the pass_test() method reports PASSED for the test
    and exits with a status of 0.  If a condition argument is supplied,
    the test passes only if the condition is true.
    """
    if not condition:
	return
    if not function is None:
	function()
    sys.stderr.write("PASSED\n")
    sys.exit(0)

def match_exact(lines = None, matches = None):
    """
    """
    if not type(lines) is types.ListType:
	lines = string.split(lines, "\n")
    if not type(matches) is types.ListType:
	matches = string.split(matches, "\n")
    if len(lines) != len(matches):
	return
    for i in range(len(lines)):
	if lines[i] != matches[i]:
	    return
    return 1

def match_re(lines = None, res = None):
    """
    """
    if not type(lines) is types.ListType:
	lines = string.split(lines, "\n")
    if not type(res) is types.ListType:
	res = string.split(res, "\n")
    if len(lines) != len(res):
	return
    for i in range(len(lines)):
	if not re.compile("^" + res[i] + "$").search(lines[i]):
	    return
    return 1

def match_re_dotall(lines = None, res = None):
    """
    """
    if not type(lines) is type(""):
        lines = string.join(lines, "\n")
    if not type(res) is type(""):
        res = string.join(res, "\n")
    if re.compile("^" + res + "$", re.DOTALL).match(lines):
        return 1

if sys.platform == 'win32':

    def where_is(file, path=None, pathext=None):
        if path is None:
            path = os.environ['PATH']
        if is_String(path):
            path = string.split(path, os.pathsep)
        if pathext is None:
            pathext = os.environ['PATHEXT']
        if is_String(pathext):
            pathext = string.split(pathext, os.pathsep)
        for ext in pathext:
            if string.lower(ext) == string.lower(file[-len(ext):]):
                pathext = ['']
                break
        for dir in path:
            f = os.path.join(dir, file)
            for ext in pathext:
                fext = f + ext
                if os.path.isfile(fext):
                    return fext
        return None

else:

    def where_is(file, path=None, pathext=None):
        if path is None:
            path = os.environ['PATH']
        if is_String(path):
            path = string.split(path, os.pathsep)
        for dir in path:
            f = os.path.join(dir, file)
            if os.path.isfile(f):
                try:
                    st = os.stat(f)
                except:
                    continue
                if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
                    return f
        return None

class TestCmd:
    """Class TestCmd
    """

    def __init__(self, description = None,
			program = None,
			interpreter = None,
			workdir = None,
			subdir = None,
			verbose = 0,
			match = None):
	self._cwd = os.getcwd()
	self.description_set(description)
	self.program_set(program)
	self.interpreter_set(interpreter)
	self.verbose_set(verbose)
	if not match is None:
	    self.match_func = match
	else:
	    self.match_func = match_re
	self._dirlist = []
	self._preserve = {'pass_test': 0, 'fail_test': 0, 'no_result': 0}
	if os.environ.has_key('PRESERVE') and not os.environ['PRESERVE'] is '':
	    self._preserve['pass_test'] = os.environ['PRESERVE']
	    self._preserve['fail_test'] = os.environ['PRESERVE']
	    self._preserve['no_result'] = os.environ['PRESERVE']
	else:
	    try:
		self._preserve['pass_test'] = os.environ['PRESERVE_PASS']
	    except KeyError:
		pass
	    try:
		self._preserve['fail_test'] = os.environ['PRESERVE_FAIL']
	    except KeyError:
		pass
	    try:
		self._preserve['no_result'] = os.environ['PRESERVE_NO_RESULT']
	    except KeyError:
		pass
	self._stdout = []
	self._stderr = []
	self.status = None
	self.condition = 'no_result'
	self.workdir_set(workdir)
	self.subdir(subdir)

    def __del__(self):
	self.cleanup()

    def __repr__(self):
	return "%x" % id(self)

    def cleanup(self, condition = None):
	"""Removes any temporary working directories for the specified
	TestCmd environment.  If the environment variable PRESERVE was
	set when the TestCmd environment was created, temporary working
	directories are not removed.  If any of the environment variables
	PRESERVE_PASS, PRESERVE_FAIL, or PRESERVE_NO_RESULT were set
	when the TestCmd environment was created, then temporary working
	directories are not removed if the test passed, failed, or had
	no result, respectively.  Temporary working directories are also
	preserved for conditions specified via the preserve method.

	Typically, this method is not called directly, but is used when
	the script exits to clean up temporary working directories as
	appropriate for the exit status.
	"""
	if not self._dirlist:
	    return
	if condition is None:
	    condition = self.condition
	#print "cleanup(" + condition + "):  ", self._preserve
	if self._preserve[condition]:
	    return
	os.chdir(self._cwd)
	self.workdir = None
	list = self._dirlist[:]
	self._dirlist = []
	list.reverse()
	for dir in list:
	    self.writable(dir, 1)
	    shutil.rmtree(dir, ignore_errors = 1)
	try:
	    global _Cleanup
	    _Cleanup.remove(self)
	except (AttributeError, ValueError):
	    pass

    def description_set(self, description):
	"""Set the description of the functionality being tested.
	"""
	self.description = description

#    def diff(self):
#	"""Diff two arrays.
#	"""

    def fail_test(self, condition = 1, function = None, skip = 0):
	"""Cause the test to fail.
	"""
	if not condition:
	    return
	self.condition = 'fail_test'
	fail_test(self = self,
		  condition = condition,
		  function = function,
		  skip = skip)

    def interpreter_set(self, interpreter):
	"""Set the program to be used to interpret the program
	under test as a script.
	"""
	self.interpreter = interpreter

    def match(self, lines, matches):
	"""Compare actual and expected file contents.
	"""
	return self.match_func(lines, matches)

    def match_exact(self, lines, matches):
	"""Compare actual and expected file contents.
	"""
	return match_exact(lines, matches)

    def match_re(self, lines, res):
	"""Compare actual and expected file contents.
	"""
	return match_re(lines, res)

    def no_result(self, condition = 1, function = None, skip = 0):
	"""Report that the test could not be run.
	"""
	if not condition:
	    return
	self.condition = 'no_result'
	no_result(self = self,
		  condition = condition,
		  function = function,
		  skip = skip)

    def pass_test(self, condition = 1, function = None):
	"""Cause the test to pass.
	"""
	if not condition:
	    return
	self.condition = 'pass_test'
	pass_test(self = self, condition = condition, function = function)

    def preserve(self, *conditions):
	"""Arrange for the temporary working directories for the
	specified TestCmd environment to be preserved for one or more
	conditions.  If no conditions are specified, arranges for
	the temporary working directories to be preserved for all
	conditions.
	"""
	if conditions is ():
	    conditions = ('pass_test', 'fail_test', 'no_result')
	for cond in conditions:
	    self._preserve[cond] = 1

    def program_set(self, program):
	"""Set the executable program or script to be tested.
	"""
	if program and not os.path.isabs(program):
	    program = os.path.join(self._cwd, program)
	self.program = program

    def read(self, file, mode = 'rb'):
	"""Reads and returns the contents of the specified file name.
	The file name may be a list, in which case the elements are
	concatenated with the os.path.join() method.  The file is
	assumed to be under the temporary working directory unless it
	is an absolute path name.  The I/O mode for the file may
	be specified; it must begin with an 'r'.  The default is
	'rb' (binary read).
	"""
	if type(file) is types.ListType:
	    file = apply(os.path.join, tuple(file))
	if not os.path.isabs(file):
	    file = os.path.join(self.workdir, file)
	if mode[0] != 'r':
	    raise ValueError, "mode must begin with 'r'"
	return open(file, mode).read()

    def run(self, program = None,
		  interpreter = None,
		  arguments = None,
		  chdir = None,
		  stdin = None):
	"""Runs a test of the program or script for the test
	environment.  Standard output and error output are saved for
	future retrieval via the stdout() and stderr() methods.
	"""
	if chdir:
	    oldcwd = os.getcwd()
	    if not os.path.isabs(chdir):
		chdir = os.path.join(self.workpath(chdir))
	    if self.verbose:
		sys.stderr.write("chdir(" + chdir + ")\n")
	    os.chdir(chdir)
	cmd = None
	if program:
	    if not os.path.isabs(program):
		program = os.path.join(self._cwd, program)
	    cmd = program
	    if interpreter:
		cmd = interpreter + " " + cmd
	else:
	    cmd = self.program
	    if self.interpreter:
		cmd =  self.interpreter + " " + cmd
	if arguments:
	    cmd = cmd + " " + arguments
	if self.verbose:
	    sys.stderr.write(cmd + "\n")
	try:
            p = popen2.Popen3(cmd, 1)
	except AttributeError:
	    (tochild, fromchild, childerr) = os.popen3(cmd)
	    if stdin:
		if type(stdin) is types.ListType:
		    for line in stdin:
			tochild.write(line)
		else:
		    tochild.write(stdin)
	    tochild.close()
	    self._stdout.append(fromchild.read())
	    self._stderr.append(childerr.read())
	    fromchild.close()
            self.status = childerr.close()
            if not self.status:
                self.status = 0
	except:
	    raise
	else:
	    if stdin:
		if type(stdin) is types.ListType:
		    for line in stdin:
			p.tochild.write(line)
		else:
		    p.tochild.write(stdin)
	    p.tochild.close()
	    self._stdout.append(p.fromchild.read())
	    self._stderr.append(p.childerr.read())
	    self.status = p.wait()
	if chdir:
	    os.chdir(oldcwd)

    def stderr(self, run = None):
	"""Returns the error output from the specified run number.
	If there is no specified run number, then returns the error
	output of the last run.  If the run number is less than zero,
	then returns the error output from that many runs back from the
	current run.
	"""
	if not run:
	    run = len(self._stderr)
	elif run < 0:
	    run = len(self._stderr) + run
	run = run - 1
	if run >= len(self._stderr) or run < 0:
	    return ''
	else:
	    return self._stderr[run]

    def stdout(self, run = None):
	"""Returns the standard output from the specified run number.
	If there is no specified run number, then returns the standard
	output of the last run.  If the run number is less than zero,
	then returns the standard output from that many runs back from
	the current run.
	"""
	if not run:
	    run = len(self._stdout)
	elif run < 0:
	    run = len(self._stdout) + run
	run = run - 1
	if run >= len(self._stdout) or run < 0:
	    return ''
	else:
	    return self._stdout[run]

    def subdir(self, *subdirs):
	"""Create new subdirectories under the temporary working
	directory, one for each argument.  An argument may be a list,
	in which case the list elements are concatenated using the
	os.path.join() method.  Subdirectories multiple levels deep
	must be created using a separate argument for each level:

		test.subdir('sub', ['sub', 'dir'], ['sub', 'dir', 'ectory'])

	Returns the number of subdirectories actually created.
	"""
	count = 0
	for sub in subdirs:
	    if sub is None:
		continue
	    if type(sub) is types.ListType:
		sub = apply(os.path.join, tuple(sub))
	    new = os.path.join(self.workdir, sub)
	    try:
		os.mkdir(new)
	    except:
		pass
	    else:
		count = count + 1
	return count

    def unlink (self, file):
        """Unlinks the specified file name.
	The file name may be a list, in which case the elements are
	concatenated with the os.path.join() method.  The file is
	assumed to be under the temporary working directory unless it
	is an absolute path name.
	"""
	if type(file) is types.ListType:
	    file = apply(os.path.join, tuple(file))
	if not os.path.isabs(file):
	    file = os.path.join(self.workdir, file)
        os.unlink(file)
        

    def verbose_set(self, verbose):
	"""Set the verbose level.
	"""
	self.verbose = verbose

    def where_is(self, file, path=None, pathext=None):
        """Find an executable file.
        """
	if type(file) is types.ListType:
	    file = apply(os.path.join, tuple(file))
	if not os.path.isabs(file):
	    file = where_is(file, path, pathext)
        return file

    def workdir_set(self, path):
	"""Creates a temporary working directory with the specified
	path name.  If the path is a null string (''), a unique
	directory name is created.
	"""
	if (path != None):
	    if path == '':
		path = tempfile.mktemp()
	    if path != None:
		os.mkdir(path)
	    self._dirlist.append(path)
	    global _Cleanup
	    try:
		_Cleanup.index(self)
	    except ValueError:
		_Cleanup.append(self)
	    # We'd like to set self.workdir like this:
	    #	self.workdir = path
	    # But symlinks in the path will report things
	    # differently from os.getcwd(), so chdir there
	    # and back to fetch the canonical path.
	    cwd = os.getcwd()
	    os.chdir(path)
	    self.workdir = os.getcwd()
	    os.chdir(cwd)
	else:
	    self.workdir = None

    def workpath(self, *args):
	"""Returns the absolute path name to a subdirectory or file
	within the current temporary working directory.  Concatenates
	the temporary working directory name with the specified
	arguments using the os.path.join() method.
	"""
	return apply(os.path.join, (self.workdir,) + tuple(args))

    def writable(self, top, write):
	"""Make the specified directory tree writable (write == 1)
	or not (write == None).
	"""

	def _walk_chmod(arg, dirname, names):
	    st = os.stat(dirname)
	    os.chmod(dirname, arg(st[stat.ST_MODE]))
	    for name in names:
		n = os.path.join(dirname, name)
		st = os.stat(n)
		os.chmod(n, arg(st[stat.ST_MODE]))

	def _mode_writable(mode):
	    return stat.S_IMODE(mode|0200)

	def _mode_non_writable(mode):
	    return stat.S_IMODE(mode&~0200)

	if write:
	    f = _mode_writable
	else:
	    f = _mode_non_writable
	try:
	    os.path.walk(top, _walk_chmod, f)
	except:
	    pass # ignore any problems changing modes
	    
    def write(self, file, content, mode = 'wb'):
	"""Writes the specified content text (second argument) to the
	specified file name (first argument).  The file name may be
	a list, in which case the elements are concatenated with the
	os.path.join() method.	The file is created under the temporary
	working directory.  Any subdirectories in the path must already
	exist.  The I/O mode for the file may be specified; it must
	begin with a 'w'.  The default is 'wb' (binary write).
	"""
	if type(file) is types.ListType:
	    file = apply(os.path.join, tuple(file))
	if not os.path.isabs(file):
	    file = os.path.join(self.workdir, file)
	if mode[0] != 'w':
	    raise ValueError, "mode must begin with 'w'"
	open(file, mode).write(content)