2 # Bootstrap Samba and run a number of tests against it.
3 # Copyright (C) 2005-2012 Jelmer Vernooij <jelmer@samba.org>
4 # Copyright (C) 2007-2009 Stefan Metzmacher <metze@samba.org>
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 from cStringIO import StringIO
31 sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
33 from selftest import (
38 from selftest.target import EnvironmentManager
43 def read_excludes(fn):
44 excludes.extend(testlist.read_test_regexes(fn))
46 def read_includes(fn):
47 includes.extend(testlist.read_test_regexes(fn))
49 parser = optparse.OptionParser("TEST-REGEXES")
50 parser.add_option("--target", type="choice", choices=["samba", "samba3"], default="samba", help="Samba version to target")
51 parser.add_option("--quick", help="run quick overall test")
52 parser.add_option("--verbose", help="be verbose")
53 parser.add_option("--list", help="list available tests")
54 parser.add_option("--socket-wrapper", help="enable socket wrapper")
55 parser.add_option("--socket-wrapper-pcap", help="save traffic to pcap directories", type="str")
56 parser.add_option("--socket-wrapper-keep-pcap", help="keep all pcap files, not just those for tests that failed")
57 parser.add_option("--one", help="abort when the first test fails")
58 parser.add_option("--exclude", action="callback", help="Add file to exclude files", callback=read_excludes)
59 parser.add_option("--include", action="callback", help="Add file to include files", callback=read_includes)
60 parser.add_option("--testenv", help="run a shell in the requested test environment")
61 parser.add_option("--resetup-environment", help="Re-setup environment")
62 parser.add_option("--binary-mapping", help="Map binaries to use", type=str)
63 parser.add_option("--load-list", help="Load list of tests to load from a file", type=str)
64 parser.add_option("--prefix", help="prefix to run tests in", type=str, default="./st")
65 parser.add_option("--srcdir", type=str, default=".", help="source directory")
66 parser.add_option("--bindir", type=str, default="./bin", help="binaries directory")
67 parser.add_option("--testlist", type=str, action="append", help="file to read available tests from")
68 parser.add_option("--ldap", help="back samba onto specified ldap server", choices=["openldap", "fedora-ds"], type="choice")
70 opts, args = parser.parse_args()
72 subunit_ops = subunithelper.SubunitOps(sys.stdout)
74 def pipe_handler(sig):
75 sys.stderr.write("Exiting early because of SIGPIPE.\n")
78 signal.signal(signal.SIGPIPE, pipe_handler)
81 return testlist.find_in_list(excludes, name)
84 if (not opts.socket_wrapper_pcap or
85 not os.environ.get("SOCKET_WRAPPER_PCAP_DIR")):
88 fname = "".join([x for x in name if x.isalnum() or x == '-'])
90 pcap_file = os.path.join(
91 os.environ["SOCKET_WRAPPER_PCAP_DIR"], "%s.pcap" % fname)
93 socket_wrapper.setup_pcap(pcap_file)
97 def cleanup_pcap(pcap_file, exit_code):
98 if not opts.socket_wrapper_pcap:
100 if opts.socket_wrapper_keep_pcap:
104 if pcap_file is None:
110 # expand strings from %ENV
111 def expand_environment_strings(s):
112 # we use a reverse sort so we do the longer ones first
113 for k in sorted(os.environ.keys(), reverse=True):
115 s = s.replace("$%s" % k, v)
119 def run_testsuite(envname, name, cmd, i, totalsuites):
120 pcap_file = setup_pcap(name)
122 subunit_ops.start_testsuite(name)
123 subunit_ops.progress_push()
124 subunit_ops.report_time(time.time())
126 exitcode = subprocess.call(cmd)
128 subunit_ops.report_time(time.time())
129 subunit_ops.progress_pop()
130 subunit_ops.progress_pop()
131 subunit_ops.end_testsuite(name, "error", "Unable to run %s: %s" % (cmd, e))
134 subunit_ops.report_time(time.time())
135 subunit_ops.progress_pop()
137 envlog = env_manager.getlog_env(envname)
139 sys.stdout.write("envlog: %s\n" % envlog)
141 sys.stdout.write("command: %s\n" % cmd)
142 sys.stdout.write("expanded command: %s\n" % expand_environment_strings(cmd))
145 subunit_ops.end_testsuite(name, "success")
147 subunit_ops.end_testsuite(name, "failure", "Exit code was %d" % exitcode)
149 cleanup_pcap(pcap_file, exitcode)
151 if not opts.socket_wrapper_keep_pcap and pcap_file is not None:
152 sys.stdout.write("PCAP FILE: %s\n" % pcap_file)
154 if exitcode != 0 and opts.one:
159 if opts.list and opts.testenv:
160 sys.stderr.write("--list and --testenv are mutually exclusive\n")
165 # quick hack to disable rpc validation when using valgrind - its way too slow
166 if not os.environ.get("VALGRIND"):
167 os.environ["VALIDATE"] = "validate"
168 os.environ["MALLOC_CHECK_"] = "2"
170 # make all our python scripts unbuffered
171 os.environ["PYTHONUNBUFFERED"] = "1"
173 bindir_abs = os.path.abspath(opts.bindir)
175 # Backwards compatibility:
176 if os.environ.get("TEST_LDAP") == "yes":
177 if os.environ.get("FEDORA_DS_ROOT"):
182 torture_maxtime = int(os.getenv("TORTURE_MAXTIME", "1200"))
187 prefix = os.path.normpath(opts.prefix)
190 raise Exception("using an empty prefix isn't allowed")
192 # Ensure we have the test prefix around.
194 # We need restrictive
195 # permissions on this as some subdirectories in this tree will have
196 # wider permissions (ie 0777) and this would allow other users on the
197 # host to subvert the test process.
198 if not os.path.isdir(prefix):
199 os.mkdir(prefix, 0700)
201 os.chmod(prefix, 0700)
203 prefix_abs = os.path.abspath(prefix)
204 tmpdir_abs = os.path.abspath(os.path.join(prefix, "tmp"))
205 if not os.path.isdir(tmpdir_abs):
206 os.mkdir(tmpdir_abs, 0777)
208 srcdir_abs = os.path.abspath(opts.srcdir)
211 raise Exception("using an empty absolute prefix isn't allowed")
212 if prefix_abs == "/":
213 raise Exception("using '/' as absolute prefix isn't allowed")
215 os.environ["PREFIX"] = prefix
216 os.environ["KRB5CCNAME"] = os.path.join(prefix, "krb5ticket")
217 os.environ["PREFIX_ABS"] = prefix_abs
218 os.environ["SRCDIR"] = opts.srcdir
219 os.environ["SRCDIR_ABS"] = srcdir_abs
220 os.environ["BINDIR"] = bindir_abs
222 tls_enabled = not opts.quick
224 os.environ["TLS_ENABLED"] = "yes"
226 os.environ["TLS_ENABLED"] = "no"
228 def prefix_pathvar(name, newpath):
229 if name in os.environ:
230 os.environ[name] = "%s:%s" % (newpath, os.environ[name])
232 os.environ[name] = newpath
233 prefix_pathvar("PKG_CONFIG_PATH", os.path.join(bindir_abs, "pkgconfig"))
234 prefix_pathvar("PYTHONPATH", os.path.join(bindir_abs, "python"))
236 if opts.socket_wrapper_keep_pcap:
237 # Socket wrapper keep pcap implies socket wrapper pcap
238 opts.socket_wrapper_pcap = True
240 if opts.socket_wrapper_pcap:
241 # Socket wrapper pcap implies socket wrapper
242 opts.socket_wrapper = True
244 if opts.socket_wrapper:
245 socket_wrapper_dir = socket_wrapper.setup_dir(os.path.join(prefix_abs, "w"), opts.socket_wrapper_pcap)
246 sys.stdout.write("SOCKET_WRAPPER_DIR=%s\n" % socket_wrapper_dir)
249 warnings.warn("not using socket wrapper, but also not running as root. Will not be able to listen on proper ports")
251 testenv_default = "none"
253 if opts.binary_mapping:
254 binary_mapping = dict([l.split(":") for l in opts.binary_mapping.split(",")])
255 os.environ["BINARY_MAPPING"] = opts.binary_mapping
258 os.environ["BINARY_MAPPING"] = ""
260 # After this many seconds, the server will self-terminate. All tests
261 # must terminate in this time, and testenv will only stay alive this
264 server_maxtime = 7500
265 if os.environ.get("SMBD_MAXTIME", ""):
266 server_maxtime = int(os.environ["SMBD_MAXTIME"])
269 def has_socket_wrapper(bindir):
271 subprocess.check_call([os.path.join(bindir, "smbd"), "-b"], stdout=f)
272 for l in f.readlines():
273 if "SOCKET_WRAPPER" in l:
279 if opts.target == "samba":
280 if opts.socket_wrapper and not has_socket_wrapper(opts.bindir):
281 sys.stderr.write("You must include --enable-socket-wrapper when compiling Samba in order to execute 'make test'. Exiting....\n")
283 testenv_default = "dc"
284 from selftest.target.samba import Samba
285 target = Samba(opts.bindir, binary_mapping, ldap, opts.srcdir, server_maxtime)
286 elif opts.target == "samba3":
287 if opts.socket_wrapper and not has_socket_wrapper(opts.bindir):
288 sys.stderr.write("You must include --enable-socket-wrapper when compiling Samba in order to execute 'make test'. Exiting....\n")
290 testenv_default = "member"
291 from selftest.target.samba3 import Samba3
292 target = Samba3(opts.bindir, binary_mapping, srcdir_abs, server_maxtime)
294 env_manager = EnvironmentManager(target)
296 interfaces = ",".join([
304 clientdir = os.path.join(prefix_abs, "client")
306 conffile = os.path.join(clientdir, "client.conf")
307 os.environ["SMB_CONF_PATH"] = conffile
309 def write_clientconf(conffile, clientdir, vars):
310 if not os.path.isdir(clientdir):
311 os.mkdir(clientdir, 0777)
313 for n in ["private", "lockdir", "statedir", "cachedir"]:
314 p = os.path.join(clientdir, n)
318 # this is ugly, but the ncalrpcdir needs exactly 0755
319 # otherwise tests fail.
320 mask = os.umask(0022)
322 for n in ["ncalrpcdir", "ncalrpcdir/np"]:
323 p = os.path.join(clientdir, n)
329 "netbios name": "client",
330 "private dir": os.path.join(clientdir, "private"),
331 "lock dir": os.path.join(clientdir, "lockdir"),
332 "state directory": os.path.join(clientdir, "statedir"),
333 "cache directory": os.path.join(clientdir, "cachedir"),
334 "ncalrpc dir": os.path.join(clientdir, "ncalrpcdir"),
335 "name resolve order": "file bcast",
336 "panic action": os.path.join(os.path.dirname(__file__), "gdb_backtrace \%d"),
338 "notify:inotify": "false",
339 "ldb:nosync": "true",
340 "system:anonymous": "true",
341 "client lanman auth": "Yes",
343 "torture:basedir": clientdir,
344 #We don't want to pass our self-tests if the PAC code is wrong
345 "gensec:require_pac": "true",
346 "resolv:host file": os.path.join(prefix_abs, "dns_host_file"),
347 #We don't want to run 'speed' tests for very long
348 "torture:timelimit": "1",
352 settings["workgroup"] = vars["DOMAIN"]
354 settings["realm"] = vars["REALM"]
355 if opts.socket_wrapper:
356 settings["interfaces"] = interfaces
358 f = open(conffile, 'w')
360 f.write("[global]\n")
361 for item in settings.iteritems():
362 f.write("\t%s = %s\n" % item)
369 sys.stderr.write("No testlists specified\n")
372 os.environ["SELFTEST_PREFIX"] = prefix_abs
373 os.environ["SELFTEST_TMPDIR"] = tmpdir_abs
374 os.environ["TEST_DATA_PREFIX"] = tmpdir_abs
375 if opts.socket_wrapper:
376 os.environ["SELFTEST_INTERFACES"] = interfaces
378 os.environ["SELFTEST_INTERFACES"] = ""
380 os.environ["SELFTEST_VERBOSE"] = "1"
382 os.environ["SELFTEST_VERBOSE"] = ""
384 os.environ["SELFTEST_QUICK"] = "1"
386 os.environ["SELFTEST_QUICK"] = ""
387 os.environ["SELFTEST_MAXTIME"] = str(torture_maxtime)
391 for testsuite in testlist.read_testlist(fn):
392 if not should_run_test(tests, testsuite):
395 if includes is not None and testlist.find_in_list(includes, name) is not None:
397 available.append(testsuite)
400 restricted_mgr = testlist.RestrictedTestManager.from_path(opts.load_list)
402 restricted_mgr = None
405 for testsuite in available:
407 skipreason = skip(name)
408 if restricted_mgr is not None:
409 match = restricted_mgr.should_run_testsuite(name)
414 if skipreason is not None:
416 subunit_ops.skip_testsuite(name, skipreason)
418 todo.append(testsuite + (match,))
420 if restricted_mgr is not None:
421 for name in restricted_mgr.iter_unused():
422 sys.stdout.write("No test or testsuite found matching %s\n" % name)
424 sys.stderr.write("No tests to run\n")
427 suitestotal = len(todo)
430 subunit_ops.progress(suitestotal)
431 subunit_ops.report_time(time.time())
440 # domain controller stuff
449 "MEMBER_NETBIOSNAME",
450 "MEMBER_NETBIOSALIAS",
452 # rpc proxy controller stuff
454 "RPC_PROXY_SERVER_IP",
455 "RPC_PROXY_NETBIOSNAME",
456 "RPC_PROXY_NETBIOSALIAS",
458 # domain controller stuff for Vampired DC
460 "VAMPIRE_DC_SERVER_IP",
461 "VAMPIRE_DC_NETBIOSNAME",
462 "VAMPIRE_DC_NETBIOSALIAS",
479 "WINBINDD_SOCKET_DIR",
480 "WINBINDD_PRIV_PIPE_DIR",
485 def handle_sigdie(signame):
486 env_manager.teardown_all()
487 sys.stderr.write("Received signal %s" % signame)
490 signal.signal(signal.SIGINT, handle_sigdie)
491 signal.signal(signal.SIGQUIT, handle_sigdie)
492 signal.signal(signal.SIGTERM, handle_sigdie)
494 def exported_envvars_str(testenv_vars):
497 for n in exported_envvars:
498 if not n in testenv_vars:
500 out += "%s=%s\n" % (n, testenv_vars[n])
505 def switch_env(name, prefix):
507 (envname, option) = name.split(":", 1)
512 env = env_manager.setup_env(envname, prefix)
514 testenv_vars = env.get_vars()
516 if option == "local":
517 socket_wrapper.set_default_iface(testenv_vars["SOCKET_WRAPPER_DEFAULT_IFACE"])
518 os.environ["SMB_CONF_PATH"] = testenv_vars["SERVERCONFFILE"]
519 elif option == "client":
520 socket_wrapper.set_default_iface(11)
521 write_clientconf(conffile, clientdir, testenv_vars)
522 os.environ["SMB_CONF_PATH"] = conffile
524 raise Exception("Unknown option[%s] for envname[%s]" % (option,
527 for name in exported_envvars:
528 if name in testenv_vars:
529 os.environ[name] = testenv_vars[name]
535 # This 'global' file needs to be empty when we start
536 os.unlink(os.path.join(prefix_abs, "dns_host_file"))
539 testenv_name = os.environ.get("SELFTEST_TESTENV", testenv_default)
541 testenv_vars = switch_env(testenv_name, prefix)
543 os.environ["PIDDIR"] = testenv_vars["PIDDIR"]
544 os.environ["ENVNAME"] = testenv_name
546 envvarstr = exported_envvars_str(testenv_vars)
548 term = os.environ.get("TERMINAL", "xterm -e")
550 Welcome to the Samba4 Test environment '%(testenv_name)'
552 This matches the client environment used in make test
553 server is pid `cat \$PIDDIR/samba.pid`
555 Some useful environment variables:
556 TORTURE_OPTIONS=\$TORTURE_OPTIONS
557 SMB_CONF_PATH=\$SMB_CONF_PATH
560 \" && LD_LIBRARY_PATH=%(LD_LIBRARY_PATH)s $(SHELL)'""" % {
561 "testenv_name": testenv_name,
562 "LD_LIBRARY_PATH": os.environ["LD_LIBRARY_PATH"]}
563 subprocess.call(term + ' ' + cmd)
564 env_manager.teardown_env(testenv_name)
566 for (name, envname, cmd, supports_loadfile, supports_idlist, subtests) in todo:
567 if not "$LISTOPT" in cmd:
568 warnings.warn("Unable to list tests in %s" % name)
571 cmd = cmd.replace("$LISTOPT", "--list")
573 exitcode = subprocess.call(cmd)
576 sys.stderr.write("%s exited with exit code %s\n" % (cmd, exitcode))
579 for (name, envname, cmd, supports_loadfile, supports_idlist, subtests) in todo:
581 envvars = switch_env(envname, prefix)
583 subunit_ops.start_testsuite(name);
584 subunit_ops.end_testsuite(name, "error",
585 "unable to set up environment %s" % envname);
588 subunit_ops.start_testsuite(name);
589 subunit_ops.end_testsuite(name, "skip",
590 "environment is unknown in this test backend - skipping" % envname)
593 # Generate a file with the individual tests to run, if the
594 # test runner for this test suite supports it.
595 if subtests is not None:
596 if supports_loadfile:
597 (fd, listid_file) = tempfile.mkstemp()
598 # FIXME: Remove tempfile afterwards
601 for test in subtests:
605 cmd = cmd.replace("$LOADLIST", "--load-list=%s" % listid_file)
606 elif supports_idlist:
607 cmd += " ".join(subtests)
609 run_testsuite(envname, name, cmd, i, suitestotal)
612 env_manager.teardown_env(envname)
614 sys.stdout.write("\n")
616 env_manager.teardown_all()
618 # if there were any valgrind failures, show them
619 for fn in os.listdir(prefix):
620 if fn.startswith("valgrind.log"):
621 sys.stdout.write("VALGRIND FAILURE\n")
622 f = open(os.path.join(prefix, fn), 'r')
624 sys.stdout.write(f.read())