3 # adt-run is part of autopkgtest
4 # autopkgtest is a tool for testing Debian binary packages
6 # autopkgtest 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/autopkgtest/CREDITS).
40 from optparse import OptionParser
41 signal.signal(signal.SIGINT, signal.SIG_DFL) # undo stupid Python SIGINT thing
43 #---------- global variables
45 tmpdir = None # pathstring on host
46 testbed = None # Testbed
47 errorcode = 0 # exit status that we are going to use
48 binaries = None # Binaries (.debs we have registered)
50 #---------- errors we define
53 def __init__(q,ec,m): q.ec = ec; q.m = m
56 print >>sys.stderr, se
57 raise Quit(20, "unexpected error: %s" % m)
60 print >>sys.stderr, se
61 print 'blame: ', ' '.join(testbed.blamed)
62 raise Quit(12, "erroneous package: %s" % m)
64 def report(tname, result): print '%-20s %s' % (tname, result)
67 def __init__(u, lno, m):
68 if lno >= 0: u.m = '%s (control line %d)' % (m, lno)
73 report(tname, 'SKIP %s' % u.m)
77 if not opts.debug: return
78 for l in m.rstrip('\n').split('\n'):
79 print >>sys.stderr, 'atd-run: debug:', l
81 def mkdir_okexist(pathname, mode=02755):
83 os.mkdir(pathname, mode)
85 if oe.errno != errno.EEXIST: raise
87 def rmtree(what, pathname):
88 debug('/ %s rmtree %s' % (what, pathname))
89 shutil.rmtree(pathname)
91 def debug_subprocess(what, cmdl=None, script=None):
96 if x is script: x = '<SCRIPT>'
97 ol.append(x. replace('\\','\\\\').
99 o += ' '+ ' '.join(ol)
100 if script is not None:
102 for l in script.rstrip('\n').split('\n'):
107 return reduce((lambda a,b: a + b), l, [])
109 #---------- fancy automatic file-copying class
113 # p.path[tb] None or path not None => path known
114 # p.file[tb] None or path not None => file exists
115 # p.spec string or None
116 # p.spec_tbp True or False, or not set if spec is None
119 def __init__(p, what):
128 if p.path[tbp] is None: return '-'+p.dir
129 elif p.file[tbp] is None: return p.path[tbp]+p.dir+'?'
130 else: return p.path[tbp]+p.dir+'!'
132 if p.spec is not None:
133 if p.spec_tbp: out += '#'
144 if p.spec is not None: xtra = ' spec[%s]=%s' % (p.spec, p.spec_tb)
145 raise ("internal error: %s (%s)" % (how, str(p)))
147 def _ensure_path(p, tbp):
148 if p.path[tbp] is None:
150 p._debug('tmp-parent %s...' % 'HT'[tbp])
151 TemporaryDir(os.path.dirname(p.what)).write(tbp)
153 p.path[tbp] = tmpdir+'/'+p.what
155 p.path[tbp] = testbed.scratch.path[True]+'/'+p.what
157 def write(p, tbp=False):
158 p._debug('write %s...' % 'HT'[tbp])
161 if p.dir and not p.file[tbp]:
164 mkdir_okexist(p.path[tbp])
167 'test -d "$1" || mkdir -p "$1"',
169 tf_what = urllib.quote(p.what).replace('/','%2F')
170 (rc,se) = testbed.execute('mkdir-'+tf_what, cmdl)
171 if rc: bomb('failed to create directory %s' %
174 p.file[tbp] = p.path[tbp]
177 def read(p, tbp=False):
178 p._debug('read %s...' % 'HT'[tbp])
181 if p.file[tbp] is None:
182 if p.file[not tbp] is None:
183 p._wrong("requesting read but nonexistent")
184 cud = ['copyup','copydown'][tbp]
185 src = p.file[not tbp] + p.dir
186 dst = p.path[tbp] + p.dir
187 testbed.command(cud, (src, dst))
188 p.file[tbp] = p.path[tbp]
190 return p.file[tbp] + p.dir
192 def invalidate(p, tbp=False):
194 p._debug('invalidated %s' % 'HT'[tbp])
197 debug('/ %s#%x: %s' % (p.what, id(p), m))
200 p._debug('constructed: '+str(p))
204 for tbp in [False,True]:
205 for pf in [p.path, p.file]:
206 if pf[tbp] is None: continue
207 if not pf[tbp]: bomb('empty path specified for '+p.what)
208 if p.dir and pf[tbp].endswith('/'):
209 pf[tbp] = pf[tbp].rstrip('/')
210 if not pf[tbp]: pf[tbp] = '/'
211 if not p.dir and pf[tbp].endswith('/'):
212 bomb("directory `%s' specified for "
213 "non-directory %s" % (pf[tbp], p.what))
215 def _relative_init(p, what, parent, leaf, onlyon_tbp, setfiles, sibling):
216 AutoFile.__init__(p,what)
217 sh_on = ''; sh_sibl = ''
218 if onlyon_tbp is not None: sh_on = ' (on %s)' % ('HT'[onlyon_tbp])
219 if sibling: sh_sibl=' (sibling)'
220 parent._debug('using as base: %s: %s%s%s' %
221 (str(parent), leaf, sh_on, sh_sibl))
222 if not sibling and not parent.dir:
223 parent._wrong('asked for non-sibling relative path of non-dir')
224 if sibling: trim = os.path.dirname
225 else: trim = lambda x: x
226 for tbp in [False,True]:
227 if parent.path[tbp] is None: continue
228 trimmed = trim(parent.path[tbp])
229 if trimmed: trimmed += '/'
230 p.path[tbp] = trimmed + leaf
231 if setfiles and (onlyon_tbp is None or onlyon_tbp == tbp):
232 p.file[tbp] = p.path[tbp]
234 class InputFile(AutoFile):
235 def _init(p, what, spec, spec_tbp=False):
236 AutoFile.__init__(p, what)
238 p.spec_tbp = spec_tbp
239 p.path[spec_tbp] = spec
240 p.file[p.spec_tbp] = p.path[p.spec_tbp]
241 def __init__(p, what, spec, spec_tbp=False):
242 p._init(what,spec,spec_tbp)
245 class InputDir(InputFile):
246 def __init__(p, what, spec, spec_tbp=False):
247 InputFile._init(p,what,spec,spec_tbp)
251 class OutputFile(AutoFile):
252 def _init(p, what, spec, spec_tbp=False):
253 AutoFile.__init__(p, what)
255 p.spec_tbp = spec_tbp
256 p.path[spec_tbp] = spec
257 def __init__(p, what, spec, spec_tbp=False):
258 p._init(what,spec,spec_tbp)
261 class OutputDir(OutputFile):
262 def __init__(p, what, spec, spec_tbp=False):
263 OutputFile._init(p,what,spec,spec_tbp)
267 class RelativeInputFile(AutoFile):
268 def __init__(p, what, parent, leaf, onlyon_tbp=None, sibling=False):
269 p._relative_init(what, parent, leaf, onlyon_tbp, True, sibling)
272 class RelativeOutputFile(AutoFile):
273 def __init__(p, what, parent, leaf, sibling=False):
274 p._relative_init(what, parent, leaf, None, False, sibling)
277 class TemporaryFile(AutoFile):
278 def __init__(p, what):
279 AutoFile.__init__(p, what)
282 class TemporaryDir(AutoFile):
283 def __init__(p, what):
284 AutoFile.__init__(p, what)
288 #---------- parsing and representation of the arguments
291 def __init__(a, kind, af, arghandling, what):
292 # extra attributes get added during processing
300 usage = "%prog <options> --- <virt-server>..."
301 parser = OptionParser(usage=usage)
302 pa = parser.add_option
303 pe = parser.add_option
308 'deb_forbuilds': 'auto',
309 'deb_fortests': 'auto',
311 'override_control': None
313 initial_arghandling = arghandling.copy()
317 # actions (ie, test sets to run, sources to build, binaries to use):
319 def cb_action(op,optstr,value,parser, long,kindpath,is_act):
320 print >>sys.stderr, "cb_action", is_act
321 parser.largs.append((value,kindpath))
322 n_non_actions += not(is_act)
324 def pa_action(long, metavar, kindpath, help, is_act=True):
325 pa('','--'+long, action='callback', callback=cb_action,
326 nargs=1, type='string',
327 callback_args=(long,kindpath,is_act), help=help)
329 pa_action('build-tree', 'TREE', '@/',
330 help='run tests from build tree TREE')
332 pa_action('source', 'DSC', '@.dsc',
333 help='build DSC and use its tests and/or'
334 ' generated binary packages')
336 pa_action('binary', 'DEB', '@.deb',
337 help='use binary package DEB according'
338 ' to most recent --binaries-* settings')
340 pa_action('override-control', 'CONTROL', ('control',), is_act=0,
341 help='run tests from control file CONTROL instead,'
342 ' (applies to next test suite only)')
345 # argument handling settings (what ways to use action
346 # arguments, and pathname processing):
348 def cb_setah(option, opt_str, value, parser, toset,setval):
349 if type(setval) == list:
350 if not value in setval:
351 parser.error('value for %s option (%s) is not '
352 'one of the permitted values (%s)' %
353 (value, opt_str, setval.join(' ')))
354 elif setval is not None:
357 arghandling[v] = value
358 parser.largs.append(arghandling.copy())
360 def pa_setah(long, affected,effect, metavar=None, **kwargs):
362 if type is not None: type = 'string'
363 pa('',long, action='callback', callback=cb_setah,
364 callback_args=(affected,effect), **kwargs)
366 #---- paths: host or testbed:
368 pa_setah('--paths-testbed', ['tb'],True,
369 help='subsequent path specifications refer to the testbed')
370 pa_setah('--paths-host', ['tb'],False,
371 help='subsequent path specifications refer to the host')
373 #---- source processing settings:
375 pa_setah('--sources-tests', ['dsc_tests'],True,
376 help='run tests from builds of subsequent sources')
377 pa_setah('--sources-no-tests', ['dsc_tests'],False,
378 help='do not run tests from builds of subsequent sources')
380 pa_setah('--built-binaries-filter', ['dsc_filter'],None,
381 type='string', metavar='PATTERN-LIST',
382 help='from subsequent sources, use binaries matching'
383 ' PATTERN-LIST (comma-separated glob patterns)'
384 ' according to most recent --binaries-* settings')
385 pa_setah('--no-built-binaries', ['dsc_filter'], '_',
386 help='from subsequent sources, do not use any binaries')
388 #---- binary package processing settings:
390 def pa_setahbins(long,toset,how):
391 pa_setah(long, toset,['ignore','auto','install'],
392 type='string', metavar='IGNORE|AUTO|INSTALL', default='auto',
393 help=how+' ignore binaries, install them as needed'
394 ' for dependencies, or unconditionally install'
395 ' them, respectively')
396 pa_setahbins('--binaries', ['deb_forbuilds','deb_fortests'], '')
397 pa_setahbins('--binaries-forbuilds', ['deb_forbuilds'], 'for builds, ')
398 pa_setahbins('--binaries-fortests', ['deb_fortests'], 'for tests, ')
403 def cb_vserv(op,optstr,value,parser):
404 parser.values.vserver = list(parser.rargs)
407 def cb_path(op,optstr,value,parser, constructor,long,dir):
408 name = long.replace('-','_')
409 af = constructor(arghandling['tb'], value, long, dir)
410 setattr(parser.values, name, af)
412 def pa_path(long, constructor, help, dir=False):
413 pa('','--'+long, action='callback', callback=cb_path,
414 callback_args=(constructor,long,dir),
415 nargs=1, type='string',
416 help=help, metavar='PATH')
418 pa_path('output-dir', OutputDir, dir=True,
419 help='write stderr/out files in PATH')
421 pa('','--tmp-dir', type='string', dest='tmpdir',
422 help='write temporary files to TMPDIR, emptying it'
423 ' beforehand and leaving it behind at the end')
425 pa('','--user', type='string', dest='user',
426 help='run tests as USER (needs root on testbed)')
427 pa('','--gain-root', type='string', dest='gainroot',
428 help='prefix debian/rules binary with GAINROOT')
429 pa('-d', '--debug', action='store_true', dest='debug');
430 pa('','--gnupg-home', type='string', dest='gnupghome',
431 default='~/.autopkgtest/gpg',
432 help='use GNUPGHOME rather than ~/.autopkgtest (for'
433 " signing private apt archive);"
434 " `fresh' means generate new key each time.")
439 class SpecialOption(optparse.Option): pass
440 vs_op = SpecialOption('','--VSERVER-DUMMY')
441 vs_op.action = 'callback'
445 vs_op.callback = cb_vserv
446 vs_op.callback_args = ( )
447 vs_op.callback_kwargs = { }
448 vs_op.help = 'introduces virtualisation server and args'
449 vs_op._short_opts = []
450 vs_op._long_opts = ['---']
454 (opts,args) = parser.parse_args()
455 if not hasattr(opts,'vserver'):
456 parser.error('you must specifiy --- <virt-server>...')
457 if n_non_actions >= len(parser.largs):
458 parser.error('nothing to do specified')
460 arghandling = initial_arghandling
464 if type(act) == dict:
467 elif type(act) == tuple:
469 elif type(act) == str:
472 raise ("unknown action in list `%s' having"
473 " type `%s'" % (act, type(act)))
474 (pathstr, kindpath) = act
476 constructor = InputFile
477 if type(kindpath) is tuple: kind = kindpath[0]
478 elif kindpath.endswith('.deb'): kind = 'deb'
479 elif kindpath.endswith('.dsc'): kind = 'dsc'
480 elif kindpath.endswith('/'):
482 constructor = InputDir
483 else: parser.error("do not know how to handle filename \`%s';"
484 " specify --source --binary or --build-tree")
486 what = '%s%s' % (kind,ix); ix += 1
488 if kind == 'dsc': fwhatx = '/' + os.path.basename(pathstr)
489 else: fwhatx = '-'+kind
491 af = constructor(what+fwhatx, pathstr, arghandling['tb'])
492 opts.actions.append(Action(kind, af, arghandling, what))
494 def finalise_options():
495 global opts, tb, tmpdir
497 if opts.tmpdir is not None:
498 rmtree('tmpdir(specified)',opts.tmpdir)
499 mkdir_okexist(opts.tmpdir, 0700)
502 assert(tmpdir is None)
503 tmpdir = tempfile.mkdtemp()
505 if opts.user is None and 'root-on-testbed' not in testbed.caps:
508 if opts.user is None:
509 su = 'suggested-normal-user='
512 for e in testbed.caps
521 if 'root-on-testbed' not in testbed.caps:
522 print >>sys.stderr, ("warning: virtualisation"
523 " system does not offer root on testbed,"
524 " but --user option specified: failure likely")
525 opts.user_wrap = lambda x: "su %s -c '%s'" % (opts.user, x)
527 opts.user_wrap = lambda x: x
529 if opts.gainroot is None:
532 'root-on-testbed' not in testbed.caps):
533 opts.gainroot = 'fakeroot'
535 if opts.gnupghome.startswith('~/'):
536 try: home = os.environ['HOME']
538 parser.error("HOME environment variable"
539 " not set, needed for --gnupghome=`%s"
541 opts.gnupghome = home + opts.gnupghome[1:]
542 elif opts.gnupghome == 'fresh':
543 opts.gnupghome = None
545 #---------- testbed management - the Testbed class
561 debug_subprocess('vserver', opts.vserver)
562 tb.sp = subprocess.Popen(opts.vserver,
563 stdin=p, stdout=p, stderr=None)
565 tb.caps = tb.commandr('capabilities')
566 tb._need_reset_apt = False
570 if tb.sp is None: return
571 ec = tb.sp.returncode
578 tb.bomb('testbed gave exit status %d after quit' % ec)
580 tb._debug('open, scratch=%s' % tb.scratch)
581 if tb.scratch is not None: return
582 pl = tb.commandr('open')
583 tb.scratch = InputDir('tb-scratch', pl[0], True)
584 tb.deps_processed = []
585 def mungeing_apt(tb):
586 if not 'revert' in tb.caps:
587 tb._need_reset_apt = True
589 if not tb._need_reset_apt: return
590 what = 'aptget-update-reset'
591 cmdl = ['apt-get','-qy','update']
592 (rc,se) = tb.execute(what, cmdl)
594 print >>sys.stderr, se, ("\n" "warning: failed to restore"
595 " testbed apt cache, exit code %d" % rc)
596 tb._need_reset_apt = False
598 tb._debug('close, scratch=%s' % tb.scratch)
599 if tb.scratch is None: return
601 if tb.sp is None: return
603 def prepare(tb, deps_new):
604 tb._debug('prepare, modified=%s, deps_processed=%s, deps_new=%s' %
605 (tb.modified, tb.deps_processed, deps_new))
606 if 'revert' in tb.caps and (tb.modified or
607 [d for d in tb.deps_processed if d not in deps_new]):
608 tb._debug('reset **')
611 for af in tb._ephemeral: af.invalidate(True)
614 tb._install_deps(deps_new)
615 def register_ephemeral(tb, af):
616 tb._ephemeral.append(af)
617 def _install_deps(tb, deps_new):
618 tb._debug(' installing dependencies '+`deps_new`)
619 tb.deps_processed = deps_new
620 if not deps_new: return
621 dstr = ', '.join(deps_new)
622 script = binaries.apt_pkg_gdebi_script(
624 'from GDebi.DebPackage import DebPackage',
625 'd = DebPackage(cache)',
626 'res = d.satisfyDependsStr(arg)',
628 cmdl = ['python','-c',script]
629 what = 'install-deps'
630 debug_subprocess(what, cmdl, script=script)
631 (rc,se) = testbed.execute(what, cmdl)
632 if rc: badpkg('dependency install failed, exit code %d' % rc, se)
634 tb._debug('needs_reset, previously=%s' % tb.modified)
637 tb._debug('blame += %s' % m)
640 tb._debug('bomb %s' % m)
641 if tb.sp is not None:
645 if ec: print >>sys.stderr, ('adt-run: testbed failing,'
646 ' exit status %d' % ec)
648 raise Quit(16, 'testbed failed: %s' % m)
649 def send(tb, string):
653 print >>tb.sp.stdin, string
657 (type, value, dummy) = sys.exc_info()
658 tb.bomb('cannot send to testbed: %s' % traceback.
659 format_exception_only(type, value))
660 def expect(tb, keyword, nresults=None):
661 l = tb.sp.stdout.readline()
662 if not l: tb.bomb('unexpected eof from the testbed')
663 if not l.endswith('\n'): tb.bomb('unterminated line from the testbed')
667 if not ll: tb.bomb('unexpected whitespace-only line from the testbed')
669 if tb.lastsend is None:
670 tb.bomb("got banner `%s', expected `%s...'" %
673 tb.bomb("sent `%s', got `%s', expected `%s...'" %
674 (tb.lastsend, l, keyword))
676 if nresults is not None and len(ll) != nresults:
677 tb.bomb("sent `%s', got `%s' (%d result parameters),"
678 " expected %d result parameters" %
679 (string, l, len(ll), nresults))
681 def commandr(tb, cmd, args=(), nresults=None):
682 # pass args=[None,...] or =(None,...) to avoid more url quoting
683 if type(cmd) is str: cmd = [cmd]
684 if len(args) and args[0] is None: args = args[1:]
685 else: args = map(urllib.quote, args)
687 tb.send(string.join(al))
688 ll = tb.expect('ok', nresults)
689 rl = map(urllib.unquote, ll)
691 def command(tb, cmd, args=()):
692 tb.commandr(cmd, args, 0)
693 def commandr1(tb, cmd, args=()):
694 rl = tb.commandr(cmd, args, 1)
696 def execute(tb, what, cmdargs,
697 si='/dev/null', so='/dev/null', se=None, cwd=None,
699 if cwd is None: cwd = tb.scratch.write(True)
702 se_af = TemporaryFile('xerr-'+what)
703 se_use = se_af.write(True)
705 ','.join(map(urllib.quote, cmdargs)),
707 if dump_fd is not None: cmdl += ['debug=%d-%d' % (dump_fd,2)]
708 rc = tb.commandr1('execute', cmdl)
710 except ValueError: bomb("execute for %s gave invalid response `%s'"
712 if se is not None: return rc
713 return (rc, file(se_af.read()).read())
715 #---------- representation of test control files: Field*, Test, etc.
718 def __init__(f, fname, stz, base, tnames, vl):
728 r = map((lambda w: (lno, w)), r)
730 return flatten(map(distribute, f.vl))
735 raise Unsupported(f.vl[1][0],
736 'only one %s field allowed' % fn)
739 class FieldIgnore(FieldBase):
743 def __init__(r,rname,base): pass
745 class Restriction_rw_build_tree(Restriction): pass
746 class Restriction_rw_tests_tree(Restriction): pass
747 class Restriction_breaks_testbed(Restriction):
748 def __init__(r, rname, base):
749 if 'revert' not in testbed.caps:
750 raise Unsupported(f.lno,
751 'Test breaks testbed but testbed cannot reset')
753 class Field_Restrictions(FieldBase):
755 for wle in f.words():
757 rname = rname.replace('-','_')
758 try: rclass = globals()['Restriction_'+rname]
759 except KeyError: raise Unsupported(lno,
760 'unknown restriction %s' % rname)
761 r = rclass(rname, f.base)
762 f.base['restrictions'].append(r)
764 class Field_Tests(FieldIgnore): pass
766 class Field_Depends(FieldBase):
768 dl = map(lambda x: x.strip(),
769 flatten(map(lambda x: x.split(','), f.vl)))
770 re = regexp.compile('[^-.+:~]')
773 badpkg("Test Depends field contains dependency"
774 " `%s' with invalid characters" % d)
775 f.base['depends'] = dl
777 class Field_Tests_directory(FieldBase):
780 if td.startswith('/'): raise Unspported(f.lno,
781 'Tests-Directory may not be absolute')
782 f.base['testsdir'] = td
784 def run_tests(stanzas, tree):
785 global errorcode, testbed
786 for stanza in stanzas:
787 tests = stanza[' tests']
789 report('*', 'SKIP no tests in this package')
794 if 'breaks-testbed' in t.restrictions:
795 testbed.needs_reset()
796 testbed.needs_reset()
799 def __init__(t, tname, base, act):
800 if '/' in tname: raise Unsupported(base[' lno'],
801 'test name may not contain / character')
802 for k in base: setattr(t,k,base[k])
805 t.what = act.what+'t-'+tname
806 if len(base['testsdir']): t.path = base['testsdir'] + '/' + tname
808 t._debug('constructed; path=%s' % t.path)
809 t._debug(' .depends=%s' % t.depends)
811 debug('& %s: %s' % (t.what, m))
814 def reportfail(t, m):
817 report(t.what, 'FAIL ' + m)
819 t._debug('preparing')
822 t._debug(' processing dependency '+d)
824 t._debug(' literal dependency '+d)
827 for (pkg,bin) in t.act.binaries:
828 d = d.replace('*',pkg)
829 t._debug(' synthesised dependency '+d)
835 idstr = t.what + '-' + oe
836 if opts.output_dir is not None and opts.output_dir.tb:
837 use_dir = opts.output_dir
839 use_dir = testbed.scratch
840 return RelativeOutputFile(idstr, use_dir, idstr)
842 t.act.work.write(True)
844 af = RelativeInputFile(t.what, tree, t.path)
845 so = stdouterr('stdout')
846 se = stdouterr('stderr')
847 rc = testbed.execute('test-'+t.what,
848 [opts.user_wrap(af.read(True))],
849 so=so.write(True), se=se.write(True), cwd=tree.read(True))
851 stab = os.stat(se.read())
852 if stab.st_size != 0:
853 l = file(se.read()).readline()
854 l = l.rstrip('\n \t\r')
855 if len(l) > 40: l = l[:40] + '...'
856 t.reportfail('status: %d, stderr: %s' % (rc, l))
858 t.reportfail('non-zero exit status %d' % rc)
862 def read_control(act, tree, control_override):
865 if control_override is not None:
866 control_af = control_override
867 testbed.blame('arg:'+control_override.spec)
869 control_af = RelativeInputFile(act.what+'-testcontrol',
870 tree, 'debian/tests/control')
872 control = file(control_af.read(), 'r')
874 if oe[0] != errno.ENOENT: raise
878 def badctrl(m): act.bomb('tests/control line %d: %s' % (lno, m))
879 stz = None # stz[field_name][index] = (lno, value)
880 # special field names:
881 # stz[' lno'] = number
882 # stz[' tests'] = list of Test objects
884 if stz is None: return
890 initre = regexp.compile('([A-Z][-0-9a-z]*)\s*\:\s*(.*)$')
892 l = control.readline()
895 if not l.endswith('\n'): badctrl('unterminated line')
896 if regexp.compile('\s*\#').match(l): continue
897 if not regexp.compile('\S').match(l): end_stanza(stz); continue
898 initmat = initre.match(l)
900 (fname, l) = initmat.groups()
901 fname = string.capwords(fname)
903 stz = { ' lno': lno, ' tests': [] }
904 if not stz.has_key(fname): stz[fname] = [ ]
905 hcurrent = stz[fname]
906 elif regexp.compile('\s').match(l):
907 if not hcurrent: badctrl('unexpected continuation')
909 badctrl('syntax error')
910 hcurrent.append((lno, l))
913 def testbadctrl(stz, lno, m):
914 report_badctrl(lno, m)
919 try: tnames = stz['Tests']
922 raise Unsupported(stz[' lno'],
924 tnames = map((lambda lt: lt[1]), tnames)
925 tnames = string.join(tnames).split()
928 'testsdir': 'debian/tests',
931 for fname in stz.keys():
932 if fname.startswith(' '): continue
934 try: fclass = globals()['Field_'+
935 fname.replace('-','_')]
936 except KeyError: raise Unsupported(vl[0][0],
937 'unknown metadata field %s' % fname)
938 f = fclass(stz, fname, base, tnames, vl)
941 t = Test(tname, base, act)
942 stz[' tests'].append(t)
943 except Unsupported, u:
944 for tname in tnames: u.report(tname)
949 def print_exception(ei, msgprefix=''):
950 if msgprefix: print >>sys.stderr, msgprefix
953 print >>sys.stderr, 'adt-run:', q.m
956 print >>sys.stderr, "adt-run: unexpected, exceptional, error:"
957 traceback.print_exc()
963 if opts.tmpdir is None and tmpdir is not None:
964 rmtree('tmpdir', tmpdir)
965 if testbed is not None:
968 if rm_ec: bomb('rm -rf -- %s failed, code %d' % (tmpdir, ec))
970 print_exception(sys.exc_info(),
971 '\nadt-run: error cleaning up:\n')
974 #---------- registration, installation etc. of .deb's: Binaries
976 def determine_package(act):
977 cmd = 'dpkg-deb --info --'.split(' ')+[act.af.read(),'control']
978 running = subprocess.Popen(cmd, stdout=subprocess.PIPE)
979 output = running.communicate()[0]
981 if rc: badpkg('failed to parse binary package, code %d' % rc)
982 re = regexp.compile('^\s*Package\s*:\s*([0-9a-z][-+.0-9a-z]*)\s*$')
984 for l in output.split('\n'):
987 if act.pkg: badpkg('two Package: lines in control file')
988 act.pkg = m.groups()[0]
989 if not act.pkg: badpkg('no good Package: line in control file')
993 b.dir = TemporaryDir('binaries')
997 if opts.gnupghome is None:
998 opts.gnupghome = tmpdir+'/gnupg'
1000 b._debug('initialising')
1002 for x in ['pubring','secring']:
1003 os.stat(opts.gnupghome + '/' + x + '.gpg')
1006 if oe.errno != errno.ENOENT: raise
1008 if ok: b._debug('no key generation needed')
1015 b._debug('preparing for key generation')
1017 mkdir_okexist(os.path.dirname(opts.gnupghome), 02755)
1018 mkdir_okexist(opts.gnupghome, 0700)
1022 exec >key-gen-log 2>&1
1023 cat <<"END" >key-gen-params
1027 Name-Real: autopkgtest per-run key
1028 Name-Comment: do not trust this key
1029 Name-Email: autopkgtest@example.com
1032 gpg --homedir="$1" --batch --gen-key key-gen-params
1034 cmdl = ['sh','-ec',script,'x',opts.gnupghome]
1035 debug_subprocess('genkey', cmdl, script=script)
1036 rc = subprocess.call(cmdl)
1039 f = open(opts.gnupghome+'/key-gen-log')
1041 except OSError, e: tp = e
1042 print >>sys.stderr, tp
1043 bomb('key generation failed, code %d' % rc)
1047 "Dir::Etc::sourcelist": b.dir.read(True)+'sources.list',
1050 def apt_pkg_gdebi_script(b, arg, middle):
1054 'arg = urllib.unquote("%s")' % urllib.quote(arg),
1056 for (k,v) in b.apt_configs().iteritems():
1058 script.append('apt_pkg.Config.Set("%s",urllib.unquote("%s"))'
1061 'from GDebi.Cache import Cache',
1067 'print d.missingDeps',
1068 'print d.requiredChanges',
1073 return '\n'.join(script)
1075 ag = ['apt-get','-qy']
1076 for kv in b.apt_configs().iteritems():
1077 ag += ['-o', '%s=%s' % kv]
1082 rmtree('binaries', b.dir.read())
1087 b.registered = set()
1089 def register(b, act, pkg, af, forwhat, blamed):
1090 b._debug('register what=%s deb_%s=%s pkg=%s af=%s'
1091 % (act.what, forwhat, act.ah['deb_'+forwhat], pkg, str(af)))
1093 if act.ah['deb_'+forwhat] == 'ignore': return
1095 b.blamed += testbed.blamed
1097 leafname = pkg+'.deb'
1098 dest = RelativeOutputFile('binaries--'+leafname, b.dir, leafname)
1100 try: os.remove(dest.write())
1102 if oe.errno != errno.ENOENT: raise e
1104 try: os.link(af.read(), dest.write())
1106 if oe.errno != errno.EXDEV: raise e
1107 shutil.copy(af.read(), dest)
1109 if act.ah['deb_'+forwhat] == 'install':
1110 b.install.append(pkg)
1112 b.registered.add(pkg)
1119 apt-ftparchive packages . >Packages
1120 gzip <Packages >Packages.gz
1121 apt-ftparchive release . >Release
1123 gpg --homedir="$2" --batch --detach-sign --armour -o Release.gpg Release
1124 gpg --homedir="$2" --batch --export >archive-key.pgp
1126 cmdl = ['sh','-ec',script,'x',b.dir.write(),opts.gnupghome]
1127 debug_subprocess('ftparchive', cmdl, script)
1128 rc = subprocess.call(cmdl)
1129 if rc: bomb('apt-ftparchive or signature failed, code %d' % rc)
1131 b.dir.invalidate(True)
1132 apt_source = b.dir.read(True)
1134 so = TemporaryFile('vlds')
1136 apt-key add archive-key.pgp >&2
1137 echo "deb file://'''+apt_source+''' /" >sources.list
1138 cat /etc/apt/sources.list >>sources.list
1139 if [ "x`ls /var/lib/dpkg/updates`" != x ]; then
1140 echo >&2 "/var/lib/dpkg/updates contains some files, aargh"; exit 1
1142 '''+ ' '.join(b.apt_get()) +''' update >&2
1143 cat /var/lib/dpkg/status
1145 testbed.mungeing_apt()
1146 debug_subprocess('apt-key', script=script)
1147 (rc,se) = testbed.execute('apt-key',
1148 ['sh','-ec',script],
1149 so=so.write(True), cwd=b.dir.write(True))
1150 if rc: bomb('apt setup failed with exit code %d' % rc, se)
1152 testbed.blamed += b.blamed
1154 b._debug('publish reinstall checking...')
1155 pkgs_reinstall = set()
1157 for l in file(so.read()):
1158 if l.startswith('Package: '):
1159 pkg = l[9:].rstrip()
1160 elif l.startswith('Status: install '):
1161 if pkg in b.registered:
1162 pkgs_reinstall.add(pkg)
1163 b._debug(' publish reinstall needs '+pkg)
1166 for pkg in pkgs_reinstall: testbed.blame(pkg)
1167 what = 'apt-get-reinstall'
1168 cmdl = (b.apt_get() + ['--reinstall','install'] +
1169 [pkg for pkg in pkgs_reinstall])
1170 debug_subprocess(what, cmdl)
1171 (rc,se) = testbed.execute(what, cmdl)
1172 if rc: badpkg("installation of basic binarries failed,"
1173 " exit code %d" % rc, se)
1175 b._debug('publish install...')
1176 for pkg in b.install:
1177 what = 'apt-get-install-%s' % pkg
1179 cmdl = b.apt_get() + ['install',pkg]
1180 debug_subprocess(what, cmdl)
1181 (rc,se) = testbed.execute(what, cmdl)
1182 if rc: badpkg("installation of %s failed, exit code %d"
1185 b._debug('publish done')
1187 #---------- processing of sources (building)
1189 def source_rules_command(act,script,what,which,work,results_lines=0):
1191 trace = "%s-%s-trace" % (what,which)
1192 script = [ "mkfifo -m600 "+trace,
1193 "tee <"+trace+" /dev/stderr >&4 &",
1194 "exec >"+trace+" 2>&1" ] + script
1196 script = [ "exec 3>&1 >&2",
1198 script = '\n'.join(script)
1199 so = TemporaryFile('%s-%s-results' % (what,which))
1200 se = TemporaryFile('%s-%s-log' % (what,which))
1201 debug_subprocess('source-rules-command/%s/%s' % (act.what, which),
1203 rc = testbed.execute('%s-%s' % (what,which),
1204 ['sh','-xec',script],
1205 so=so.write(True), se=se.write(True),
1206 cwd= work.write(True), dump_fd=4)
1207 results = file(so.read()).read().rstrip('\n').split("\n")
1208 se = file(se.read()).read()
1209 if rc: badpkg("%s failed with exit code %d" % (which,rc), se)
1210 if results_lines is not None and len(results) != results_lines:
1211 badpkg("got %d lines of results from %s where %d expected"
1212 % (len(results), which, results_lines), se)
1213 if results_lines==1: return results[0]
1216 def build_source(act):
1217 act.blame = 'arg:'+act.af.spec
1218 testbed.blame(act.blame)
1219 testbed.needs_reset()
1225 dsc_file = open(dsc.read())
1227 fre = regexp.compile('^\s+[0-9a-f]+\s+\d+\s+([^/.][^/]*)$')
1230 if l.startswith('Files:'): in_files = True; continue
1231 elif l.startswith('#'): pass
1232 elif not l.startswith(' '):
1234 if l.startswith('Source:'):
1235 act.blame = 'dsc:'+l[7:].strip()
1236 testbed.blame(act.blame)
1237 if not in_files: continue
1240 if not m: badpkg(".dsc contains unparseable line"
1241 " in Files: `%s'" % l)
1242 leaf = m.groups(0)[0]
1243 subfile = RelativeInputFile(what+'/'+leaf, dsc, leaf,
1248 script = binaries.apt_pkg_gdebi_script(
1250 'from GDebi.DscSrcPackage import DscSrcPackage',
1251 'd = DscSrcPackage(cache, arg)',
1252 'res = d.checkDeb()',
1254 'from GDebi.DebPackage import DebPackage',
1255 'd = DebPackage(cache)',
1256 'res = d.satisfyDependsStr("build-essential")',
1258 cmdl = ['python','-c',script]
1259 whatp = what+'-builddeps'
1260 debug_subprocess(whatp, cmdl, script=script)
1261 (rc,se) = testbed.execute(what, cmdl)
1262 if rc: badpkg('build-depends install failed, exit code %d' % rc, se)
1264 work = TemporaryDir(what+'-build')
1267 'cd '+work.write(True),
1269 if opts.user: script += [
1270 'chown '+opts.user+' .',
1271 'dsc=dsc.read(True) '+
1272 opts.user_wrap('dpkg-source -x $dsc')
1275 'dpkg-source -x '+dsc.read(True),
1279 'dpkg-checkbuilddeps',
1281 opts.user_wrap('debian/rules build'),
1283 result_pwd = source_rules_command(act,script,what,'build',work,1)
1285 if os.path.dirname(result_pwd)+'/' != work.read(True):
1286 badpkg("results dir `%s' is not in expected parent dir `%s'"
1287 % (result_pwd, work.read(True)))
1290 act.tests_tree = InputDir(what+'-tests-tree',
1291 work.read(True)+os.path.basename(result_pwd),
1293 if act.ah['dsc_tests']:
1294 act.tests_tree.read()
1295 testbed.register_ephemeral(act.work)
1296 testbed.register_ephemeral(act.tests_tree)
1298 act.blamed = copy.copy(testbed.blamed)
1300 def debug_b(m): debug('* <dsc:%s> %s' % (act.what, m))
1302 filter = act.ah['dsc_filter']
1303 debug_b('filter=%s' % filter)
1306 'cd '+work.write(True)+'/*/.',
1307 opts.user_wrap(opts.gainroot+' debian/rules binary'),
1311 result_debs = source_rules_command(act,script,what,
1313 if result_debs == '*': debs = []
1314 else: debs = result_debs.split(' ')
1315 debug_b('debs='+`debs`)
1316 re = regexp.compile('^([-+.0-9a-z]+)_[^_/]+(?:_[^_/]+)\.deb$')
1319 if not m: badpkg("badly-named binary `%s'" % deb)
1321 debug_b(' deb=%s, pkg=%s' % (deb,pkg))
1322 for pat in filter.split(','):
1323 debug_b(' pat=%s' % pat)
1324 if not fnmatch.fnmatchcase(pkg,pat):
1325 debug_b(' no match')
1327 deb_what = pkg+'_'+what+'.deb'
1328 bin = RelativeInputFile(deb_what,work,deb,True)
1329 debug_b(' deb_what=%s, bin=%s' %
1330 (deb_what, str(bin)))
1331 binaries.register(act,pkg,bin,
1332 'forbuilds',testbed.blamed)
1333 act.binaries.append((pkg,bin))
1335 debug_b('all done.')
1337 #---------- main processing loop and main program
1339 def process_actions():
1342 def debug_a1(m): debug('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ '+m)
1343 def debug_a2(m): debug('@@@@@@@@@@@@@@@@@@@@ '+m)
1344 def debug_a3(m): debug('@@@@@@@@@@ '+m)
1346 debug_a1('starting')
1348 binaries = Binaries()
1352 debug_a1('builds ...')
1353 for act in opts.actions:
1355 (act.kind, act.what))
1358 if act.kind == 'deb':
1359 testbed.blame('arg:'+act.af.spec)
1360 determine_package(act)
1361 testbed.blame('deb:'+act.pkg)
1362 binaries.register(act,act.pkg,act.af,
1363 'forbuilds',testbed.blamed)
1364 if act.kind == 'dsc':
1366 if act.kind == 'tree':
1369 debug_a1('builds done.')
1372 control_override = None
1374 debug_a1('tests ...')
1375 for act in opts.actions:
1376 debug_a2('test %s %s' % (act.kind, act.what))
1378 testbed.needs_reset()
1379 if act.kind == 'control':
1380 control_override = act.af
1381 if act.kind == 'deb':
1382 binaries.register(act,act.pkg,act.af,'fortests',
1384 if act.kind == 'dsc':
1385 for (pkg,bin) in act.binaries:
1386 binaries.register(act,pkg,bin,'fortests',
1388 if act.ah['dsc_tests']:
1389 debug_a3('read control ...')
1390 stanzas = read_control(act, act.tests_tree,
1392 testbed.blamed += act.blamed
1393 debug_a3('run_tests ...')
1394 run_tests(stanzas, act.tests_tree)
1395 control_override = None
1396 if act.kind == 'tree':
1397 testbed.blame('arg:'+act.af.spec)
1398 stanzas = read_control(act, act.af, control_override)
1399 debug_a3('run_tests ...')
1400 run_tests(stanzas, act.af)
1401 control_override = None
1402 debug_a1('tests done.')
1409 except SystemExit, se:
1417 ec = print_exception(sys.exc_info(), '')