]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/test/test_runner.py
3c79777f8f7df8aa1b26e6d4989f443099d23613
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / test / test_runner.py
1 import os.path, re, sys, subprocess
2 from cStringIO import StringIO
3
4 from twisted.trial import unittest
5
6 from twisted.python import usage, runtime
7 from twisted.internet import threads
8
9 from allmydata.util import fileutil, pollmixin
10 from allmydata.util.encodingutil import unicode_to_argv, unicode_to_output, get_filesystem_encoding
11 from allmydata.scripts import runner
12 from allmydata.client import Client
13 from allmydata.test import common_util
14 import allmydata
15
16
17 timeout = 240
18
19 def get_root_from_file(src):
20     srcdir = os.path.dirname(os.path.dirname(os.path.normcase(os.path.realpath(src))))
21
22     root = os.path.dirname(srcdir)
23     if os.path.basename(srcdir) == 'site-packages':
24         if re.search(r'python.+\..+', os.path.basename(root)):
25             root = os.path.dirname(root)
26         root = os.path.dirname(root)
27     elif os.path.basename(root) == 'src':
28         root = os.path.dirname(root)
29
30     return root
31
32 srcfile = allmydata.__file__
33 rootdir = get_root_from_file(srcfile)
34
35 if hasattr(sys, 'frozen'):
36     bintahoe = os.path.join(rootdir, 'tahoe')
37     if sys.platform == "win32" and os.path.exists(bintahoe + '.exe'):
38         bintahoe += '.exe'
39 else:
40     bintahoe = os.path.join(rootdir, 'bin', 'tahoe')
41     if sys.platform == "win32":
42         bintahoe += '.pyscript'
43         if not os.path.exists(bintahoe):
44             alt_bintahoe = os.path.join(rootdir, 'Scripts', 'tahoe.pyscript')
45             if os.path.exists(alt_bintahoe):
46                 bintahoe = alt_bintahoe
47
48
49 class RunBinTahoeMixin:
50     def skip_if_cannot_run_bintahoe(self):
51         if not os.path.exists(bintahoe):
52             raise unittest.SkipTest("The bin/tahoe script isn't to be found in the expected location (%s), and I don't want to test a 'tahoe' executable that I find somewhere else, in case it isn't the right executable for this version of Tahoe. Perhaps running 'setup.py build' again will help." % (bintahoe,))
53
54     def skip_if_cannot_daemonize(self):
55         self.skip_if_cannot_run_bintahoe()
56         if runtime.platformType == "win32":
57             # twistd on windows doesn't daemonize. cygwin should work normally.
58             raise unittest.SkipTest("twistd does not fork under windows")
59
60     def run_bintahoe(self, args, stdin=None, python_options=[], env=None):
61         self.skip_if_cannot_run_bintahoe()
62
63         if hasattr(sys, 'frozen'):
64             if python_options:
65                 raise unittest.SkipTest("This test doesn't apply to frozen builds.")
66             command = [bintahoe] + args
67         else:
68             command = [sys.executable] + python_options + [bintahoe] + args
69
70         if stdin is None:
71             stdin_stream = None
72         else:
73             stdin_stream = subprocess.PIPE
74
75         def _run():
76             p = subprocess.Popen(command, stdin=stdin_stream, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
77             (out, err) = p.communicate(stdin)
78             return (out, err, p.returncode)
79         return threads.deferToThread(_run)
80
81
82 class BinTahoe(common_util.SignalMixin, unittest.TestCase, RunBinTahoeMixin):
83     def _check_right_code(self, file_to_check):
84         root_to_check = get_root_from_file(file_to_check)
85         if os.path.basename(root_to_check) == 'dist':
86             root_to_check = os.path.dirname(root_to_check)
87
88         cwd = os.path.normcase(os.path.realpath("."))
89         root_from_cwd = os.path.dirname(cwd)
90         if os.path.basename(root_from_cwd) == 'src':
91             root_from_cwd = os.path.dirname(root_from_cwd)
92
93         # This is needed if we are running in a temporary directory created by 'make tmpfstest'.
94         if os.path.basename(root_from_cwd).startswith('tmp'):
95             root_from_cwd = os.path.dirname(root_from_cwd)
96
97         same = (root_from_cwd == root_to_check)
98         if not same:
99             try:
100                 same = os.path.samefile(root_from_cwd, root_to_check)
101             except AttributeError, e:
102                 e  # hush pyflakes
103
104         if not same:
105             msg = ("We seem to be testing the code at %r,\n"
106                    "(according to the source filename %r),\n"
107                    "but expected to be testing the code at %r.\n"
108                    % (root_to_check, file_to_check, root_from_cwd))
109
110             root_from_cwdu = os.path.dirname(os.path.normcase(os.path.normpath(os.getcwdu())))
111             if os.path.basename(root_from_cwdu) == u'src':
112                 root_from_cwdu = os.path.dirname(root_from_cwdu)
113
114             # This is needed if we are running in a temporary directory created by 'make tmpfstest'.
115             if os.path.basename(root_from_cwdu).startswith(u'tmp'):
116                 root_from_cwdu = os.path.dirname(root_from_cwdu)
117
118             if not isinstance(root_from_cwd, unicode) and root_from_cwd.decode(get_filesystem_encoding(), 'replace') != root_from_cwdu:
119                 msg += ("However, this may be a false alarm because the current directory path\n"
120                         "is not representable in the filesystem encoding. Please run the tests\n"
121                         "from the root of the Tahoe-LAFS distribution at a non-Unicode path.")
122                 raise unittest.SkipTest(msg)
123             else:
124                 msg += "Please run the tests from the root of the Tahoe-LAFS distribution."
125                 self.fail(msg)
126
127     def test_the_right_code(self):
128         self._check_right_code(srcfile)
129
130     def test_import_in_repl(self):
131         d = self.run_bintahoe(["debug", "repl"],
132                               stdin="import allmydata; print; print allmydata.__file__")
133         def _cb(res):
134             out, err, rc_or_sig = res
135             self.failUnlessEqual(rc_or_sig, 0, str(res))
136             lines = out.splitlines()
137             self.failUnlessIn('>>>', lines[0], str(res))
138             self._check_right_code(lines[1])
139         d.addCallback(_cb)
140         return d
141     # The timeout was exceeded on FreeStorm's CentOS5-i386.
142     test_import_in_repl.timeout = 480
143
144     def test_path(self):
145         d = self.run_bintahoe(["--version-and-path"])
146         def _cb(res):
147             from allmydata import normalized_version
148
149             out, err, rc_or_sig = res
150             self.failUnlessEqual(rc_or_sig, 0, str(res))
151
152             # Fail unless the __appname__ package is *this* version *and*
153             # was loaded from *this* source directory.
154
155             required_verstr = str(allmydata.__version__)
156
157             self.failIfEqual(required_verstr, "unknown",
158                              "We don't know our version, because this distribution didn't come "
159                              "with a _version.py and 'setup.py update_version' hasn't been run.")
160
161             srcdir = os.path.dirname(os.path.dirname(os.path.normcase(os.path.realpath(srcfile))))
162             info = repr((res, allmydata.__appname__, required_verstr, srcdir))
163
164             appverpath = out.split(')')[0]
165             (appverfull, path) = appverpath.split('] (')
166             (appver, comment) = appverfull.split(' [')
167             (branch, full_version) = comment.split(': ')
168             (app, ver) = appver.split(': ')
169
170             self.failUnlessEqual(app, allmydata.__appname__, info)
171             norm_ver = normalized_version(ver)
172             norm_required = normalized_version(required_verstr)
173             self.failUnlessEqual(norm_ver, norm_required, info)
174             self.failUnlessEqual(path, srcdir, info)
175             self.failUnlessEqual(branch, allmydata.branch)
176             self.failUnlessEqual(full_version, allmydata.full_version)
177         d.addCallback(_cb)
178         return d
179
180     def test_unicode_arguments_and_output(self):
181         self.skip_if_cannot_run_bintahoe()
182
183         tricky = u"\u2621"
184         try:
185             tricky_arg = unicode_to_argv(tricky, mangle=True)
186             tricky_out = unicode_to_output(tricky)
187         except UnicodeEncodeError:
188             raise unittest.SkipTest("A non-ASCII argument/output could not be encoded on this platform.")
189
190         d = self.run_bintahoe([tricky_arg])
191         def _cb(res):
192             out, err, rc_or_sig = res
193             self.failUnlessEqual(rc_or_sig, 1, str(res))
194             self.failUnlessIn("Unknown command: "+tricky_out, out)
195         d.addCallback(_cb)
196         return d
197
198     def test_run_with_python_options(self):
199         # -t is a harmless option that warns about tabs.
200         d = self.run_bintahoe(["--version"], python_options=["-t"])
201         def _cb(res):
202             out, err, rc_or_sig = res
203             self.failUnlessEqual(rc_or_sig, 0, str(res))
204             self.failUnless(out.startswith(allmydata.__appname__+':'), str(res))
205         d.addCallback(_cb)
206         return d
207
208     def test_version_no_noise(self):
209         self.skip_if_cannot_run_bintahoe()
210
211         d = self.run_bintahoe(["--version"])
212         def _cb(res):
213             out, err, rc_or_sig = res
214             self.failUnlessEqual(rc_or_sig, 0, str(res))
215             self.failUnless(out.startswith(allmydata.__appname__+':'), str(res))
216             self.failIfIn("DeprecationWarning", out, str(res))
217             errlines = err.split("\n")
218             self.failIf([True for line in errlines if (line != "" and "UserWarning: Unbuilt egg for setuptools" not in line
219                                                                   and "from pkg_resources import load_entry_point" not in line)], str(res))
220             if err != "":
221                 raise unittest.SkipTest("This test is known not to pass on Ubuntu Lucid; see #1235.")
222         d.addCallback(_cb)
223         return d
224
225
226 class CreateNode(unittest.TestCase):
227     # exercise "tahoe create-node", create-introducer,
228     # create-key-generator, and create-stats-gatherer, by calling the
229     # corresponding code as a subroutine.
230
231     def workdir(self, name):
232         basedir = os.path.join("test_runner", "CreateNode", name)
233         fileutil.make_dirs(basedir)
234         return basedir
235
236     def run_tahoe(self, argv):
237         out,err = StringIO(), StringIO()
238         rc = runner.runner(argv, stdout=out, stderr=err)
239         return rc, out.getvalue(), err.getvalue()
240
241     def do_create(self, kind):
242         basedir = self.workdir("test_" + kind)
243         command = "create-" + kind
244         is_client = kind in ("node", "client")
245         tac = is_client and "tahoe-client.tac" or ("tahoe-" + kind + ".tac")
246
247         n1 = os.path.join(basedir, command + "-n1")
248         argv = ["--quiet", command, "--basedir", n1]
249         rc, out, err = self.run_tahoe(argv)
250         self.failUnlessEqual(err, "")
251         self.failUnlessEqual(out, "")
252         self.failUnlessEqual(rc, 0)
253         self.failUnless(os.path.exists(n1))
254         self.failUnless(os.path.exists(os.path.join(n1, tac)))
255
256         if is_client:
257             # tahoe.cfg should exist, and should have storage enabled for
258             # 'create-node', and disabled for 'create-client'.
259             tahoe_cfg = os.path.join(n1, "tahoe.cfg")
260             self.failUnless(os.path.exists(tahoe_cfg))
261             content = fileutil.read(tahoe_cfg).replace('\r\n', '\n')
262             if kind == "client":
263                 self.failUnless(re.search(r"\n\[storage\]\n#.*\nenabled = false\n", content), content)
264             else:
265                 self.failUnless(re.search(r"\n\[storage\]\n#.*\nenabled = true\n", content), content)
266                 self.failUnless("\nreserved_space = 1G\n" in content)
267
268             self.failUnless(re.search(r"\n\[drop_upload\]\n#.*\nenabled = false\n", content), content)
269
270         # creating the node a second time should be rejected
271         rc, out, err = self.run_tahoe(argv)
272         self.failIfEqual(rc, 0, str((out, err, rc)))
273         self.failUnlessEqual(out, "")
274         self.failUnless("is not empty." in err)
275
276         # Fail if there is a non-empty line that doesn't end with a
277         # punctuation mark.
278         for line in err.splitlines():
279             self.failIf(re.search("[\S][^\.!?]$", line), (line,))
280
281         # test that the non --basedir form works too
282         n2 = os.path.join(basedir, command + "-n2")
283         argv = ["--quiet", command, n2]
284         rc, out, err = self.run_tahoe(argv)
285         self.failUnlessEqual(err, "")
286         self.failUnlessEqual(out, "")
287         self.failUnlessEqual(rc, 0)
288         self.failUnless(os.path.exists(n2))
289         self.failUnless(os.path.exists(os.path.join(n2, tac)))
290
291         # test the --node-directory form
292         n3 = os.path.join(basedir, command + "-n3")
293         argv = ["--quiet", "--node-directory", n3, command]
294         rc, out, err = self.run_tahoe(argv)
295         self.failUnlessEqual(err, "")
296         self.failUnlessEqual(out, "")
297         self.failUnlessEqual(rc, 0)
298         self.failUnless(os.path.exists(n3))
299         self.failUnless(os.path.exists(os.path.join(n3, tac)))
300
301         # make sure it rejects too many arguments
302         argv = [command, "basedir", "extraarg"]
303         self.failUnlessRaises(usage.UsageError,
304                               runner.runner, argv,
305                               run_by_human=False)
306
307         # when creating a non-client, there is no default for the basedir
308         if not is_client:
309             argv = [command]
310             self.failUnlessRaises(usage.UsageError,
311                                   runner.runner, argv,
312                                   run_by_human=False)
313
314
315     def test_node(self):
316         self.do_create("node")
317
318     def test_client(self):
319         # create-client should behave like create-node --no-storage.
320         self.do_create("client")
321
322     def test_introducer(self):
323         self.do_create("introducer")
324
325     def test_key_generator(self):
326         self.do_create("key-generator")
327
328     def test_stats_gatherer(self):
329         self.do_create("stats-gatherer")
330
331     def test_subcommands(self):
332         # no arguments should trigger a command listing, via UsageError
333         self.failUnlessRaises(usage.UsageError,
334                               runner.runner,
335                               [],
336                               run_by_human=False)
337
338
339 class RunNode(common_util.SignalMixin, unittest.TestCase, pollmixin.PollMixin,
340               RunBinTahoeMixin):
341     # exercise "tahoe start", for both introducer, client node, and
342     # key-generator, by spawning "tahoe start" as a subprocess. This doesn't
343     # get us figleaf-based line-level coverage, but it does a better job of
344     # confirming that the user can actually run "./bin/tahoe start" and
345     # expect it to work. This verifies that bin/tahoe sets up PYTHONPATH and
346     # the like correctly.
347
348     # This doesn't work on cygwin (it hangs forever), so we skip this test
349     # when we're on cygwin. It is likely that "tahoe start" itself doesn't
350     # work on cygwin: twisted seems unable to provide a version of
351     # spawnProcess which really works there.
352
353     def workdir(self, name):
354         basedir = os.path.join("test_runner", "RunNode", name)
355         fileutil.make_dirs(basedir)
356         return basedir
357
358     def test_introducer(self):
359         self.skip_if_cannot_daemonize()
360
361         basedir = self.workdir("test_introducer")
362         c1 = os.path.join(basedir, "c1")
363         exit_trigger_file = os.path.join(c1, Client.EXIT_TRIGGER_FILE)
364         twistd_pid_file = os.path.join(c1, "twistd.pid")
365         introducer_furl_file = os.path.join(c1, "private", "introducer.furl")
366         portnum_file = os.path.join(c1, "introducer.port")
367         node_url_file = os.path.join(c1, "node.url")
368         config_file = os.path.join(c1, "tahoe.cfg")
369
370         d = self.run_bintahoe(["--quiet", "create-introducer", "--basedir", c1])
371         def _cb(res):
372             out, err, rc_or_sig = res
373             self.failUnlessEqual(rc_or_sig, 0)
374
375             # This makes sure that node.url is written, which allows us to
376             # detect when the introducer restarts in _node_has_restarted below.
377             config = fileutil.read(config_file)
378             self.failUnlessIn('\nweb.port = \n', config)
379             fileutil.write(config_file, config.replace('\nweb.port = \n', '\nweb.port = 0\n'))
380
381             # by writing this file, we get ten seconds before the node will
382             # exit. This insures that even if the test fails (and the 'stop'
383             # command doesn't work), the client should still terminate.
384             fileutil.write(exit_trigger_file, "")
385             # now it's safe to start the node
386         d.addCallback(_cb)
387
388         def _then_start_the_node(res):
389             return self.run_bintahoe(["--quiet", "start", c1])
390         d.addCallback(_then_start_the_node)
391
392         def _cb2(res):
393             out, err, rc_or_sig = res
394
395             fileutil.write(exit_trigger_file, "")
396             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
397             self.failUnlessEqual(rc_or_sig, 0, errstr)
398             self.failUnlessEqual(out, "", errstr)
399             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
400
401             # the parent (twistd) has exited. However, twistd writes the pid
402             # from the child, not the parent, so we can't expect twistd.pid
403             # to exist quite yet.
404
405             # the node is running, but it might not have made it past the
406             # first reactor turn yet, and if we kill it too early, it won't
407             # remove the twistd.pid file. So wait until it does something
408             # that we know it won't do until after the first turn.
409         d.addCallback(_cb2)
410
411         def _node_has_started():
412             return os.path.exists(introducer_furl_file)
413         d.addCallback(lambda res: self.poll(_node_has_started))
414
415         def _started(res):
416             # read the introducer.furl and introducer.port files so we can
417             # check that their contents don't change on restart
418             self.furl = fileutil.read(introducer_furl_file)
419             self.failUnless(os.path.exists(portnum_file))
420             self.portnum = fileutil.read(portnum_file)
421
422             fileutil.write(exit_trigger_file, "")
423             self.failUnless(os.path.exists(twistd_pid_file))
424             self.failUnless(os.path.exists(node_url_file))
425
426             # rm this so we can detect when the second incarnation is ready
427             os.unlink(node_url_file)
428             return self.run_bintahoe(["--quiet", "restart", c1])
429         d.addCallback(_started)
430
431         def _then(res):
432             out, err, rc_or_sig = res
433             fileutil.write(exit_trigger_file, "")
434             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
435             self.failUnlessEqual(rc_or_sig, 0, errstr)
436             self.failUnlessEqual(out, "", errstr)
437             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
438         d.addCallback(_then)
439
440         # Again, the second incarnation of the node might not be ready yet,
441         # so poll until it is. This time introducer_furl_file already
442         # exists, so we check for the existence of node_url_file instead.
443         def _node_has_restarted():
444             return os.path.exists(node_url_file) and os.path.exists(portnum_file)
445         d.addCallback(lambda res: self.poll(_node_has_restarted))
446
447         def _check_same_furl_and_port(res):
448             self.failUnless(os.path.exists(introducer_furl_file))
449             self.failUnlessEqual(self.furl, fileutil.read(introducer_furl_file))
450             self.failUnlessEqual(self.portnum, fileutil.read(portnum_file))
451         d.addCallback(_check_same_furl_and_port)
452
453         # Now we can kill it. TODO: On a slow machine, the node might kill
454         # itself before we get a chance to, especially if spawning the
455         # 'tahoe stop' command takes a while.
456         def _stop(res):
457             fileutil.write(exit_trigger_file, "")
458             self.failUnless(os.path.exists(twistd_pid_file))
459
460             return self.run_bintahoe(["--quiet", "stop", c1])
461         d.addCallback(_stop)
462
463         def _after_stopping(res):
464             out, err, rc_or_sig = res
465             fileutil.write(exit_trigger_file, "")
466             # the parent has exited by now
467             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
468             self.failUnlessEqual(rc_or_sig, 0, errstr)
469             self.failUnlessEqual(out, "", errstr)
470             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
471             # the parent was supposed to poll and wait until it sees
472             # twistd.pid go away before it exits, so twistd.pid should be
473             # gone by now.
474             self.failIf(os.path.exists(twistd_pid_file))
475         d.addCallback(_after_stopping)
476         d.addBoth(self._remove, exit_trigger_file)
477         return d
478     # This test has hit a 240-second timeout on our feisty2.5 buildslave, and a 480-second timeout
479     # on Francois's Lenny-armv5tel buildslave.
480     test_introducer.timeout = 960
481
482     def test_client_no_noise(self):
483         self.skip_if_cannot_daemonize()
484
485         basedir = self.workdir("test_client_no_noise")
486         c1 = os.path.join(basedir, "c1")
487         exit_trigger_file = os.path.join(c1, Client.EXIT_TRIGGER_FILE)
488         twistd_pid_file = os.path.join(c1, "twistd.pid")
489         portnum_file = os.path.join(c1, "client.port")
490
491         d = self.run_bintahoe(["--quiet", "create-client", "--basedir", c1, "--webport", "0"])
492         def _cb(res):
493             out, err, rc_or_sig = res
494             errstr = "cc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
495             assert rc_or_sig == 0, errstr
496             self.failUnlessEqual(rc_or_sig, 0)
497
498             # By writing this file, we get two minutes before the client will exit. This ensures
499             # that even if the 'stop' command doesn't work (and the test fails), the client should
500             # still terminate.
501             fileutil.write(exit_trigger_file, "")
502             # now it's safe to start the node
503         d.addCallback(_cb)
504
505         def _start(res):
506             return self.run_bintahoe(["--quiet", "start", c1])
507         d.addCallback(_start)
508
509         def _cb2(res):
510             out, err, rc_or_sig = res
511             errstr = "cc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
512             fileutil.write(exit_trigger_file, "")
513             self.failUnlessEqual(rc_or_sig, 0, errstr)
514             self.failUnlessEqual(out, "", errstr) # If you emit noise, you fail this test.
515             errlines = err.split("\n")
516             self.failIf([True for line in errlines if (line != "" and "UserWarning: Unbuilt egg for setuptools" not in line
517                                                                   and "from pkg_resources import load_entry_point" not in line)], errstr)
518             if err != "":
519                 raise unittest.SkipTest("This test is known not to pass on Ubuntu Lucid; see #1235.")
520
521             # the parent (twistd) has exited. However, twistd writes the pid
522             # from the child, not the parent, so we can't expect twistd.pid
523             # to exist quite yet.
524
525             # the node is running, but it might not have made it past the
526             # first reactor turn yet, and if we kill it too early, it won't
527             # remove the twistd.pid file. So wait until it does something
528             # that we know it won't do until after the first turn.
529         d.addCallback(_cb2)
530
531         def _node_has_started():
532             return os.path.exists(portnum_file)
533         d.addCallback(lambda res: self.poll(_node_has_started))
534
535         # now we can kill it. TODO: On a slow machine, the node might kill
536         # itself before we get a chance to, especially if spawning the
537         # 'tahoe stop' command takes a while.
538         def _stop(res):
539             self.failUnless(os.path.exists(twistd_pid_file),
540                             (twistd_pid_file, os.listdir(os.path.dirname(twistd_pid_file))))
541             return self.run_bintahoe(["--quiet", "stop", c1])
542         d.addCallback(_stop)
543         d.addBoth(self._remove, exit_trigger_file)
544         return d
545
546     def test_client(self):
547         self.skip_if_cannot_daemonize()
548
549         basedir = self.workdir("test_client")
550         c1 = os.path.join(basedir, "c1")
551         exit_trigger_file = os.path.join(c1, Client.EXIT_TRIGGER_FILE)
552         twistd_pid_file = os.path.join(c1, "twistd.pid")
553         portnum_file = os.path.join(c1, "client.port")
554         node_url_file = os.path.join(c1, "node.url")
555         config_file = os.path.join(c1, "tahoe.cfg")
556
557         d = self.run_bintahoe(["--quiet", "create-node", "--basedir", c1, "--webport", "0"])
558         def _cb(res):
559             out, err, rc_or_sig = res
560             self.failUnlessEqual(rc_or_sig, 0)
561
562             # Check that the --webport option worked.
563             config = fileutil.read(config_file)
564             self.failUnlessIn('\nweb.port = 0\n', config)
565
566             # By writing this file, we get two minutes before the client will exit. This ensures
567             # that even if the 'stop' command doesn't work (and the test fails), the client should
568             # still terminate.
569             fileutil.write(exit_trigger_file, "")
570             # now it's safe to start the node
571         d.addCallback(_cb)
572
573         def _start(res):
574             return self.run_bintahoe(["--quiet", "start", c1])
575         d.addCallback(_start)
576
577         def _cb2(res):
578             out, err, rc_or_sig = res
579             fileutil.write(exit_trigger_file, "")
580             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
581             self.failUnlessEqual(rc_or_sig, 0, errstr)
582             self.failUnlessEqual(out, "", errstr)
583             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
584
585             # the parent (twistd) has exited. However, twistd writes the pid
586             # from the child, not the parent, so we can't expect twistd.pid
587             # to exist quite yet.
588
589             # the node is running, but it might not have made it past the
590             # first reactor turn yet, and if we kill it too early, it won't
591             # remove the twistd.pid file. So wait until it does something
592             # that we know it won't do until after the first turn.
593         d.addCallback(_cb2)
594
595         def _node_has_started():
596             # this depends upon both files being created atomically
597             return os.path.exists(node_url_file) and os.path.exists(portnum_file)
598         d.addCallback(lambda res: self.poll(_node_has_started))
599
600         def _started(res):
601             # read the client.port file so we can check that its contents
602             # don't change on restart
603             self.portnum = fileutil.read(portnum_file)
604
605             fileutil.write(exit_trigger_file, "")
606             self.failUnless(os.path.exists(twistd_pid_file))
607
608             # rm this so we can detect when the second incarnation is ready
609             os.unlink(node_url_file)
610             return self.run_bintahoe(["--quiet", "restart", c1])
611         d.addCallback(_started)
612
613         def _cb3(res):
614             out, err, rc_or_sig = res
615
616             fileutil.write(exit_trigger_file, "")
617             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
618             self.failUnlessEqual(rc_or_sig, 0, errstr)
619             self.failUnlessEqual(out, "", errstr)
620             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
621         d.addCallback(_cb3)
622
623         # again, the second incarnation of the node might not be ready yet,
624         # so poll until it is
625         d.addCallback(lambda res: self.poll(_node_has_started))
626
627         def _check_same_port(res):
628             self.failUnlessEqual(self.portnum, fileutil.read(portnum_file))
629         d.addCallback(_check_same_port)
630
631         # now we can kill it. TODO: On a slow machine, the node might kill
632         # itself before we get a chance to, especially if spawning the
633         # 'tahoe stop' command takes a while.
634         def _stop(res):
635             fileutil.write(exit_trigger_file, "")
636             self.failUnless(os.path.exists(twistd_pid_file),
637                             (twistd_pid_file, os.listdir(os.path.dirname(twistd_pid_file))))
638             return self.run_bintahoe(["--quiet", "stop", c1])
639         d.addCallback(_stop)
640
641         def _cb4(res):
642             out, err, rc_or_sig = res
643
644             fileutil.write(exit_trigger_file, "")
645             # the parent has exited by now
646             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
647             self.failUnlessEqual(rc_or_sig, 0, errstr)
648             self.failUnlessEqual(out, "", errstr)
649             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
650             # the parent was supposed to poll and wait until it sees
651             # twistd.pid go away before it exits, so twistd.pid should be
652             # gone by now.
653             self.failIf(os.path.exists(twistd_pid_file))
654         d.addCallback(_cb4)
655         d.addBoth(self._remove, exit_trigger_file)
656         return d
657
658     def _remove(self, res, file):
659         fileutil.remove(file)
660         return res
661
662     def test_baddir(self):
663         self.skip_if_cannot_daemonize()
664         basedir = self.workdir("test_baddir")
665         fileutil.make_dirs(basedir)
666
667         d = self.run_bintahoe(["--quiet", "start", "--basedir", basedir])
668         def _cb(res):
669             out, err, rc_or_sig = res
670             self.failUnlessEqual(rc_or_sig, 1)
671             self.failUnless("is not a recognizable node directory" in err, err)
672         d.addCallback(_cb)
673
674         def _then_stop_it(res):
675             return self.run_bintahoe(["--quiet", "stop", "--basedir", basedir])
676         d.addCallback(_then_stop_it)
677
678         def _cb2(res):
679             out, err, rc_or_sig = res
680             self.failUnlessEqual(rc_or_sig, 2)
681             self.failUnless("does not look like a running node directory" in err)
682         d.addCallback(_cb2)
683
684         def _then_start_in_bogus_basedir(res):
685             not_a_dir = os.path.join(basedir, "bogus")
686             return self.run_bintahoe(["--quiet", "start", "--basedir", not_a_dir])
687         d.addCallback(_then_start_in_bogus_basedir)
688
689         def _cb3(res):
690             out, err, rc_or_sig = res
691             self.failUnlessEqual(rc_or_sig, 1)
692             self.failUnlessIn("does not look like a directory at all", err)
693         d.addCallback(_cb3)
694         return d
695
696     def test_keygen(self):
697         self.skip_if_cannot_daemonize()
698
699         basedir = self.workdir("test_keygen")
700         c1 = os.path.join(basedir, "c1")
701         twistd_pid_file = os.path.join(c1, "twistd.pid")
702         keygen_furl_file = os.path.join(c1, "key_generator.furl")
703
704         d = self.run_bintahoe(["--quiet", "create-key-generator", "--basedir", c1])
705         def _cb(res):
706             out, err, rc_or_sig = res
707             self.failUnlessEqual(rc_or_sig, 0)
708         d.addCallback(_cb)
709
710         def _start(res):
711             return self.run_bintahoe(["--quiet", "start", c1])
712         d.addCallback(_start)
713
714         def _cb2(res):
715             out, err, rc_or_sig = res
716             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
717             self.failUnlessEqual(rc_or_sig, 0, errstr)
718             self.failUnlessEqual(out, "", errstr)
719             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
720
721             # the parent (twistd) has exited. However, twistd writes the pid
722             # from the child, not the parent, so we can't expect twistd.pid
723             # to exist quite yet.
724
725             # the node is running, but it might not have made it past the
726             # first reactor turn yet, and if we kill it too early, it won't
727             # remove the twistd.pid file. So wait until it does something
728             # that we know it won't do until after the first turn.
729         d.addCallback(_cb2)
730
731         def _node_has_started():
732             return os.path.exists(keygen_furl_file)
733         d.addCallback(lambda res: self.poll(_node_has_started))
734
735         def _started(res):
736             self.failUnless(os.path.exists(twistd_pid_file))
737             # rm this so we can detect when the second incarnation is ready
738             os.unlink(keygen_furl_file)
739             return self.run_bintahoe(["--quiet", "restart", c1])
740         d.addCallback(_started)
741
742         def _cb3(res):
743             out, err, rc_or_sig = res
744             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
745             self.failUnlessEqual(rc_or_sig, 0, errstr)
746             self.failUnlessEqual(out, "", errstr)
747             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
748         d.addCallback(_cb3)
749
750         # again, the second incarnation of the node might not be ready yet,
751         # so poll until it is
752         d.addCallback(lambda res: self.poll(_node_has_started))
753
754         # now we can kill it. TODO: On a slow machine, the node might kill
755         # itself before we get a chance too, especially if spawning the
756         # 'tahoe stop' command takes a while.
757         def _stop(res):
758             self.failUnless(os.path.exists(twistd_pid_file))
759             return self.run_bintahoe(["--quiet", "stop", c1])
760         d.addCallback(_stop)
761
762         def _cb4(res):
763             out, err, rc_or_sig = res
764             # the parent has exited by now
765             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
766             self.failUnlessEqual(rc_or_sig, 0, errstr)
767             self.failUnlessEqual(out, "", errstr)
768             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
769             # the parent was supposed to poll and wait until it sees
770             # twistd.pid go away before it exits, so twistd.pid should be
771             # gone by now.
772             self.failIf(os.path.exists(twistd_pid_file))
773         d.addCallback(_cb4)
774         return d