3 # adt-run is part of autodebtest
4 # autodebtest is a tool for testing Debian binary packages
6 # autodebtest is Copyright (C) 2006 Canonical Ltd.
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 # See the file CREDITS for a full list of credits information (often
23 # installed as /usr/share/doc/autodebtest/CREDITS).
37 from optparse import OptionParser
43 signal.signal(signal.SIGINT, signal.SIG_DFL) # undo stupid Python SIGINT thing
46 def __init__(q,ec,m): q.ec = ec; q.m = m
48 def bomb(m): raise Quit(20, "unexpected error: %s" % m)
49 def badpkg(m): raise Quit(12, "erroneous package: %s" % m)
50 def report(tname, result): print '%-20s %s' % (tname, result)
53 def __init__(u, lno, m):
54 if lno >= 0: u.m = '%s (control line %d)' % (m, lno)
59 report(tname, 'SKIP %s' % u.m)
63 if not opts.debug: return
64 print >>sys.stderr, 'atd-run: debug:', m
67 return reduce((lambda a,b: a + b), l, [])
70 def __init__(p, tb, path, what, dir=False):
77 bomb("path %s specified as being in testbed but"
78 " not absolute: `%s'" % (what, p.p))
84 if p.dir: p.dirsfx = '/'
88 def append(p, suffix, what, dir=False):
89 return Path(p.tb, p.path() + suffix, what=what, dir=dir)
91 if p.tb: pfx = '/VIRT'
92 elif p.p[:1] == '/': pfx = '/HOST'
96 if p.local is not None: return p.local
98 p.local = tmpdir + '/tb-' + p.what
99 testbed.command('copyup', (p.path(), p.local + p.dirsfx))
102 if p.down is not None: return p.down
103 p.down = testbed.scratch.p + '/host-' + p.what
104 testbed.command('copydown', (p.path(), p.down + p.dirsfx))
109 usage = "%prog <options> -- <virt-server>..."
110 parser = OptionParser(usage=usage)
111 pa = parser.add_option
112 pe = parser.add_option
114 def cb_vserv(op,optstr,value,parser):
115 parser.values.vserver = list(parser.rargs)
118 def cb_path(op,optstr,value,parser, long,tb,dir):
119 name = long.replace('-','_')
120 setattr(parser.values, name, Path(tb, value, long, dir))
122 def pa_path(long, dir, help):
123 def papa_tb(long, ca, pahelp):
124 pa('', long, action='callback', callback=cb_path,
125 nargs=1, type='string', callback_args=ca,
126 help=(help % pahelp), metavar='PATH')
127 papa_tb('--'+long, (long, False, dir), 'host')
128 papa_tb('--'+long+'-tb',(long, True, dir), 'testbed')
130 pa_path('build-tree', True, 'use build tree from PATH on %s')
131 pa_path('control', False, 'read control file PATH on %s')
133 pa('-d', '--debug', action='store_true', dest='debug');
134 # pa('','--user', type='string',
135 # help='run tests as USER (needs root on testbed)')
138 class SpecialOption(optparse.Option): pass
139 vs_op = SpecialOption('','--VSERVER-DUMMY')
140 vs_op.action = 'callback'
144 vs_op.callback = cb_vserv
145 vs_op.callback_args = ( )
146 vs_op.callback_kwargs = { }
147 vs_op.help = 'introduces virtualisation server and args'
148 vs_op._short_opts = []
149 #vs_op._long_opts = ['--DUMMY']
150 vs_op._long_opts = ['---']
154 (opts,args) = parser.parse_args()
155 if not hasattr(opts,'vserver'):
156 parser.error('you must specifiy --- <virt-server>...')
158 if opts.build_tree is None:
159 opts.build_tree = Path(False, '.', 'build-tree', dir=True)
160 if opts.control is None:
161 opts.control = opts.build_tree.append(
162 'debian/tests/control', 'control')
171 tb.sp = subprocess.Popen(opts.vserver,
172 stdin=p, stdout=p, stderr=None)
176 if tb.sp is None: return
177 ec = tb.sp.returncode
184 tb.bomb('testbed gave exit status %d after quit' % ec)
186 if tb.scratch is not None: return
187 p = tb.commandr1('open')
188 tb.scratch = Path(True, p, 'tb-scratch', dir=True)
190 if tb.scratch is None: return
194 if tb.sp is not None:
198 if ec: print >>sys.stderr, ('adt-run: testbed failing,'
199 ' exit status %d' % ec)
201 raise Quit(16, 'testbed failed: %s' % m)
202 def send(tb, string):
205 print >>tb.sp.stdin, string
209 tb.bomb('cannot send to testbed: %s' %
210 formatexception_only(sys.last_type, sys.last_value))
211 def expect(tb, keyword, nresults=-1):
212 l = tb.sp.stdout.readline()
213 if not l: tb.bomb('unexpected eof from the testbed')
214 if not l.endswith('\n'): tb.bomb('unterminated line from the testbed')
218 if not ll: tb.bomb('unexpected whitespace-only line from the testbed')
220 if tb.lastsend is None:
221 tb.bomb("got banner `%s', expected `%s...'" %
224 tb.bomb("sent `%s', got `%s', expected `%s...'" %
225 (tb.lastsend, l, keyword))
227 if nresults >= 0 and len(ll) != nresults:
228 tb.bomb("sent `%s', got `%s' (%d result parameters),"
229 " expected %d result parameters" %
230 (string, l, len(ll), nresults))
232 def commandr(tb, cmd, nresults, args=()):
233 al = [cmd] + map(urllib.quote, args)
234 tb.send(string.join(al))
236 rl = map(urllib.unquote, ll)
238 def command(tb, cmd, args=()):
239 tb.commandr(cmd, 0, args)
240 def commandr1(tb, cmd, args=()):
241 rl = tb.commandr(cmd, 1, args)
245 def __init__(f, fname, stz, base, tnames, vl):
255 r = map((lambda w: (lno, w)), r)
257 return flatten(map(distribute, f.vl))
262 raise Unsupported(f.vl[1][0],
263 'only one %s field allowed' % fn)
266 class FieldIgnore(FieldBase):
270 def __init__(r,rname,base): pass
272 class Restriction_rw_build_tree(Restriction): pass
274 class Field_Restrictions(FieldBase):
276 for wle in f.words():
278 rname = rname.replace('-','_')
279 try: rclass = globals()['Restriction_'+rname]
280 except KeyError: raise Unsupported(lno,
281 'unknown restriction %s' % rname)
282 r = rclass(rname, f.base)
283 f.base['restrictions'].append(r)
285 class Field_Tests(FieldIgnore): pass
287 class Field_Tests_directory(FieldBase):
290 if td.startswith('/'): raise Unspported(f.lno,
291 'Tests-Directory may not be absolute')
292 base['testsdir'] = td
300 report('*', 'SKIP no tests in this package')
304 def __init__(t, tname, base):
305 if '/' in tname: raise Unsupported(base[' lno'],
306 'test name may not contain / character')
307 for k in base: setattr(t,k,base[k])
309 t.p = opts.build_tree.append(tname, 'test-'+tname)
313 def reportfail(t, m):
316 report(t.tname, 'FAIL ' + m)
319 so = testbed.scratch.append('stdout-' + t.tname, 'stdout-' + t.tname)
320 se = testbed.scratch.append('stdout-' + t.tname, 'stdout-' + t.tname)
321 rc = testbed.commandr1('execute',(t.p.ontb(),
322 '/dev/null', so.ontb(), se.ontb()))
328 if stab.st_size != 0:
329 l = file(seh).readline()
330 l = l.rstrip('\n \t\r')
331 if len(l) > 40: l = l[:40] + '...'
332 t.reportfail('stderr: %s' % l)
334 t.reportfail('non-zero exit status %d' % rc)
341 control = file(opts.control.onhost(), 'r')
343 if oe[0] != errno.ENOENT: raise
347 def badctrl(m): testbed.badpkg('tests/control line %d: %s' % (lno, m))
348 stz = None # stz[field_name][index] = (lno, value)
354 if stz is None: return
360 initre = regexp.compile('([A-Z][-0-9a-z]*)\s*\:\s*(.*)$')
362 l = control.readline()
365 if not l.endswith('\n'): badctrl('unterminated line')
366 if regexp.compile('\s*\#').match(l): continue
367 if not regexp.compile('\S').match(l): end_stanza(stz); continue
368 initmat = initre.match(l)
370 (fname, l) = initmat.groups()
371 fname = string.capwords(fname)
373 stz = { ' lno': lno }
374 if not stz.has_key(fname): stz[fname] = [ ]
375 hcurrent = stz[fname]
376 elif regexp.compile('\s').match(l):
377 if not hcurrent: badctrl('unexpected continuation')
379 badctrl('syntax error')
380 hcurrent.append((lno, l))
383 def testbadctrl(stz, lno, m):
384 report_badctrl(lno, m)
389 try: tnames = stz['Tests']
392 raise Unsupported(stz[' lno'],
394 tnames = map((lambda lt: lt[1]), tnames)
395 tnames = string.join(tnames).split()
398 'testsdir': 'debian/tests'
400 for fname in stz.keys():
401 if fname.startswith(' '): continue
403 try: fclass = globals()['Field_'+
404 fname.replace('-','_')]
405 except KeyError: raise Unsupported(vl[0][0],
406 'unknown metadata field %s' % fname)
407 f = fclass(stz, fname, base, tnames, vl)
411 t = Test(tname, base)
413 except Unsupported, u:
414 for tname in tnames: u.report(tname)
417 def print_exception(ei, msgprefix=''):
418 if msgprefix: print >>sys.stderr, msgprefix
421 print >>sys.stderr, 'adt-run:', q.m
424 print >>sys.stderr, "adt-run: unexpected, exceptional, error:"
425 traceback.print_exc()
431 if tmpdir is not None:
432 rm_ec = subprocess.call(['rm','-rf','--',tmpdir])
433 if testbed is not None:
435 if rm_ec: bomb('rm -rf -- %s failed, code %d' % (tmpdir, ec))
437 print_exception(sys.exc_info(),
438 '\nadt-run: error cleaning up:\n')
446 except SystemExit, se:
449 tmpdir = tempfile.mkdtemp()
455 ec = print_exception(sys.exc_info(), '')