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