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