]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/test/test_runner.py
tests: use verlib to compare versions, and get the versions of Twisted and Nevow...
[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             from allmydata import normalized_version
137
138             out, err, rc_or_sig = res
139             self.failUnlessEqual(rc_or_sig, 0, str(res))
140
141             # Fail unless the allmydata-tahoe package is *this* version *and*
142             # was loaded from *this* source directory.
143
144             required_verstr = str(allmydata.__version__)
145
146             self.failIfEqual(required_verstr, "unknown",
147                              "We don't know our version, because this distribution didn't come "
148                              "with a _version.py and 'setup.py darcsver' hasn't been run.")
149
150             srcdir = os.path.dirname(os.path.dirname(os.path.normcase(os.path.realpath(srcfile))))
151             info = (res, allmydata.__appname__, required_verstr, srcdir)
152
153             appverpath = out.split(')')[0]
154             (appver, path) = appverpath.split(' (')
155             (app, ver) = appver.split(': ')
156
157             self.failUnlessEqual(app, allmydata.__appname__, info)
158             self.failUnlessEqual(normalized_version(ver), normalized_version(required_verstr), info)
159             self.failUnlessEqual(path, srcdir, info)
160         d.addCallback(_cb)
161         return d
162
163     def test_unicode_arguments_and_output(self):
164         self.skip_if_cannot_run_bintahoe()
165
166         tricky = u"\u2621"
167         try:
168             tricky_arg = unicode_to_argv(tricky, mangle=True)
169             tricky_out = unicode_to_output(tricky)
170         except UnicodeEncodeError:
171             raise unittest.SkipTest("A non-ASCII argument/output could not be encoded on this platform.")
172
173         d = self.run_bintahoe([tricky_arg])
174         def _cb(res):
175             out, err, rc_or_sig = res
176             self.failUnlessEqual(rc_or_sig, 1, str(res))
177             self.failUnlessIn("Unknown command: "+tricky_out, out)
178         d.addCallback(_cb)
179         return d
180
181     def test_run_with_python_options(self):
182         # -t is a harmless option that warns about tabs.
183         d = self.run_bintahoe(["--version"], python_options=["-t"])
184         def _cb(res):
185             out, err, rc_or_sig = res
186             self.failUnlessEqual(rc_or_sig, 0, str(res))
187             self.failUnless(out.startswith(allmydata.__appname__+':'), str(res))
188         d.addCallback(_cb)
189         return d
190
191     def test_version_no_noise(self):
192         self.skip_if_cannot_run_bintahoe()
193
194         from allmydata import get_package_versions, normalized_version
195         twisted_ver = get_package_versions()['Twisted']
196
197         if not normalized_version(twisted_ver) >= normalized_version('9.0.0'):
198             raise unittest.SkipTest("We pass this test only with Twisted >= v9.0.0")
199
200         d = self.run_bintahoe(["--version"])
201         def _cb(res):
202             out, err, rc_or_sig = res
203             self.failUnlessEqual(rc_or_sig, 0, str(res))
204             self.failUnless(out.startswith(allmydata.__appname__+':'), str(res))
205             self.failIfIn("DeprecationWarning", out, str(res))
206             errlines = err.split("\n")
207             self.failIf([True for line in errlines if (line != "" and "UserWarning: Unbuilt egg for setuptools" not in line
208                                                                   and "from pkg_resources import load_entry_point" not in line)], str(res))
209             if err != "":
210                 raise unittest.SkipTest("This test is known not to pass on Ubuntu Lucid; see #1235.")
211         d.addCallback(_cb)
212         return d
213
214
215 class CreateNode(unittest.TestCase):
216     # exercise "tahoe create-node", create-introducer,
217     # create-key-generator, and create-stats-gatherer, by calling the
218     # corresponding code as a subroutine.
219
220     def workdir(self, name):
221         basedir = os.path.join("test_runner", "CreateNode", name)
222         fileutil.make_dirs(basedir)
223         return basedir
224
225     def run_tahoe(self, argv):
226         out,err = StringIO(), StringIO()
227         rc = runner.runner(argv, stdout=out, stderr=err)
228         return rc, out.getvalue(), err.getvalue()
229
230     def do_create(self, kind):
231         basedir = self.workdir("test_" + kind)
232         command = "create-" + kind
233         is_client = kind in ("node", "client")
234         tac = is_client and "tahoe-client.tac" or ("tahoe-" + kind + ".tac")
235
236         n1 = os.path.join(basedir, command + "-n1")
237         argv = ["--quiet", command, "--basedir", n1]
238         rc, out, err = self.run_tahoe(argv)
239         self.failUnlessEqual(err, "")
240         self.failUnlessEqual(out, "")
241         self.failUnlessEqual(rc, 0)
242         self.failUnless(os.path.exists(n1))
243         self.failUnless(os.path.exists(os.path.join(n1, tac)))
244
245         if is_client:
246             # tahoe.cfg should exist, and should have storage enabled for
247             # 'create-node', and disabled for 'create-client'.
248             tahoe_cfg = os.path.join(n1, "tahoe.cfg")
249             self.failUnless(os.path.exists(tahoe_cfg))
250             content = open(tahoe_cfg).read()
251             if kind == "client":
252                 self.failUnless(re.search(r"\n\[storage\]\n#.*\nenabled = false\n", content), content)
253             else:
254                 self.failUnless(re.search(r"\n\[storage\]\n#.*\nenabled = true\n", content), content)
255                 self.failUnless("\nreserved_space = 1G\n" in content)
256
257         # creating the node a second time should be rejected
258         rc, out, err = self.run_tahoe(argv)
259         self.failIfEqual(rc, 0, str((out, err, rc)))
260         self.failUnlessEqual(out, "")
261         self.failUnless("is not empty." in err)
262
263         # Fail if there is a non-empty line that doesn't end with a
264         # punctuation mark.
265         for line in err.splitlines():
266             self.failIf(re.search("[\S][^\.!?]$", line), (line,))
267
268         # test that the non --basedir form works too
269         n2 = os.path.join(basedir, command + "-n2")
270         argv = ["--quiet", command, n2]
271         rc, out, err = self.run_tahoe(argv)
272         self.failUnlessEqual(err, "")
273         self.failUnlessEqual(out, "")
274         self.failUnlessEqual(rc, 0)
275         self.failUnless(os.path.exists(n2))
276         self.failUnless(os.path.exists(os.path.join(n2, tac)))
277
278         # test the --node-directory form
279         n3 = os.path.join(basedir, command + "-n3")
280         argv = ["--quiet", command, "--node-directory", n3]
281         rc, out, err = self.run_tahoe(argv)
282         self.failUnlessEqual(err, "")
283         self.failUnlessEqual(out, "")
284         self.failUnlessEqual(rc, 0)
285         self.failUnless(os.path.exists(n3))
286         self.failUnless(os.path.exists(os.path.join(n3, tac)))
287
288         # make sure it rejects too many arguments
289         argv = [command, "basedir", "extraarg"]
290         self.failUnlessRaises(usage.UsageError,
291                               runner.runner, argv,
292                               run_by_human=False)
293
294         # when creating a non-client, there is no default for the basedir
295         if not is_client:
296             argv = [command]
297             self.failUnlessRaises(usage.UsageError,
298                                   runner.runner, argv,
299                                   run_by_human=False)
300
301
302     def test_node(self):
303         self.do_create("node")
304
305     def test_client(self):
306         # create-client should behave like create-node --no-storage.
307         self.do_create("client")
308
309     def test_introducer(self):
310         self.do_create("introducer")
311
312     def test_key_generator(self):
313         self.do_create("key-generator")
314
315     def test_stats_gatherer(self):
316         self.do_create("stats-gatherer")
317
318     def test_subcommands(self):
319         # no arguments should trigger a command listing, via UsageError
320         self.failUnlessRaises(usage.UsageError,
321                               runner.runner,
322                               [],
323                               run_by_human=False)
324
325
326 class RunNode(common_util.SignalMixin, unittest.TestCase, pollmixin.PollMixin,
327               RunBinTahoeMixin):
328     # exercise "tahoe start", for both introducer, client node, and
329     # key-generator, by spawning "tahoe start" as a subprocess. This doesn't
330     # get us figleaf-based line-level coverage, but it does a better job of
331     # confirming that the user can actually run "./bin/tahoe start" and
332     # expect it to work. This verifies that bin/tahoe sets up PYTHONPATH and
333     # the like correctly.
334
335     # This doesn't work on cygwin (it hangs forever), so we skip this test
336     # when we're on cygwin. It is likely that "tahoe start" itself doesn't
337     # work on cygwin: twisted seems unable to provide a version of
338     # spawnProcess which really works there.
339
340     def workdir(self, name):
341         basedir = os.path.join("test_runner", "RunNode", name)
342         fileutil.make_dirs(basedir)
343         return basedir
344
345     def test_introducer(self):
346         self.skip_if_cannot_daemonize()
347         basedir = self.workdir("test_introducer")
348         c1 = os.path.join(basedir, "c1")
349         HOTLINE_FILE = os.path.join(c1, "suicide_prevention_hotline")
350         TWISTD_PID_FILE = os.path.join(c1, "twistd.pid")
351         INTRODUCER_FURL_FILE = os.path.join(c1, "introducer.furl")
352
353         d = self.run_bintahoe(["--quiet", "create-introducer", "--basedir", c1])
354         def _cb(res):
355             out, err, rc_or_sig = res
356             self.failUnlessEqual(rc_or_sig, 0)
357             # by writing this file, we get ten seconds before the node will
358             # exit. This insures that even if the test fails (and the 'stop'
359             # command doesn't work), the client should still terminate.
360             open(HOTLINE_FILE, "w").write("")
361             # now it's safe to start the node
362         d.addCallback(_cb)
363
364         def _then_start_the_node(res):
365             return self.run_bintahoe(["--quiet", "start", c1])
366         d.addCallback(_then_start_the_node)
367
368         def _cb2(res):
369             out, err, rc_or_sig = res
370
371             open(HOTLINE_FILE, "w").write("")
372             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
373             self.failUnlessEqual(rc_or_sig, 0, errstr)
374             self.failUnlessEqual(out, "", errstr)
375             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
376
377             # the parent (twistd) has exited. However, twistd writes the pid
378             # from the child, not the parent, so we can't expect twistd.pid
379             # to exist quite yet.
380
381             # the node is running, but it might not have made it past the
382             # first reactor turn yet, and if we kill it too early, it won't
383             # remove the twistd.pid file. So wait until it does something
384             # that we know it won't do until after the first turn.
385         d.addCallback(_cb2)
386
387         def _node_has_started():
388             return os.path.exists(INTRODUCER_FURL_FILE)
389         d.addCallback(lambda res: self.poll(_node_has_started))
390
391         def _started(res):
392             open(HOTLINE_FILE, "w").write("")
393             self.failUnless(os.path.exists(TWISTD_PID_FILE))
394             # rm this so we can detect when the second incarnation is ready
395             os.unlink(INTRODUCER_FURL_FILE)
396             return self.run_bintahoe(["--quiet", "restart", c1])
397         d.addCallback(_started)
398
399         def _then(res):
400             out, err, rc_or_sig = res
401             open(HOTLINE_FILE, "w").write("")
402             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
403             self.failUnlessEqual(rc_or_sig, 0, errstr)
404             self.failUnlessEqual(out, "", errstr)
405             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
406         d.addCallback(_then)
407
408         # again, the second incarnation of the node might not be ready yet,
409         # so poll until it is
410         d.addCallback(lambda res: self.poll(_node_has_started))
411
412         # now we can kill it. TODO: On a slow machine, the node might kill
413         # itself before we get a chance too, especially if spawning the
414         # 'tahoe stop' command takes a while.
415         def _stop(res):
416             open(HOTLINE_FILE, "w").write("")
417             self.failUnless(os.path.exists(TWISTD_PID_FILE))
418
419             return self.run_bintahoe(["--quiet", "stop", c1])
420         d.addCallback(_stop)
421
422         def _after_stopping(res):
423             out, err, rc_or_sig = res
424             open(HOTLINE_FILE, "w").write("")
425             # the parent has exited by now
426             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
427             self.failUnlessEqual(rc_or_sig, 0, errstr)
428             self.failUnlessEqual(out, "", errstr)
429             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
430             # the parent was supposed to poll and wait until it sees
431             # twistd.pid go away before it exits, so twistd.pid should be
432             # gone by now.
433             self.failIf(os.path.exists(TWISTD_PID_FILE))
434         d.addCallback(_after_stopping)
435
436         def _remove_hotline(res):
437             os.unlink(HOTLINE_FILE)
438             return res
439         d.addBoth(_remove_hotline)
440         return d
441     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
442
443     def test_client_no_noise(self):
444         self.skip_if_cannot_daemonize()
445
446         from allmydata import get_package_versions, normalized_version
447         twisted_ver = get_package_versions()['Twisted']
448
449         if not normalized_version(twisted_ver) >= normalized_version('9.0.0'):
450             raise unittest.SkipTest("We pass this test only with Twisted >= v9.0.0")
451
452         basedir = self.workdir("test_client_no_noise")
453         c1 = os.path.join(basedir, "c1")
454         HOTLINE_FILE = os.path.join(c1, "suicide_prevention_hotline")
455         TWISTD_PID_FILE = os.path.join(c1, "twistd.pid")
456         PORTNUMFILE = os.path.join(c1, "client.port")
457
458         d = self.run_bintahoe(["--quiet", "create-client", "--basedir", c1, "--webport", "0"])
459         def _cb(res):
460             out, err, rc_or_sig = res
461             errstr = "cc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
462             assert rc_or_sig == 0, errstr
463             self.failUnlessEqual(rc_or_sig, 0)
464             # By writing this file, we get forty seconds before the client will exit. This insures
465             # that even if the 'stop' command doesn't work (and the test fails), the client should
466             # still terminate.
467             open(HOTLINE_FILE, "w").write("")
468             open(os.path.join(c1, "introducer.furl"), "w").write("pb://xrndsskn2zuuian5ltnxrte7lnuqdrkz@127.0.0.1:55617/introducer\n")
469             # now it's safe to start the node
470         d.addCallback(_cb)
471
472         def _start(res):
473             return self.run_bintahoe(["--quiet", "start", c1])
474         d.addCallback(_start)
475
476         def _cb2(res):
477             out, err, rc_or_sig = res
478             errstr = "cc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
479             open(HOTLINE_FILE, "w").write("")
480             self.failUnlessEqual(rc_or_sig, 0, errstr)
481             self.failUnlessEqual(out, "", errstr) # If you emit noise, you fail this test.
482             errlines = err.split("\n")
483             self.failIf([True for line in errlines if (line != "" and "UserWarning: Unbuilt egg for setuptools" not in line
484                                                                   and "from pkg_resources import load_entry_point" not in line)], errstr)
485             if err != "":
486                 raise unittest.SkipTest("This test is known not to pass on Ubuntu Lucid; see #1235.")
487
488             # the parent (twistd) has exited. However, twistd writes the pid
489             # from the child, not the parent, so we can't expect twistd.pid
490             # to exist quite yet.
491
492             # the node is running, but it might not have made it past the
493             # first reactor turn yet, and if we kill it too early, it won't
494             # remove the twistd.pid file. So wait until it does something
495             # that we know it won't do until after the first turn.
496         d.addCallback(_cb2)
497
498         def _node_has_started():
499             return os.path.exists(PORTNUMFILE)
500         d.addCallback(lambda res: self.poll(_node_has_started))
501
502         # now we can kill it. TODO: On a slow machine, the node might kill
503         # itself before we get a chance to, especially if spawning the
504         # 'tahoe stop' command takes a while.
505         def _stop(res):
506             self.failUnless(os.path.exists(TWISTD_PID_FILE), (TWISTD_PID_FILE, os.listdir(os.path.dirname(TWISTD_PID_FILE))))
507             return self.run_bintahoe(["--quiet", "stop", c1])
508         d.addCallback(_stop)
509         return d
510
511     def test_client(self):
512         self.skip_if_cannot_daemonize()
513         basedir = self.workdir("test_client")
514         c1 = os.path.join(basedir, "c1")
515         HOTLINE_FILE = os.path.join(c1, "suicide_prevention_hotline")
516         TWISTD_PID_FILE = os.path.join(c1, "twistd.pid")
517         PORTNUMFILE = os.path.join(c1, "client.port")
518
519         d = self.run_bintahoe(["--quiet", "create-node", "--basedir", c1, "--webport", "0"])
520         def _cb(res):
521             out, err, rc_or_sig = res
522             self.failUnlessEqual(rc_or_sig, 0)
523             # By writing this file, we get sixty seconds before the client will exit. This insures
524             # that even if the 'stop' command doesn't work (and the test fails), the client should
525             # still terminate.
526             open(HOTLINE_FILE, "w").write("")
527             open(os.path.join(c1, "introducer.furl"), "w").write("pb://xrndsskn2zuuian5ltnxrte7lnuqdrkz@127.0.0.1:55617/introducer\n")
528             # now it's safe to start the node
529         d.addCallback(_cb)
530
531         def _start(res):
532             return self.run_bintahoe(["--quiet", "start", c1])
533         d.addCallback(_start)
534
535         def _cb2(res):
536             out, err, rc_or_sig = res
537             open(HOTLINE_FILE, "w").write("")
538             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
539             self.failUnlessEqual(rc_or_sig, 0, errstr)
540             self.failUnlessEqual(out, "", errstr)
541             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
542
543             # the parent (twistd) has exited. However, twistd writes the pid
544             # from the child, not the parent, so we can't expect twistd.pid
545             # to exist quite yet.
546
547             # the node is running, but it might not have made it past the
548             # first reactor turn yet, and if we kill it too early, it won't
549             # remove the twistd.pid file. So wait until it does something
550             # that we know it won't do until after the first turn.
551         d.addCallback(_cb2)
552
553         def _node_has_started():
554             return os.path.exists(PORTNUMFILE)
555         d.addCallback(lambda res: self.poll(_node_has_started))
556
557         def _started(res):
558             open(HOTLINE_FILE, "w").write("")
559             self.failUnless(os.path.exists(TWISTD_PID_FILE))
560             # rm this so we can detect when the second incarnation is ready
561             os.unlink(PORTNUMFILE)
562
563             return self.run_bintahoe(["--quiet", "restart", c1])
564         d.addCallback(_started)
565
566         def _cb3(res):
567             out, err, rc_or_sig = res
568
569             open(HOTLINE_FILE, "w").write("")
570             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
571             self.failUnlessEqual(rc_or_sig, 0, errstr)
572             self.failUnlessEqual(out, "", errstr)
573             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
574         d.addCallback(_cb3)
575
576         # again, the second incarnation of the node might not be ready yet,
577         # so poll until it is
578         d.addCallback(lambda res: self.poll(_node_has_started))
579
580         # now we can kill it. TODO: On a slow machine, the node might kill
581         # itself before we get a chance too, especially if spawning the
582         # 'tahoe stop' command takes a while.
583         def _stop(res):
584             open(HOTLINE_FILE, "w").write("")
585             self.failUnless(os.path.exists(TWISTD_PID_FILE), (TWISTD_PID_FILE, os.listdir(os.path.dirname(TWISTD_PID_FILE))))
586             return self.run_bintahoe(["--quiet", "stop", c1])
587         d.addCallback(_stop)
588
589         def _cb4(res):
590             out, err, rc_or_sig = res
591
592             open(HOTLINE_FILE, "w").write("")
593             # the parent has exited by now
594             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
595             self.failUnlessEqual(rc_or_sig, 0, errstr)
596             self.failUnlessEqual(out, "", errstr)
597             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
598             # the parent was supposed to poll and wait until it sees
599             # twistd.pid go away before it exits, so twistd.pid should be
600             # gone by now.
601             self.failIf(os.path.exists(TWISTD_PID_FILE))
602         d.addCallback(_cb4)
603         def _remove_hotline(res):
604             os.unlink(HOTLINE_FILE)
605             return res
606         d.addBoth(_remove_hotline)
607         return d
608
609     def test_baddir(self):
610         self.skip_if_cannot_daemonize()
611         basedir = self.workdir("test_baddir")
612         fileutil.make_dirs(basedir)
613
614         d = self.run_bintahoe(["--quiet", "start", "--basedir", basedir])
615         def _cb(res):
616             out, err, rc_or_sig = res
617             self.failUnlessEqual(rc_or_sig, 1)
618             self.failUnless("does not look like a node directory" in err, err)
619         d.addCallback(_cb)
620
621         def _then_stop_it(res):
622             return self.run_bintahoe(["--quiet", "stop", "--basedir", basedir])
623         d.addCallback(_then_stop_it)
624
625         def _cb2(res):
626             out, err, rc_or_sig = res
627             self.failUnlessEqual(rc_or_sig, 2)
628             self.failUnless("does not look like a running node directory" in err)
629         d.addCallback(_cb2)
630
631         def _then_start_in_bogus_basedir(res):
632             not_a_dir = os.path.join(basedir, "bogus")
633             return self.run_bintahoe(["--quiet", "start", "--basedir", not_a_dir])
634         d.addCallback(_then_start_in_bogus_basedir)
635
636         def _cb3(res):
637             out, err, rc_or_sig = res
638             self.failUnlessEqual(rc_or_sig, 1)
639             self.failUnless("does not look like a directory at all" in err, err)
640         d.addCallback(_cb3)
641         return d
642
643     def test_keygen(self):
644         self.skip_if_cannot_daemonize()
645         basedir = self.workdir("test_keygen")
646         c1 = os.path.join(basedir, "c1")
647         TWISTD_PID_FILE = os.path.join(c1, "twistd.pid")
648         KEYGEN_FURL_FILE = os.path.join(c1, "key_generator.furl")
649
650         d = self.run_bintahoe(["--quiet", "create-key-generator", "--basedir", c1])
651         def _cb(res):
652             out, err, rc_or_sig = res
653             self.failUnlessEqual(rc_or_sig, 0)
654         d.addCallback(_cb)
655
656         def _start(res):
657             return self.run_bintahoe(["--quiet", "start", c1])
658         d.addCallback(_start)
659
660         def _cb2(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
667             # the parent (twistd) has exited. However, twistd writes the pid
668             # from the child, not the parent, so we can't expect twistd.pid
669             # to exist quite yet.
670
671             # the node is running, but it might not have made it past the
672             # first reactor turn yet, and if we kill it too early, it won't
673             # remove the twistd.pid file. So wait until it does something
674             # that we know it won't do until after the first turn.
675         d.addCallback(_cb2)
676
677         def _node_has_started():
678             return os.path.exists(KEYGEN_FURL_FILE)
679         d.addCallback(lambda res: self.poll(_node_has_started))
680
681         def _started(res):
682             self.failUnless(os.path.exists(TWISTD_PID_FILE))
683             # rm this so we can detect when the second incarnation is ready
684             os.unlink(KEYGEN_FURL_FILE)
685             return self.run_bintahoe(["--quiet", "restart", c1])
686         d.addCallback(_started)
687
688         def _cb3(res):
689             out, err, rc_or_sig = res
690             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
691             self.failUnlessEqual(rc_or_sig, 0, errstr)
692             self.failUnlessEqual(out, "", errstr)
693             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
694         d.addCallback(_cb3)
695
696         # again, the second incarnation of the node might not be ready yet,
697         # so poll until it is
698         d.addCallback(lambda res: self.poll(_node_has_started))
699
700         # now we can kill it. TODO: On a slow machine, the node might kill
701         # itself before we get a chance too, especially if spawning the
702         # 'tahoe stop' command takes a while.
703         def _stop(res):
704             self.failUnless(os.path.exists(TWISTD_PID_FILE))
705             return self.run_bintahoe(["--quiet", "stop", c1])
706         d.addCallback(_stop)
707
708         def _cb4(res):
709             out, err, rc_or_sig = res
710             # the parent has exited by now
711             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
712             self.failUnlessEqual(rc_or_sig, 0, errstr)
713             self.failUnlessEqual(out, "", errstr)
714             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
715             # the parent was supposed to poll and wait until it sees
716             # twistd.pid go away before it exits, so twistd.pid should be
717             # gone by now.
718             self.failIf(os.path.exists(TWISTD_PID_FILE))
719         d.addCallback(_cb4)
720         return d