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