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