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