]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/test/test_cli.py
test_cli: probably remove the unix-ism that broke tests on windows
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / test / test_cli.py
1
2 import os.path
3 from twisted.trial import unittest
4 from cStringIO import StringIO
5 import urllib, re, sys
6 import simplejson
7
8 from mock import patch, Mock, call
9
10 from allmydata.util import fileutil, hashutil, base32, keyutil
11 from allmydata import uri
12 from allmydata.immutable import upload
13 from allmydata.interfaces import MDMF_VERSION, SDMF_VERSION
14 from allmydata.mutable.publish import MutableData
15 from allmydata.dirnode import normalize
16 from allmydata.scripts.common_http import socket_error
17 import allmydata.scripts.common_http
18 from pycryptopp.publickey import ed25519
19
20 # Test that the scripts can be imported.
21 from allmydata.scripts import create_node, debug, keygen, startstop_node, \
22     tahoe_add_alias, tahoe_backup, tahoe_check, tahoe_cp, tahoe_get, tahoe_ls, \
23     tahoe_manifest, tahoe_mkdir, tahoe_mv, tahoe_put, tahoe_unlink, tahoe_webopen
24 _hush_pyflakes = [create_node, debug, keygen, startstop_node,
25     tahoe_add_alias, tahoe_backup, tahoe_check, tahoe_cp, tahoe_get, tahoe_ls,
26     tahoe_manifest, tahoe_mkdir, tahoe_mv, tahoe_put, tahoe_unlink, tahoe_webopen]
27
28 from allmydata.scripts import common
29 from allmydata.scripts.common import DEFAULT_ALIAS, get_aliases, get_alias, \
30      DefaultAliasMarker
31
32 from allmydata.scripts import cli, debug, runner, backupdb
33 from allmydata.test.common_util import StallMixin, ReallyEqualMixin
34 from allmydata.test.no_network import GridTestMixin
35 from twisted.internet import threads # CLI tests use deferToThread
36 from twisted.internet import defer # List uses a DeferredList in one place.
37 from twisted.python import usage
38
39 from allmydata.util.assertutil import precondition
40 from allmydata.util.encodingutil import listdir_unicode, unicode_platform, \
41     quote_output, get_io_encoding, get_filesystem_encoding, \
42     unicode_to_output, unicode_to_argv, to_str
43 from allmydata.util.fileutil import abspath_expanduser_unicode
44
45 timeout = 480 # deep_check takes 360s on Zandr's linksys box, others take > 240s
46
47 def parse_options(basedir, command, args):
48     o = runner.Options()
49     o.parseOptions(["--node-directory", basedir, command] + args)
50     while hasattr(o, "subOptions"):
51         o = o.subOptions
52     return o
53
54 class CLITestMixin(ReallyEqualMixin):
55     def do_cli(self, verb, *args, **kwargs):
56         nodeargs = [
57             "--node-directory", self.get_clientdir(),
58             ]
59         argv = nodeargs + [verb] + list(args)
60         stdin = kwargs.get("stdin", "")
61         stdout, stderr = StringIO(), StringIO()
62         d = threads.deferToThread(runner.runner, argv, run_by_human=False,
63                                   stdin=StringIO(stdin),
64                                   stdout=stdout, stderr=stderr)
65         def _done(rc):
66             return rc, stdout.getvalue(), stderr.getvalue()
67         d.addCallback(_done)
68         return d
69
70     def skip_if_cannot_represent_filename(self, u):
71         precondition(isinstance(u, unicode))
72
73         enc = get_filesystem_encoding()
74         if not unicode_platform():
75             try:
76                 u.encode(enc)
77             except UnicodeEncodeError:
78                 raise unittest.SkipTest("A non-ASCII filename could not be encoded on this platform.")
79
80
81 class CLI(CLITestMixin, unittest.TestCase):
82     def _dump_cap(self, *args):
83         config = debug.DumpCapOptions()
84         config.stdout,config.stderr = StringIO(), StringIO()
85         config.parseOptions(args)
86         debug.dump_cap(config)
87         self.failIf(config.stderr.getvalue())
88         output = config.stdout.getvalue()
89         return output
90
91     def test_dump_cap_chk(self):
92         key = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
93         uri_extension_hash = hashutil.uri_extension_hash("stuff")
94         needed_shares = 25
95         total_shares = 100
96         size = 1234
97         u = uri.CHKFileURI(key=key,
98                            uri_extension_hash=uri_extension_hash,
99                            needed_shares=needed_shares,
100                            total_shares=total_shares,
101                            size=size)
102         output = self._dump_cap(u.to_string())
103         self.failUnless("CHK File:" in output, output)
104         self.failUnless("key: aaaqeayeaudaocajbifqydiob4" in output, output)
105         self.failUnless("UEB hash: nf3nimquen7aeqm36ekgxomalstenpkvsdmf6fplj7swdatbv5oa" in output, output)
106         self.failUnless("size: 1234" in output, output)
107         self.failUnless("k/N: 25/100" in output, output)
108         self.failUnless("storage index: hdis5iaveku6lnlaiccydyid7q" in output, output)
109
110         output = self._dump_cap("--client-secret", "5s33nk3qpvnj2fw3z4mnm2y6fa",
111                                 u.to_string())
112         self.failUnless("client renewal secret: znxmki5zdibb5qlt46xbdvk2t55j7hibejq3i5ijyurkr6m6jkhq" in output, output)
113
114         output = self._dump_cap(u.get_verify_cap().to_string())
115         self.failIf("key: " in output, output)
116         self.failUnless("UEB hash: nf3nimquen7aeqm36ekgxomalstenpkvsdmf6fplj7swdatbv5oa" in output, output)
117         self.failUnless("size: 1234" in output, output)
118         self.failUnless("k/N: 25/100" in output, output)
119         self.failUnless("storage index: hdis5iaveku6lnlaiccydyid7q" in output, output)
120
121         prefixed_u = "http://127.0.0.1/uri/%s" % urllib.quote(u.to_string())
122         output = self._dump_cap(prefixed_u)
123         self.failUnless("CHK File:" in output, output)
124         self.failUnless("key: aaaqeayeaudaocajbifqydiob4" in output, output)
125         self.failUnless("UEB hash: nf3nimquen7aeqm36ekgxomalstenpkvsdmf6fplj7swdatbv5oa" in output, output)
126         self.failUnless("size: 1234" in output, output)
127         self.failUnless("k/N: 25/100" in output, output)
128         self.failUnless("storage index: hdis5iaveku6lnlaiccydyid7q" in output, output)
129
130     def test_dump_cap_lit(self):
131         u = uri.LiteralFileURI("this is some data")
132         output = self._dump_cap(u.to_string())
133         self.failUnless("Literal File URI:" in output, output)
134         self.failUnless("data: 'this is some data'" in output, output)
135
136     def test_dump_cap_sdmf(self):
137         writekey = "\x01" * 16
138         fingerprint = "\xfe" * 32
139         u = uri.WriteableSSKFileURI(writekey, fingerprint)
140
141         output = self._dump_cap(u.to_string())
142         self.failUnless("SDMF Writeable URI:" in output, output)
143         self.failUnless("writekey: aeaqcaibaeaqcaibaeaqcaibae" in output, output)
144         self.failUnless("readkey: nvgh5vj2ekzzkim5fgtb4gey5y" in output, output)
145         self.failUnless("storage index: nt4fwemuw7flestsezvo2eveke" in output, output)
146         self.failUnless("fingerprint: 737p57x6737p57x6737p57x6737p57x6737p57x6737p57x6737a" in output, output)
147
148         output = self._dump_cap("--client-secret", "5s33nk3qpvnj2fw3z4mnm2y6fa",
149                                 u.to_string())
150         self.failUnless("file renewal secret: arpszxzc2t6kb4okkg7sp765xgkni5z7caavj7lta73vmtymjlxq" in output, output)
151
152         fileutil.make_dirs("cli/test_dump_cap/private")
153         fileutil.write("cli/test_dump_cap/private/secret", "5s33nk3qpvnj2fw3z4mnm2y6fa\n")
154         output = self._dump_cap("--client-dir", "cli/test_dump_cap",
155                                 u.to_string())
156         self.failUnless("file renewal secret: arpszxzc2t6kb4okkg7sp765xgkni5z7caavj7lta73vmtymjlxq" in output, output)
157
158         output = self._dump_cap("--client-dir", "cli/test_dump_cap_BOGUS",
159                                 u.to_string())
160         self.failIf("file renewal secret:" in output, output)
161
162         output = self._dump_cap("--nodeid", "tqc35esocrvejvg4mablt6aowg6tl43j",
163                                 u.to_string())
164         self.failUnless("write_enabler: mgcavriox2wlb5eer26unwy5cw56elh3sjweffckkmivvsxtaknq" in output, output)
165         self.failIf("file renewal secret:" in output, output)
166
167         output = self._dump_cap("--nodeid", "tqc35esocrvejvg4mablt6aowg6tl43j",
168                                 "--client-secret", "5s33nk3qpvnj2fw3z4mnm2y6fa",
169                                 u.to_string())
170         self.failUnless("write_enabler: mgcavriox2wlb5eer26unwy5cw56elh3sjweffckkmivvsxtaknq" in output, output)
171         self.failUnless("file renewal secret: arpszxzc2t6kb4okkg7sp765xgkni5z7caavj7lta73vmtymjlxq" in output, output)
172         self.failUnless("lease renewal secret: 7pjtaumrb7znzkkbvekkmuwpqfjyfyamznfz4bwwvmh4nw33lorq" in output, output)
173
174         u = u.get_readonly()
175         output = self._dump_cap(u.to_string())
176         self.failUnless("SDMF Read-only URI:" in output, output)
177         self.failUnless("readkey: nvgh5vj2ekzzkim5fgtb4gey5y" in output, output)
178         self.failUnless("storage index: nt4fwemuw7flestsezvo2eveke" in output, output)
179         self.failUnless("fingerprint: 737p57x6737p57x6737p57x6737p57x6737p57x6737p57x6737a" in output, output)
180
181         u = u.get_verify_cap()
182         output = self._dump_cap(u.to_string())
183         self.failUnless("SDMF Verifier URI:" in output, output)
184         self.failUnless("storage index: nt4fwemuw7flestsezvo2eveke" in output, output)
185         self.failUnless("fingerprint: 737p57x6737p57x6737p57x6737p57x6737p57x6737p57x6737a" in output, output)
186
187     def test_dump_cap_mdmf(self):
188         writekey = "\x01" * 16
189         fingerprint = "\xfe" * 32
190         u = uri.WriteableMDMFFileURI(writekey, fingerprint)
191
192         output = self._dump_cap(u.to_string())
193         self.failUnless("MDMF Writeable URI:" in output, output)
194         self.failUnless("writekey: aeaqcaibaeaqcaibaeaqcaibae" in output, output)
195         self.failUnless("readkey: nvgh5vj2ekzzkim5fgtb4gey5y" in output, output)
196         self.failUnless("storage index: nt4fwemuw7flestsezvo2eveke" in output, output)
197         self.failUnless("fingerprint: 737p57x6737p57x6737p57x6737p57x6737p57x6737p57x6737a" in output, output)
198
199         output = self._dump_cap("--client-secret", "5s33nk3qpvnj2fw3z4mnm2y6fa",
200                                 u.to_string())
201         self.failUnless("file renewal secret: arpszxzc2t6kb4okkg7sp765xgkni5z7caavj7lta73vmtymjlxq" in output, output)
202
203         fileutil.make_dirs("cli/test_dump_cap/private")
204         fileutil.write("cli/test_dump_cap/private/secret", "5s33nk3qpvnj2fw3z4mnm2y6fa\n")
205         output = self._dump_cap("--client-dir", "cli/test_dump_cap",
206                                 u.to_string())
207         self.failUnless("file renewal secret: arpszxzc2t6kb4okkg7sp765xgkni5z7caavj7lta73vmtymjlxq" in output, output)
208
209         output = self._dump_cap("--client-dir", "cli/test_dump_cap_BOGUS",
210                                 u.to_string())
211         self.failIf("file renewal secret:" in output, output)
212
213         output = self._dump_cap("--nodeid", "tqc35esocrvejvg4mablt6aowg6tl43j",
214                                 u.to_string())
215         self.failUnless("write_enabler: mgcavriox2wlb5eer26unwy5cw56elh3sjweffckkmivvsxtaknq" in output, output)
216         self.failIf("file renewal secret:" in output, output)
217
218         output = self._dump_cap("--nodeid", "tqc35esocrvejvg4mablt6aowg6tl43j",
219                                 "--client-secret", "5s33nk3qpvnj2fw3z4mnm2y6fa",
220                                 u.to_string())
221         self.failUnless("write_enabler: mgcavriox2wlb5eer26unwy5cw56elh3sjweffckkmivvsxtaknq" in output, output)
222         self.failUnless("file renewal secret: arpszxzc2t6kb4okkg7sp765xgkni5z7caavj7lta73vmtymjlxq" in output, output)
223         self.failUnless("lease renewal secret: 7pjtaumrb7znzkkbvekkmuwpqfjyfyamznfz4bwwvmh4nw33lorq" in output, output)
224
225         u = u.get_readonly()
226         output = self._dump_cap(u.to_string())
227         self.failUnless("MDMF Read-only URI:" in output, output)
228         self.failUnless("readkey: nvgh5vj2ekzzkim5fgtb4gey5y" in output, output)
229         self.failUnless("storage index: nt4fwemuw7flestsezvo2eveke" in output, output)
230         self.failUnless("fingerprint: 737p57x6737p57x6737p57x6737p57x6737p57x6737p57x6737a" in output, output)
231
232         u = u.get_verify_cap()
233         output = self._dump_cap(u.to_string())
234         self.failUnless("MDMF Verifier URI:" in output, output)
235         self.failUnless("storage index: nt4fwemuw7flestsezvo2eveke" in output, output)
236         self.failUnless("fingerprint: 737p57x6737p57x6737p57x6737p57x6737p57x6737p57x6737a" in output, output)
237
238
239     def test_dump_cap_chk_directory(self):
240         key = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
241         uri_extension_hash = hashutil.uri_extension_hash("stuff")
242         needed_shares = 25
243         total_shares = 100
244         size = 1234
245         u1 = uri.CHKFileURI(key=key,
246                             uri_extension_hash=uri_extension_hash,
247                             needed_shares=needed_shares,
248                             total_shares=total_shares,
249                             size=size)
250         u = uri.ImmutableDirectoryURI(u1)
251
252         output = self._dump_cap(u.to_string())
253         self.failUnless("CHK Directory URI:" in output, output)
254         self.failUnless("key: aaaqeayeaudaocajbifqydiob4" in output, output)
255         self.failUnless("UEB hash: nf3nimquen7aeqm36ekgxomalstenpkvsdmf6fplj7swdatbv5oa" in output, output)
256         self.failUnless("size: 1234" in output, output)
257         self.failUnless("k/N: 25/100" in output, output)
258         self.failUnless("storage index: hdis5iaveku6lnlaiccydyid7q" in output, output)
259
260         output = self._dump_cap("--client-secret", "5s33nk3qpvnj2fw3z4mnm2y6fa",
261                                 u.to_string())
262         self.failUnless("file renewal secret: csrvkjgomkyyyil5yo4yk5np37p6oa2ve2hg6xmk2dy7kaxsu6xq" in output, output)
263
264         u = u.get_verify_cap()
265         output = self._dump_cap(u.to_string())
266         self.failUnless("CHK Directory Verifier URI:" in output, output)
267         self.failIf("key: " in output, output)
268         self.failUnless("UEB hash: nf3nimquen7aeqm36ekgxomalstenpkvsdmf6fplj7swdatbv5oa" in output, output)
269         self.failUnless("size: 1234" in output, output)
270         self.failUnless("k/N: 25/100" in output, output)
271         self.failUnless("storage index: hdis5iaveku6lnlaiccydyid7q" in output, output)
272
273     def test_dump_cap_sdmf_directory(self):
274         writekey = "\x01" * 16
275         fingerprint = "\xfe" * 32
276         u1 = uri.WriteableSSKFileURI(writekey, fingerprint)
277         u = uri.DirectoryURI(u1)
278
279         output = self._dump_cap(u.to_string())
280         self.failUnless("Directory Writeable URI:" in output, output)
281         self.failUnless("writekey: aeaqcaibaeaqcaibaeaqcaibae" in output,
282                         output)
283         self.failUnless("readkey: nvgh5vj2ekzzkim5fgtb4gey5y" in output, output)
284         self.failUnless("storage index: nt4fwemuw7flestsezvo2eveke" in output,
285                         output)
286         self.failUnless("fingerprint: 737p57x6737p57x6737p57x6737p57x6737p57x6737p57x6737a" in output, output)
287
288         output = self._dump_cap("--client-secret", "5s33nk3qpvnj2fw3z4mnm2y6fa",
289                                 u.to_string())
290         self.failUnless("file renewal secret: arpszxzc2t6kb4okkg7sp765xgkni5z7caavj7lta73vmtymjlxq" in output, output)
291
292         output = self._dump_cap("--nodeid", "tqc35esocrvejvg4mablt6aowg6tl43j",
293                                 u.to_string())
294         self.failUnless("write_enabler: mgcavriox2wlb5eer26unwy5cw56elh3sjweffckkmivvsxtaknq" in output, output)
295         self.failIf("file renewal secret:" in output, output)
296
297         output = self._dump_cap("--nodeid", "tqc35esocrvejvg4mablt6aowg6tl43j",
298                                 "--client-secret", "5s33nk3qpvnj2fw3z4mnm2y6fa",
299                                 u.to_string())
300         self.failUnless("write_enabler: mgcavriox2wlb5eer26unwy5cw56elh3sjweffckkmivvsxtaknq" in output, output)
301         self.failUnless("file renewal secret: arpszxzc2t6kb4okkg7sp765xgkni5z7caavj7lta73vmtymjlxq" in output, output)
302         self.failUnless("lease renewal secret: 7pjtaumrb7znzkkbvekkmuwpqfjyfyamznfz4bwwvmh4nw33lorq" in output, output)
303
304         u = u.get_readonly()
305         output = self._dump_cap(u.to_string())
306         self.failUnless("Directory Read-only URI:" in output, output)
307         self.failUnless("readkey: nvgh5vj2ekzzkim5fgtb4gey5y" in output, output)
308         self.failUnless("storage index: nt4fwemuw7flestsezvo2eveke" in output, output)
309         self.failUnless("fingerprint: 737p57x6737p57x6737p57x6737p57x6737p57x6737p57x6737a" in output, output)
310
311         u = u.get_verify_cap()
312         output = self._dump_cap(u.to_string())
313         self.failUnless("Directory Verifier URI:" in output, output)
314         self.failUnless("storage index: nt4fwemuw7flestsezvo2eveke" in output, output)
315         self.failUnless("fingerprint: 737p57x6737p57x6737p57x6737p57x6737p57x6737p57x6737a" in output, output)
316
317     def test_dump_cap_mdmf_directory(self):
318         writekey = "\x01" * 16
319         fingerprint = "\xfe" * 32
320         u1 = uri.WriteableMDMFFileURI(writekey, fingerprint)
321         u = uri.MDMFDirectoryURI(u1)
322
323         output = self._dump_cap(u.to_string())
324         self.failUnless("Directory Writeable URI:" in output, output)
325         self.failUnless("writekey: aeaqcaibaeaqcaibaeaqcaibae" in output,
326                         output)
327         self.failUnless("readkey: nvgh5vj2ekzzkim5fgtb4gey5y" in output, output)
328         self.failUnless("storage index: nt4fwemuw7flestsezvo2eveke" in output,
329                         output)
330         self.failUnless("fingerprint: 737p57x6737p57x6737p57x6737p57x6737p57x6737p57x6737a" in output, output)
331
332         output = self._dump_cap("--client-secret", "5s33nk3qpvnj2fw3z4mnm2y6fa",
333                                 u.to_string())
334         self.failUnless("file renewal secret: arpszxzc2t6kb4okkg7sp765xgkni5z7caavj7lta73vmtymjlxq" in output, output)
335
336         output = self._dump_cap("--nodeid", "tqc35esocrvejvg4mablt6aowg6tl43j",
337                                 u.to_string())
338         self.failUnless("write_enabler: mgcavriox2wlb5eer26unwy5cw56elh3sjweffckkmivvsxtaknq" in output, output)
339         self.failIf("file renewal secret:" in output, output)
340
341         output = self._dump_cap("--nodeid", "tqc35esocrvejvg4mablt6aowg6tl43j",
342                                 "--client-secret", "5s33nk3qpvnj2fw3z4mnm2y6fa",
343                                 u.to_string())
344         self.failUnless("write_enabler: mgcavriox2wlb5eer26unwy5cw56elh3sjweffckkmivvsxtaknq" in output, output)
345         self.failUnless("file renewal secret: arpszxzc2t6kb4okkg7sp765xgkni5z7caavj7lta73vmtymjlxq" in output, output)
346         self.failUnless("lease renewal secret: 7pjtaumrb7znzkkbvekkmuwpqfjyfyamznfz4bwwvmh4nw33lorq" in output, output)
347
348         u = u.get_readonly()
349         output = self._dump_cap(u.to_string())
350         self.failUnless("Directory Read-only URI:" in output, output)
351         self.failUnless("readkey: nvgh5vj2ekzzkim5fgtb4gey5y" in output, output)
352         self.failUnless("storage index: nt4fwemuw7flestsezvo2eveke" in output, output)
353         self.failUnless("fingerprint: 737p57x6737p57x6737p57x6737p57x6737p57x6737p57x6737a" in output, output)
354
355         u = u.get_verify_cap()
356         output = self._dump_cap(u.to_string())
357         self.failUnless("Directory Verifier URI:" in output, output)
358         self.failUnless("storage index: nt4fwemuw7flestsezvo2eveke" in output, output)
359         self.failUnless("fingerprint: 737p57x6737p57x6737p57x6737p57x6737p57x6737p57x6737a" in output, output)
360
361
362     def _catalog_shares(self, *basedirs):
363         o = debug.CatalogSharesOptions()
364         o.stdout,o.stderr = StringIO(), StringIO()
365         args = list(basedirs)
366         o.parseOptions(args)
367         debug.catalog_shares(o)
368         out = o.stdout.getvalue()
369         err = o.stderr.getvalue()
370         return out, err
371
372     def test_catalog_shares_error(self):
373         nodedir1 = "cli/test_catalog_shares/node1"
374         sharedir = os.path.join(nodedir1, "storage", "shares", "mq", "mqfblse6m5a6dh45isu2cg7oji")
375         fileutil.make_dirs(sharedir)
376         fileutil.write("cli/test_catalog_shares/node1/storage/shares/mq/not-a-dir", "")
377         # write a bogus share that looks a little bit like CHK
378         fileutil.write(os.path.join(sharedir, "8"),
379                        "\x00\x00\x00\x01" + "\xff" * 200) # this triggers an assert
380
381         nodedir2 = "cli/test_catalog_shares/node2"
382         fileutil.make_dirs(nodedir2)
383         fileutil.write("cli/test_catalog_shares/node1/storage/shares/not-a-dir", "")
384
385         # now make sure that the 'catalog-shares' commands survives the error
386         out, err = self._catalog_shares(nodedir1, nodedir2)
387         self.failUnlessReallyEqual(out, "", out)
388         self.failUnless("Error processing " in err,
389                         "didn't see 'error processing' in '%s'" % err)
390         #self.failUnless(nodedir1 in err,
391         #                "didn't see '%s' in '%s'" % (nodedir1, err))
392         # windows mangles the path, and os.path.join isn't enough to make
393         # up for it, so just look for individual strings
394         self.failUnless("node1" in err,
395                         "didn't see 'node1' in '%s'" % err)
396         self.failUnless("mqfblse6m5a6dh45isu2cg7oji" in err,
397                         "didn't see 'mqfblse6m5a6dh45isu2cg7oji' in '%s'" % err)
398
399     def test_alias(self):
400         aliases = {"tahoe": "TA",
401                    "work": "WA",
402                    "c": "CA"}
403         def ga1(path):
404             return get_alias(aliases, path, u"tahoe")
405         uses_lettercolon = common.platform_uses_lettercolon_drivename()
406         self.failUnlessReallyEqual(ga1(u"bare"), ("TA", "bare"))
407         self.failUnlessReallyEqual(ga1(u"baredir/file"), ("TA", "baredir/file"))
408         self.failUnlessReallyEqual(ga1(u"baredir/file:7"), ("TA", "baredir/file:7"))
409         self.failUnlessReallyEqual(ga1(u"tahoe:"), ("TA", ""))
410         self.failUnlessReallyEqual(ga1(u"tahoe:file"), ("TA", "file"))
411         self.failUnlessReallyEqual(ga1(u"tahoe:dir/file"), ("TA", "dir/file"))
412         self.failUnlessReallyEqual(ga1(u"work:"), ("WA", ""))
413         self.failUnlessReallyEqual(ga1(u"work:file"), ("WA", "file"))
414         self.failUnlessReallyEqual(ga1(u"work:dir/file"), ("WA", "dir/file"))
415         # default != None means we really expect a tahoe path, regardless of
416         # whether we're on windows or not. This is what 'tahoe get' uses.
417         self.failUnlessReallyEqual(ga1(u"c:"), ("CA", ""))
418         self.failUnlessReallyEqual(ga1(u"c:file"), ("CA", "file"))
419         self.failUnlessReallyEqual(ga1(u"c:dir/file"), ("CA", "dir/file"))
420         self.failUnlessReallyEqual(ga1(u"URI:stuff"), ("URI:stuff", ""))
421         self.failUnlessReallyEqual(ga1(u"URI:stuff/file"), ("URI:stuff", "file"))
422         self.failUnlessReallyEqual(ga1(u"URI:stuff:./file"), ("URI:stuff", "file"))
423         self.failUnlessReallyEqual(ga1(u"URI:stuff/dir/file"), ("URI:stuff", "dir/file"))
424         self.failUnlessReallyEqual(ga1(u"URI:stuff:./dir/file"), ("URI:stuff", "dir/file"))
425         self.failUnlessRaises(common.UnknownAliasError, ga1, u"missing:")
426         self.failUnlessRaises(common.UnknownAliasError, ga1, u"missing:dir")
427         self.failUnlessRaises(common.UnknownAliasError, ga1, u"missing:dir/file")
428
429         def ga2(path):
430             return get_alias(aliases, path, None)
431         self.failUnlessReallyEqual(ga2(u"bare"), (DefaultAliasMarker, "bare"))
432         self.failUnlessReallyEqual(ga2(u"baredir/file"),
433                              (DefaultAliasMarker, "baredir/file"))
434         self.failUnlessReallyEqual(ga2(u"baredir/file:7"),
435                              (DefaultAliasMarker, "baredir/file:7"))
436         self.failUnlessReallyEqual(ga2(u"baredir/sub:1/file:7"),
437                              (DefaultAliasMarker, "baredir/sub:1/file:7"))
438         self.failUnlessReallyEqual(ga2(u"tahoe:"), ("TA", ""))
439         self.failUnlessReallyEqual(ga2(u"tahoe:file"), ("TA", "file"))
440         self.failUnlessReallyEqual(ga2(u"tahoe:dir/file"), ("TA", "dir/file"))
441         # on windows, we really want c:foo to indicate a local file.
442         # default==None is what 'tahoe cp' uses.
443         if uses_lettercolon:
444             self.failUnlessReallyEqual(ga2(u"c:"), (DefaultAliasMarker, "c:"))
445             self.failUnlessReallyEqual(ga2(u"c:file"), (DefaultAliasMarker, "c:file"))
446             self.failUnlessReallyEqual(ga2(u"c:dir/file"),
447                                  (DefaultAliasMarker, "c:dir/file"))
448         else:
449             self.failUnlessReallyEqual(ga2(u"c:"), ("CA", ""))
450             self.failUnlessReallyEqual(ga2(u"c:file"), ("CA", "file"))
451             self.failUnlessReallyEqual(ga2(u"c:dir/file"), ("CA", "dir/file"))
452         self.failUnlessReallyEqual(ga2(u"work:"), ("WA", ""))
453         self.failUnlessReallyEqual(ga2(u"work:file"), ("WA", "file"))
454         self.failUnlessReallyEqual(ga2(u"work:dir/file"), ("WA", "dir/file"))
455         self.failUnlessReallyEqual(ga2(u"URI:stuff"), ("URI:stuff", ""))
456         self.failUnlessReallyEqual(ga2(u"URI:stuff/file"), ("URI:stuff", "file"))
457         self.failUnlessReallyEqual(ga2(u"URI:stuff:./file"), ("URI:stuff", "file"))
458         self.failUnlessReallyEqual(ga2(u"URI:stuff/dir/file"), ("URI:stuff", "dir/file"))
459         self.failUnlessReallyEqual(ga2(u"URI:stuff:./dir/file"), ("URI:stuff", "dir/file"))
460         self.failUnlessRaises(common.UnknownAliasError, ga2, u"missing:")
461         self.failUnlessRaises(common.UnknownAliasError, ga2, u"missing:dir")
462         self.failUnlessRaises(common.UnknownAliasError, ga2, u"missing:dir/file")
463
464         def ga3(path):
465             old = common.pretend_platform_uses_lettercolon
466             try:
467                 common.pretend_platform_uses_lettercolon = True
468                 retval = get_alias(aliases, path, None)
469             finally:
470                 common.pretend_platform_uses_lettercolon = old
471             return retval
472         self.failUnlessReallyEqual(ga3(u"bare"), (DefaultAliasMarker, "bare"))
473         self.failUnlessReallyEqual(ga3(u"baredir/file"),
474                              (DefaultAliasMarker, "baredir/file"))
475         self.failUnlessReallyEqual(ga3(u"baredir/file:7"),
476                              (DefaultAliasMarker, "baredir/file:7"))
477         self.failUnlessReallyEqual(ga3(u"baredir/sub:1/file:7"),
478                              (DefaultAliasMarker, "baredir/sub:1/file:7"))
479         self.failUnlessReallyEqual(ga3(u"tahoe:"), ("TA", ""))
480         self.failUnlessReallyEqual(ga3(u"tahoe:file"), ("TA", "file"))
481         self.failUnlessReallyEqual(ga3(u"tahoe:dir/file"), ("TA", "dir/file"))
482         self.failUnlessReallyEqual(ga3(u"c:"), (DefaultAliasMarker, "c:"))
483         self.failUnlessReallyEqual(ga3(u"c:file"), (DefaultAliasMarker, "c:file"))
484         self.failUnlessReallyEqual(ga3(u"c:dir/file"),
485                              (DefaultAliasMarker, "c:dir/file"))
486         self.failUnlessReallyEqual(ga3(u"work:"), ("WA", ""))
487         self.failUnlessReallyEqual(ga3(u"work:file"), ("WA", "file"))
488         self.failUnlessReallyEqual(ga3(u"work:dir/file"), ("WA", "dir/file"))
489         self.failUnlessReallyEqual(ga3(u"URI:stuff"), ("URI:stuff", ""))
490         self.failUnlessReallyEqual(ga3(u"URI:stuff:./file"), ("URI:stuff", "file"))
491         self.failUnlessReallyEqual(ga3(u"URI:stuff:./dir/file"), ("URI:stuff", "dir/file"))
492         self.failUnlessRaises(common.UnknownAliasError, ga3, u"missing:")
493         self.failUnlessRaises(common.UnknownAliasError, ga3, u"missing:dir")
494         self.failUnlessRaises(common.UnknownAliasError, ga3, u"missing:dir/file")
495         # calling get_alias with a path that doesn't include an alias and
496         # default set to something that isn't in the aliases argument should
497         # raise an UnknownAliasError.
498         def ga4(path):
499             return get_alias(aliases, path, u"badddefault:")
500         self.failUnlessRaises(common.UnknownAliasError, ga4, u"afile")
501         self.failUnlessRaises(common.UnknownAliasError, ga4, u"a/dir/path/")
502
503         def ga5(path):
504             old = common.pretend_platform_uses_lettercolon
505             try:
506                 common.pretend_platform_uses_lettercolon = True
507                 retval = get_alias(aliases, path, u"baddefault:")
508             finally:
509                 common.pretend_platform_uses_lettercolon = old
510             return retval
511         self.failUnlessRaises(common.UnknownAliasError, ga5, u"C:\\Windows")
512
513     def test_listdir_unicode_good(self):
514         filenames = [u'L\u00F4zane', u'Bern', u'Gen\u00E8ve']  # must be NFC
515
516         for name in filenames:
517             self.skip_if_cannot_represent_filename(name)
518
519         basedir = "cli/common/listdir_unicode_good"
520         fileutil.make_dirs(basedir)
521
522         for name in filenames:
523             open(os.path.join(unicode(basedir), name), "wb").close()
524
525         for file in listdir_unicode(unicode(basedir)):
526             self.failUnlessIn(normalize(file), filenames)
527
528     def test_exception_catcher(self):
529         self.basedir = "cli/exception_catcher"
530
531         runner_mock = Mock()
532         sys_exit_mock = Mock()
533         stderr = StringIO()
534         self.patch(sys, "argv", ["tahoe"])
535         self.patch(runner, "runner", runner_mock)
536         self.patch(sys, "exit", sys_exit_mock)
537         self.patch(sys, "stderr", stderr)
538         exc = Exception("canary")
539
540         def call_runner(args, install_node_control=True):
541             raise exc
542         runner_mock.side_effect = call_runner
543
544         runner.run()
545         self.failUnlessEqual(runner_mock.call_args_list, [call([], install_node_control=True)])
546         self.failUnlessEqual(sys_exit_mock.call_args_list, [call(1)])
547         self.failUnlessIn(str(exc), stderr.getvalue())
548
549
550 class Help(unittest.TestCase):
551     def test_get(self):
552         help = str(cli.GetOptions())
553         self.failUnlessIn(" get [options] REMOTE_FILE LOCAL_FILE", help)
554         self.failUnlessIn("% tahoe get FOO |less", help)
555
556     def test_put(self):
557         help = str(cli.PutOptions())
558         self.failUnlessIn(" put [options] LOCAL_FILE REMOTE_FILE", help)
559         self.failUnlessIn("% cat FILE | tahoe put", help)
560
561     def test_ls(self):
562         help = str(cli.ListOptions())
563         self.failUnlessIn(" ls [options] [PATH]", help)
564
565     def test_unlink(self):
566         help = str(cli.UnlinkOptions())
567         self.failUnlessIn(" unlink [options] REMOTE_FILE", help)
568
569     def test_rm(self):
570         help = str(cli.RmOptions())
571         self.failUnlessIn(" rm [options] REMOTE_FILE", help)
572
573     def test_mv(self):
574         help = str(cli.MvOptions())
575         self.failUnlessIn(" mv [options] FROM TO", help)
576         self.failUnlessIn("Use 'tahoe mv' to move files", help)
577
578     def test_cp(self):
579         help = str(cli.CpOptions())
580         self.failUnlessIn(" cp [options] FROM.. TO", help)
581         self.failUnlessIn("Use 'tahoe cp' to copy files", help)
582
583     def test_ln(self):
584         help = str(cli.LnOptions())
585         self.failUnlessIn(" ln [options] FROM_LINK TO_LINK", help)
586         self.failUnlessIn("Use 'tahoe ln' to duplicate a link", help)
587
588     def test_mkdir(self):
589         help = str(cli.MakeDirectoryOptions())
590         self.failUnlessIn(" mkdir [options] [REMOTE_DIR]", help)
591         self.failUnlessIn("Create a new directory", help)
592
593     def test_backup(self):
594         help = str(cli.BackupOptions())
595         self.failUnlessIn(" backup [options] FROM ALIAS:TO", help)
596
597     def test_webopen(self):
598         help = str(cli.WebopenOptions())
599         self.failUnlessIn(" webopen [options] [ALIAS:PATH]", help)
600
601     def test_manifest(self):
602         help = str(cli.ManifestOptions())
603         self.failUnlessIn(" manifest [options] [ALIAS:PATH]", help)
604
605     def test_stats(self):
606         help = str(cli.StatsOptions())
607         self.failUnlessIn(" stats [options] [ALIAS:PATH]", help)
608
609     def test_check(self):
610         help = str(cli.CheckOptions())
611         self.failUnlessIn(" check [options] [ALIAS:PATH]", help)
612
613     def test_deep_check(self):
614         help = str(cli.DeepCheckOptions())
615         self.failUnlessIn(" deep-check [options] [ALIAS:PATH]", help)
616
617     def test_create_alias(self):
618         help = str(cli.CreateAliasOptions())
619         self.failUnlessIn(" create-alias [options] ALIAS[:]", help)
620
621     def test_add_alias(self):
622         help = str(cli.AddAliasOptions())
623         self.failUnlessIn(" add-alias [options] ALIAS[:] DIRCAP", help)
624
625     def test_list_aliases(self):
626         help = str(cli.ListAliasesOptions())
627         self.failUnlessIn(" list-aliases [options]", help)
628
629     def test_start(self):
630         help = str(startstop_node.StartOptions())
631         self.failUnlessIn(" start [options] [NODEDIR]", help)
632
633     def test_stop(self):
634         help = str(startstop_node.StopOptions())
635         self.failUnlessIn(" stop [options] [NODEDIR]", help)
636
637     def test_restart(self):
638         help = str(startstop_node.RestartOptions())
639         self.failUnlessIn(" restart [options] [NODEDIR]", help)
640
641     def test_run(self):
642         help = str(startstop_node.RunOptions())
643         self.failUnlessIn(" run [options] [NODEDIR]", help)
644
645     def test_create_client(self):
646         help = str(create_node.CreateClientOptions())
647         self.failUnlessIn(" create-client [options] [NODEDIR]", help)
648
649     def test_create_node(self):
650         help = str(create_node.CreateNodeOptions())
651         self.failUnlessIn(" create-node [options] [NODEDIR]", help)
652
653     def test_create_introducer(self):
654         help = str(create_node.CreateIntroducerOptions())
655         self.failUnlessIn(" create-introducer [options] NODEDIR", help)
656
657     def test_debug_trial(self):
658         help = str(debug.TrialOptions())
659         self.failUnlessIn(" debug trial [options] [[file|package|module|TestCase|testmethod]...]", help)
660         self.failUnlessIn("The 'tahoe debug trial' command uses the correct imports", help)
661
662     def test_debug_flogtool(self):
663         options = debug.FlogtoolOptions()
664         help = str(options)
665         self.failUnlessIn(" debug flogtool ", help)
666         self.failUnlessIn("The 'tahoe debug flogtool' command uses the correct imports", help)
667
668         for (option, shortcut, oClass, desc) in options.subCommands:
669             subhelp = str(oClass())
670             self.failUnlessIn(" debug flogtool %s " % (option,), subhelp)
671
672
673 class CreateAlias(GridTestMixin, CLITestMixin, unittest.TestCase):
674
675     def _test_webopen(self, args, expected_url):
676         o = runner.Options()
677         o.parseOptions(["--node-directory", self.get_clientdir(), "webopen"]
678                        + list(args))
679         urls = []
680         rc = cli.webopen(o, urls.append)
681         self.failUnlessReallyEqual(rc, 0)
682         self.failUnlessReallyEqual(len(urls), 1)
683         self.failUnlessReallyEqual(urls[0], expected_url)
684
685     def test_create(self):
686         self.basedir = "cli/CreateAlias/create"
687         self.set_up_grid()
688         aliasfile = os.path.join(self.get_clientdir(), "private", "aliases")
689
690         d = self.do_cli("create-alias", "tahoe")
691         def _done((rc,stdout,stderr)):
692             self.failUnless("Alias 'tahoe' created" in stdout)
693             self.failIf(stderr)
694             aliases = get_aliases(self.get_clientdir())
695             self.failUnless("tahoe" in aliases)
696             self.failUnless(aliases["tahoe"].startswith("URI:DIR2:"))
697         d.addCallback(_done)
698         d.addCallback(lambda res: self.do_cli("create-alias", "two:"))
699
700         def _stash_urls(res):
701             aliases = get_aliases(self.get_clientdir())
702             node_url_file = os.path.join(self.get_clientdir(), "node.url")
703             nodeurl = fileutil.read(node_url_file).strip()
704             self.welcome_url = nodeurl
705             uribase = nodeurl + "uri/"
706             self.tahoe_url = uribase + urllib.quote(aliases["tahoe"])
707             self.tahoe_subdir_url = self.tahoe_url + "/subdir"
708             self.two_url = uribase + urllib.quote(aliases["two"])
709             self.two_uri = aliases["two"]
710         d.addCallback(_stash_urls)
711
712         d.addCallback(lambda res: self.do_cli("create-alias", "two")) # dup
713         def _check_create_duplicate((rc,stdout,stderr)):
714             self.failIfEqual(rc, 0)
715             self.failUnless("Alias 'two' already exists!" in stderr)
716             aliases = get_aliases(self.get_clientdir())
717             self.failUnlessReallyEqual(aliases["two"], self.two_uri)
718         d.addCallback(_check_create_duplicate)
719
720         d.addCallback(lambda res: self.do_cli("add-alias", "added", self.two_uri))
721         def _check_add((rc,stdout,stderr)):
722             self.failUnlessReallyEqual(rc, 0)
723             self.failUnless("Alias 'added' added" in stdout)
724         d.addCallback(_check_add)
725
726         # check add-alias with a duplicate
727         d.addCallback(lambda res: self.do_cli("add-alias", "two", self.two_uri))
728         def _check_add_duplicate((rc,stdout,stderr)):
729             self.failIfEqual(rc, 0)
730             self.failUnless("Alias 'two' already exists!" in stderr)
731             aliases = get_aliases(self.get_clientdir())
732             self.failUnlessReallyEqual(aliases["two"], self.two_uri)
733         d.addCallback(_check_add_duplicate)
734
735         # check create-alias and add-alias with invalid aliases
736         def _check_invalid((rc,stdout,stderr)):
737             self.failIfEqual(rc, 0)
738             self.failUnlessIn("cannot contain", stderr)
739
740         for invalid in ['foo:bar', 'foo bar', 'foobar::']:
741             d.addCallback(lambda res, invalid=invalid: self.do_cli("create-alias", invalid))
742             d.addCallback(_check_invalid)
743             d.addCallback(lambda res, invalid=invalid: self.do_cli("add-alias", invalid, self.two_uri))
744             d.addCallback(_check_invalid)
745
746         def _test_urls(junk):
747             self._test_webopen([], self.welcome_url)
748             self._test_webopen(["/"], self.tahoe_url)
749             self._test_webopen(["tahoe:"], self.tahoe_url)
750             self._test_webopen(["tahoe:/"], self.tahoe_url)
751             self._test_webopen(["tahoe:subdir"], self.tahoe_subdir_url)
752             self._test_webopen(["-i", "tahoe:subdir"],
753                                self.tahoe_subdir_url+"?t=info")
754             self._test_webopen(["tahoe:subdir/"], self.tahoe_subdir_url + '/')
755             self._test_webopen(["tahoe:subdir/file"],
756                                self.tahoe_subdir_url + '/file')
757             self._test_webopen(["--info", "tahoe:subdir/file"],
758                                self.tahoe_subdir_url + '/file?t=info')
759             # if "file" is indeed a file, then the url produced by webopen in
760             # this case is disallowed by the webui. but by design, webopen
761             # passes through the mistake from the user to the resultant
762             # webopened url
763             self._test_webopen(["tahoe:subdir/file/"], self.tahoe_subdir_url + '/file/')
764             self._test_webopen(["two:"], self.two_url)
765         d.addCallback(_test_urls)
766
767         def _remove_trailing_newline_and_create_alias(ign):
768             # ticket #741 is about a manually-edited alias file (which
769             # doesn't end in a newline) being corrupted by a subsequent
770             # "tahoe create-alias"
771             old = fileutil.read(aliasfile)
772             fileutil.write(aliasfile, old.rstrip())
773             return self.do_cli("create-alias", "un-corrupted1")
774         d.addCallback(_remove_trailing_newline_and_create_alias)
775         def _check_not_corrupted1((rc,stdout,stderr)):
776             self.failUnless("Alias 'un-corrupted1' created" in stdout, stdout)
777             self.failIf(stderr)
778             # the old behavior was to simply append the new record, causing a
779             # line that looked like "NAME1: CAP1NAME2: CAP2". This won't look
780             # like a valid dircap, so get_aliases() will raise an exception.
781             aliases = get_aliases(self.get_clientdir())
782             self.failUnless("added" in aliases)
783             self.failUnless(aliases["added"].startswith("URI:DIR2:"))
784             # to be safe, let's confirm that we don't see "NAME2:" in CAP1.
785             # No chance of a false-negative, because the hyphen in
786             # "un-corrupted1" is not a valid base32 character.
787             self.failIfIn("un-corrupted1:", aliases["added"])
788             self.failUnless("un-corrupted1" in aliases)
789             self.failUnless(aliases["un-corrupted1"].startswith("URI:DIR2:"))
790         d.addCallback(_check_not_corrupted1)
791
792         def _remove_trailing_newline_and_add_alias(ign):
793             # same thing, but for "tahoe add-alias"
794             old = fileutil.read(aliasfile)
795             fileutil.write(aliasfile, old.rstrip())
796             return self.do_cli("add-alias", "un-corrupted2", self.two_uri)
797         d.addCallback(_remove_trailing_newline_and_add_alias)
798         def _check_not_corrupted((rc,stdout,stderr)):
799             self.failUnless("Alias 'un-corrupted2' added" in stdout, stdout)
800             self.failIf(stderr)
801             aliases = get_aliases(self.get_clientdir())
802             self.failUnless("un-corrupted1" in aliases)
803             self.failUnless(aliases["un-corrupted1"].startswith("URI:DIR2:"))
804             self.failIfIn("un-corrupted2:", aliases["un-corrupted1"])
805             self.failUnless("un-corrupted2" in aliases)
806             self.failUnless(aliases["un-corrupted2"].startswith("URI:DIR2:"))
807         d.addCallback(_check_not_corrupted)
808
809     def test_create_unicode(self):
810         self.basedir = "cli/CreateAlias/create_unicode"
811         self.set_up_grid()
812
813         try:
814             etudes_arg = u"\u00E9tudes".encode(get_io_encoding())
815             lumiere_arg = u"lumi\u00E8re.txt".encode(get_io_encoding())
816         except UnicodeEncodeError:
817             raise unittest.SkipTest("A non-ASCII command argument could not be encoded on this platform.")
818
819         d = self.do_cli("create-alias", etudes_arg)
820         def _check_create_unicode((rc, out, err)):
821             self.failUnlessReallyEqual(rc, 0)
822             self.failUnlessReallyEqual(err, "")
823             self.failUnlessIn("Alias %s created" % quote_output(u"\u00E9tudes"), out)
824
825             aliases = get_aliases(self.get_clientdir())
826             self.failUnless(aliases[u"\u00E9tudes"].startswith("URI:DIR2:"))
827         d.addCallback(_check_create_unicode)
828
829         d.addCallback(lambda res: self.do_cli("ls", etudes_arg + ":"))
830         def _check_ls1((rc, out, err)):
831             self.failUnlessReallyEqual(rc, 0)
832             self.failUnlessReallyEqual(err, "")
833             self.failUnlessReallyEqual(out, "")
834         d.addCallback(_check_ls1)
835
836         d.addCallback(lambda res: self.do_cli("put", "-", etudes_arg + ":uploaded.txt",
837                                               stdin="Blah blah blah"))
838
839         d.addCallback(lambda res: self.do_cli("ls", etudes_arg + ":"))
840         def _check_ls2((rc, out, err)):
841             self.failUnlessReallyEqual(rc, 0)
842             self.failUnlessReallyEqual(err, "")
843             self.failUnlessReallyEqual(out, "uploaded.txt\n")
844         d.addCallback(_check_ls2)
845
846         d.addCallback(lambda res: self.do_cli("get", etudes_arg + ":uploaded.txt"))
847         def _check_get((rc, out, err)):
848             self.failUnlessReallyEqual(rc, 0)
849             self.failUnlessReallyEqual(err, "")
850             self.failUnlessReallyEqual(out, "Blah blah blah")
851         d.addCallback(_check_get)
852
853         # Ensure that an Unicode filename in an Unicode alias works as expected
854         d.addCallback(lambda res: self.do_cli("put", "-", etudes_arg + ":" + lumiere_arg,
855                                               stdin="Let the sunshine In!"))
856
857         d.addCallback(lambda res: self.do_cli("get",
858                                               get_aliases(self.get_clientdir())[u"\u00E9tudes"] + "/" + lumiere_arg))
859         def _check_get2((rc, out, err)):
860             self.failUnlessReallyEqual(rc, 0)
861             self.failUnlessReallyEqual(err, "")
862             self.failUnlessReallyEqual(out, "Let the sunshine In!")
863         d.addCallback(_check_get2)
864
865         return d
866
867     # TODO: test list-aliases, including Unicode
868
869
870 class Ln(GridTestMixin, CLITestMixin, unittest.TestCase):
871     def _create_test_file(self):
872         data = "puppies" * 1000
873         path = os.path.join(self.basedir, "datafile")
874         fileutil.write(path, data)
875         self.datafile = path
876
877     def test_ln_without_alias(self):
878         # if invoked without an alias when the 'tahoe' alias doesn't
879         # exist, 'tahoe ln' should output a useful error message and not
880         # a stack trace
881         self.basedir = "cli/Ln/ln_without_alias"
882         self.set_up_grid()
883         d = self.do_cli("ln", "from", "to")
884         def _check((rc, out, err)):
885             self.failUnlessReallyEqual(rc, 1)
886             self.failUnlessIn("error:", err)
887             self.failUnlessReallyEqual(out, "")
888         d.addCallback(_check)
889         # Make sure that validation extends to the "to" parameter
890         d.addCallback(lambda ign: self.do_cli("create-alias", "havasu"))
891         d.addCallback(lambda ign: self._create_test_file())
892         d.addCallback(lambda ign: self.do_cli("put", self.datafile,
893                                               "havasu:from"))
894         d.addCallback(lambda ign: self.do_cli("ln", "havasu:from", "to"))
895         d.addCallback(_check)
896         return d
897
898     def test_ln_with_nonexistent_alias(self):
899         # If invoked with aliases that don't exist, 'tahoe ln' should
900         # output a useful error message and not a stack trace.
901         self.basedir = "cli/Ln/ln_with_nonexistent_alias"
902         self.set_up_grid()
903         d = self.do_cli("ln", "havasu:from", "havasu:to")
904         def _check((rc, out, err)):
905             self.failUnlessReallyEqual(rc, 1)
906             self.failUnlessIn("error:", err)
907         d.addCallback(_check)
908         # Make sure that validation occurs on the to parameter if the
909         # from parameter passes.
910         d.addCallback(lambda ign: self.do_cli("create-alias", "havasu"))
911         d.addCallback(lambda ign: self._create_test_file())
912         d.addCallback(lambda ign: self.do_cli("put", self.datafile,
913                                               "havasu:from"))
914         d.addCallback(lambda ign: self.do_cli("ln", "havasu:from", "huron:to"))
915         d.addCallback(_check)
916         return d
917
918
919 class Put(GridTestMixin, CLITestMixin, unittest.TestCase):
920
921     def test_unlinked_immutable_stdin(self):
922         # tahoe get `echo DATA | tahoe put`
923         # tahoe get `echo DATA | tahoe put -`
924         self.basedir = "cli/Put/unlinked_immutable_stdin"
925         DATA = "data" * 100
926         self.set_up_grid()
927         d = self.do_cli("put", stdin=DATA)
928         def _uploaded(res):
929             (rc, out, err) = res
930             self.failUnlessIn("waiting for file data on stdin..", err)
931             self.failUnlessIn("200 OK", err)
932             self.readcap = out
933             self.failUnless(self.readcap.startswith("URI:CHK:"))
934         d.addCallback(_uploaded)
935         d.addCallback(lambda res: self.do_cli("get", self.readcap))
936         def _downloaded(res):
937             (rc, out, err) = res
938             self.failUnlessReallyEqual(err, "")
939             self.failUnlessReallyEqual(out, DATA)
940         d.addCallback(_downloaded)
941         d.addCallback(lambda res: self.do_cli("put", "-", stdin=DATA))
942         d.addCallback(lambda (rc, out, err):
943                       self.failUnlessReallyEqual(out, self.readcap))
944         return d
945
946     def test_unlinked_immutable_from_file(self):
947         # tahoe put file.txt
948         # tahoe put ./file.txt
949         # tahoe put /tmp/file.txt
950         # tahoe put ~/file.txt
951         self.basedir = "cli/Put/unlinked_immutable_from_file"
952         self.set_up_grid()
953
954         rel_fn = os.path.join(self.basedir, "DATAFILE")
955         abs_fn = unicode_to_argv(abspath_expanduser_unicode(unicode(rel_fn)))
956         # we make the file small enough to fit in a LIT file, for speed
957         fileutil.write(rel_fn, "short file")
958         d = self.do_cli("put", rel_fn)
959         def _uploaded((rc, out, err)):
960             readcap = out
961             self.failUnless(readcap.startswith("URI:LIT:"), readcap)
962             self.readcap = readcap
963         d.addCallback(_uploaded)
964         d.addCallback(lambda res: self.do_cli("put", "./" + rel_fn))
965         d.addCallback(lambda (rc,stdout,stderr):
966                       self.failUnlessReallyEqual(stdout, self.readcap))
967         d.addCallback(lambda res: self.do_cli("put", abs_fn))
968         d.addCallback(lambda (rc,stdout,stderr):
969                       self.failUnlessReallyEqual(stdout, self.readcap))
970         # we just have to assume that ~ is handled properly
971         return d
972
973     def test_immutable_from_file(self):
974         # tahoe put file.txt uploaded.txt
975         # tahoe - uploaded.txt
976         # tahoe put file.txt subdir/uploaded.txt
977         # tahoe put file.txt tahoe:uploaded.txt
978         # tahoe put file.txt tahoe:subdir/uploaded.txt
979         # tahoe put file.txt DIRCAP:./uploaded.txt
980         # tahoe put file.txt DIRCAP:./subdir/uploaded.txt
981         self.basedir = "cli/Put/immutable_from_file"
982         self.set_up_grid()
983
984         rel_fn = os.path.join(self.basedir, "DATAFILE")
985         # we make the file small enough to fit in a LIT file, for speed
986         DATA = "short file"
987         DATA2 = "short file two"
988         fileutil.write(rel_fn, DATA)
989
990         d = self.do_cli("create-alias", "tahoe")
991
992         d.addCallback(lambda res:
993                       self.do_cli("put", rel_fn, "uploaded.txt"))
994         def _uploaded((rc, out, err)):
995             readcap = out.strip()
996             self.failUnless(readcap.startswith("URI:LIT:"), readcap)
997             self.failUnlessIn("201 Created", err)
998             self.readcap = readcap
999         d.addCallback(_uploaded)
1000         d.addCallback(lambda res:
1001                       self.do_cli("get", "tahoe:uploaded.txt"))
1002         d.addCallback(lambda (rc,stdout,stderr):
1003                       self.failUnlessReallyEqual(stdout, DATA))
1004
1005         d.addCallback(lambda res:
1006                       self.do_cli("put", "-", "uploaded.txt", stdin=DATA2))
1007         def _replaced((rc, out, err)):
1008             readcap = out.strip()
1009             self.failUnless(readcap.startswith("URI:LIT:"), readcap)
1010             self.failUnlessIn("200 OK", err)
1011         d.addCallback(_replaced)
1012
1013         d.addCallback(lambda res:
1014                       self.do_cli("put", rel_fn, "subdir/uploaded2.txt"))
1015         d.addCallback(lambda res: self.do_cli("get", "subdir/uploaded2.txt"))
1016         d.addCallback(lambda (rc,stdout,stderr):
1017                       self.failUnlessReallyEqual(stdout, DATA))
1018
1019         d.addCallback(lambda res:
1020                       self.do_cli("put", rel_fn, "tahoe:uploaded3.txt"))
1021         d.addCallback(lambda res: self.do_cli("get", "tahoe:uploaded3.txt"))
1022         d.addCallback(lambda (rc,stdout,stderr):
1023                       self.failUnlessReallyEqual(stdout, DATA))
1024
1025         d.addCallback(lambda res:
1026                       self.do_cli("put", rel_fn, "tahoe:subdir/uploaded4.txt"))
1027         d.addCallback(lambda res:
1028                       self.do_cli("get", "tahoe:subdir/uploaded4.txt"))
1029         d.addCallback(lambda (rc,stdout,stderr):
1030                       self.failUnlessReallyEqual(stdout, DATA))
1031
1032         def _get_dircap(res):
1033             self.dircap = get_aliases(self.get_clientdir())["tahoe"]
1034         d.addCallback(_get_dircap)
1035
1036         d.addCallback(lambda res:
1037                       self.do_cli("put", rel_fn,
1038                                   self.dircap+":./uploaded5.txt"))
1039         d.addCallback(lambda res:
1040                       self.do_cli("get", "tahoe:uploaded5.txt"))
1041         d.addCallback(lambda (rc,stdout,stderr):
1042                       self.failUnlessReallyEqual(stdout, DATA))
1043
1044         d.addCallback(lambda res:
1045                       self.do_cli("put", rel_fn,
1046                                   self.dircap+":./subdir/uploaded6.txt"))
1047         d.addCallback(lambda res:
1048                       self.do_cli("get", "tahoe:subdir/uploaded6.txt"))
1049         d.addCallback(lambda (rc,stdout,stderr):
1050                       self.failUnlessReallyEqual(stdout, DATA))
1051
1052         return d
1053
1054     def test_mutable_unlinked(self):
1055         # FILECAP = `echo DATA | tahoe put --mutable`
1056         # tahoe get FILECAP, compare against DATA
1057         # echo DATA2 | tahoe put - FILECAP
1058         # tahoe get FILECAP, compare against DATA2
1059         # tahoe put file.txt FILECAP
1060         self.basedir = "cli/Put/mutable_unlinked"
1061         self.set_up_grid()
1062
1063         DATA = "data" * 100
1064         DATA2 = "two" * 100
1065         rel_fn = os.path.join(self.basedir, "DATAFILE")
1066         DATA3 = "three" * 100
1067         fileutil.write(rel_fn, DATA3)
1068
1069         d = self.do_cli("put", "--mutable", stdin=DATA)
1070         def _created(res):
1071             (rc, out, err) = res
1072             self.failUnlessIn("waiting for file data on stdin..", err)
1073             self.failUnlessIn("200 OK", err)
1074             self.filecap = out
1075             self.failUnless(self.filecap.startswith("URI:SSK:"), self.filecap)
1076         d.addCallback(_created)
1077         d.addCallback(lambda res: self.do_cli("get", self.filecap))
1078         d.addCallback(lambda (rc,out,err): self.failUnlessReallyEqual(out, DATA))
1079
1080         d.addCallback(lambda res: self.do_cli("put", "-", self.filecap, stdin=DATA2))
1081         def _replaced(res):
1082             (rc, out, err) = res
1083             self.failUnlessIn("waiting for file data on stdin..", err)
1084             self.failUnlessIn("200 OK", err)
1085             self.failUnlessReallyEqual(self.filecap, out)
1086         d.addCallback(_replaced)
1087         d.addCallback(lambda res: self.do_cli("get", self.filecap))
1088         d.addCallback(lambda (rc,out,err): self.failUnlessReallyEqual(out, DATA2))
1089
1090         d.addCallback(lambda res: self.do_cli("put", rel_fn, self.filecap))
1091         def _replaced2(res):
1092             (rc, out, err) = res
1093             self.failUnlessIn("200 OK", err)
1094             self.failUnlessReallyEqual(self.filecap, out)
1095         d.addCallback(_replaced2)
1096         d.addCallback(lambda res: self.do_cli("get", self.filecap))
1097         d.addCallback(lambda (rc,out,err): self.failUnlessReallyEqual(out, DATA3))
1098
1099         return d
1100
1101     def test_mutable(self):
1102         # echo DATA1 | tahoe put --mutable - uploaded.txt
1103         # echo DATA2 | tahoe put - uploaded.txt # should modify-in-place
1104         # tahoe get uploaded.txt, compare against DATA2
1105
1106         self.basedir = "cli/Put/mutable"
1107         self.set_up_grid()
1108
1109         DATA1 = "data" * 100
1110         fn1 = os.path.join(self.basedir, "DATA1")
1111         fileutil.write(fn1, DATA1)
1112         DATA2 = "two" * 100
1113         fn2 = os.path.join(self.basedir, "DATA2")
1114         fileutil.write(fn2, DATA2)
1115
1116         d = self.do_cli("create-alias", "tahoe")
1117         d.addCallback(lambda res:
1118                       self.do_cli("put", "--mutable", fn1, "tahoe:uploaded.txt"))
1119         def _check(res):
1120             (rc, out, err) = res
1121             self.failUnlessEqual(rc, 0, str(res))
1122             self.failUnlessEqual(err.strip(), "201 Created", str(res))
1123             self.uri = out
1124         d.addCallback(_check)
1125         d.addCallback(lambda res:
1126                       self.do_cli("put", fn2, "tahoe:uploaded.txt"))
1127         def _check2(res):
1128             (rc, out, err) = res
1129             self.failUnlessEqual(rc, 0, str(res))
1130             self.failUnlessEqual(err.strip(), "200 OK", str(res))
1131             self.failUnlessEqual(out, self.uri, str(res))
1132         d.addCallback(_check2)
1133         d.addCallback(lambda res:
1134                       self.do_cli("get", "tahoe:uploaded.txt"))
1135         d.addCallback(lambda (rc,out,err): self.failUnlessReallyEqual(out, DATA2))
1136         return d
1137
1138     def _check_mdmf_json(self, (rc, json, err)):
1139          self.failUnlessEqual(rc, 0)
1140          self.failUnlessEqual(err, "")
1141          self.failUnlessIn('"format": "MDMF"', json)
1142          # We also want a valid MDMF cap to be in the json.
1143          self.failUnlessIn("URI:MDMF", json)
1144          self.failUnlessIn("URI:MDMF-RO", json)
1145          self.failUnlessIn("URI:MDMF-Verifier", json)
1146
1147     def _check_sdmf_json(self, (rc, json, err)):
1148         self.failUnlessEqual(rc, 0)
1149         self.failUnlessEqual(err, "")
1150         self.failUnlessIn('"format": "SDMF"', json)
1151         # We also want to see the appropriate SDMF caps.
1152         self.failUnlessIn("URI:SSK", json)
1153         self.failUnlessIn("URI:SSK-RO", json)
1154         self.failUnlessIn("URI:SSK-Verifier", json)
1155
1156     def _check_chk_json(self, (rc, json, err)):
1157         self.failUnlessEqual(rc, 0)
1158         self.failUnlessEqual(err, "")
1159         self.failUnlessIn('"format": "CHK"', json)
1160         # We also want to see the appropriate CHK caps.
1161         self.failUnlessIn("URI:CHK", json)
1162         self.failUnlessIn("URI:CHK-Verifier", json)
1163
1164     def test_format(self):
1165         self.basedir = "cli/Put/format"
1166         self.set_up_grid()
1167         data = "data" * 40000 # 160kB total, two segments
1168         fn1 = os.path.join(self.basedir, "data")
1169         fileutil.write(fn1, data)
1170         d = self.do_cli("create-alias", "tahoe")
1171
1172         def _put_and_ls(ign, cmdargs, expected, filename=None):
1173             if filename:
1174                 args = ["put"] + cmdargs + [fn1, filename]
1175             else:
1176                 # unlinked
1177                 args = ["put"] + cmdargs + [fn1]
1178             d2 = self.do_cli(*args)
1179             def _list((rc, out, err)):
1180                 self.failUnlessEqual(rc, 0) # don't allow failure
1181                 if filename:
1182                     return self.do_cli("ls", "--json", filename)
1183                 else:
1184                     cap = out.strip()
1185                     return self.do_cli("ls", "--json", cap)
1186             d2.addCallback(_list)
1187             return d2
1188
1189         # 'tahoe put' to a directory
1190         d.addCallback(_put_and_ls, ["--mutable"], "SDMF", "tahoe:s1.txt")
1191         d.addCallback(self._check_sdmf_json) # backwards-compatibility
1192         d.addCallback(_put_and_ls, ["--format=SDMF"], "SDMF", "tahoe:s2.txt")
1193         d.addCallback(self._check_sdmf_json)
1194         d.addCallback(_put_and_ls, ["--format=sdmf"], "SDMF", "tahoe:s3.txt")
1195         d.addCallback(self._check_sdmf_json)
1196         d.addCallback(_put_and_ls, ["--mutable", "--format=SDMF"], "SDMF", "tahoe:s4.txt")
1197         d.addCallback(self._check_sdmf_json)
1198
1199         d.addCallback(_put_and_ls, ["--format=MDMF"], "MDMF", "tahoe:m1.txt")
1200         d.addCallback(self._check_mdmf_json)
1201         d.addCallback(_put_and_ls, ["--mutable", "--format=MDMF"], "MDMF", "tahoe:m2.txt")
1202         d.addCallback(self._check_mdmf_json)
1203
1204         d.addCallback(_put_and_ls, ["--format=CHK"], "CHK", "tahoe:c1.txt")
1205         d.addCallback(self._check_chk_json)
1206         d.addCallback(_put_and_ls, [], "CHK", "tahoe:c1.txt")
1207         d.addCallback(self._check_chk_json)
1208
1209         # 'tahoe put' unlinked
1210         d.addCallback(_put_and_ls, ["--mutable"], "SDMF")
1211         d.addCallback(self._check_sdmf_json) # backwards-compatibility
1212         d.addCallback(_put_and_ls, ["--format=SDMF"], "SDMF")
1213         d.addCallback(self._check_sdmf_json)
1214         d.addCallback(_put_and_ls, ["--format=sdmf"], "SDMF")
1215         d.addCallback(self._check_sdmf_json)
1216         d.addCallback(_put_and_ls, ["--mutable", "--format=SDMF"], "SDMF")
1217         d.addCallback(self._check_sdmf_json)
1218
1219         d.addCallback(_put_and_ls, ["--format=MDMF"], "MDMF")
1220         d.addCallback(self._check_mdmf_json)
1221         d.addCallback(_put_and_ls, ["--mutable", "--format=MDMF"], "MDMF")
1222         d.addCallback(self._check_mdmf_json)
1223
1224         d.addCallback(_put_and_ls, ["--format=CHK"], "CHK")
1225         d.addCallback(self._check_chk_json)
1226         d.addCallback(_put_and_ls, [], "CHK")
1227         d.addCallback(self._check_chk_json)
1228
1229         return d
1230
1231     def test_put_to_mdmf_cap(self):
1232         self.basedir = "cli/Put/put_to_mdmf_cap"
1233         self.set_up_grid()
1234         data = "data" * 100000
1235         fn1 = os.path.join(self.basedir, "data")
1236         fileutil.write(fn1, data)
1237         d = self.do_cli("put", "--format=MDMF", fn1)
1238         def _got_cap((rc, out, err)):
1239             self.failUnlessEqual(rc, 0)
1240             self.cap = out.strip()
1241         d.addCallback(_got_cap)
1242         # Now try to write something to the cap using put.
1243         data2 = "data2" * 100000
1244         fn2 = os.path.join(self.basedir, "data2")
1245         fileutil.write(fn2, data2)
1246         d.addCallback(lambda ignored:
1247             self.do_cli("put", fn2, self.cap))
1248         def _got_put((rc, out, err)):
1249             self.failUnlessEqual(rc, 0)
1250             self.failUnlessIn(self.cap, out)
1251         d.addCallback(_got_put)
1252         # Now get the cap. We should see the data we just put there.
1253         d.addCallback(lambda ignored:
1254             self.do_cli("get", self.cap))
1255         def _got_data((rc, out, err)):
1256             self.failUnlessEqual(rc, 0)
1257             self.failUnlessEqual(out, data2)
1258         d.addCallback(_got_data)
1259         # add some extension information to the cap and try to put something
1260         # to it.
1261         def _make_extended_cap(ignored):
1262             self.cap = self.cap + ":Extension-Stuff"
1263         d.addCallback(_make_extended_cap)
1264         data3 = "data3" * 100000
1265         fn3 = os.path.join(self.basedir, "data3")
1266         fileutil.write(fn3, data3)
1267         d.addCallback(lambda ignored:
1268             self.do_cli("put", fn3, self.cap))
1269         d.addCallback(lambda ignored:
1270             self.do_cli("get", self.cap))
1271         def _got_data3((rc, out, err)):
1272             self.failUnlessEqual(rc, 0)
1273             self.failUnlessEqual(out, data3)
1274         d.addCallback(_got_data3)
1275         return d
1276
1277     def test_put_to_sdmf_cap(self):
1278         self.basedir = "cli/Put/put_to_sdmf_cap"
1279         self.set_up_grid()
1280         data = "data" * 100000
1281         fn1 = os.path.join(self.basedir, "data")
1282         fileutil.write(fn1, data)
1283         d = self.do_cli("put", "--format=SDMF", fn1)
1284         def _got_cap((rc, out, err)):
1285             self.failUnlessEqual(rc, 0)
1286             self.cap = out.strip()
1287         d.addCallback(_got_cap)
1288         # Now try to write something to the cap using put.
1289         data2 = "data2" * 100000
1290         fn2 = os.path.join(self.basedir, "data2")
1291         fileutil.write(fn2, data2)
1292         d.addCallback(lambda ignored:
1293             self.do_cli("put", fn2, self.cap))
1294         def _got_put((rc, out, err)):
1295             self.failUnlessEqual(rc, 0)
1296             self.failUnlessIn(self.cap, out)
1297         d.addCallback(_got_put)
1298         # Now get the cap. We should see the data we just put there.
1299         d.addCallback(lambda ignored:
1300             self.do_cli("get", self.cap))
1301         def _got_data((rc, out, err)):
1302             self.failUnlessEqual(rc, 0)
1303             self.failUnlessEqual(out, data2)
1304         d.addCallback(_got_data)
1305         return d
1306
1307     def test_mutable_type_invalid_format(self):
1308         o = cli.PutOptions()
1309         self.failUnlessRaises(usage.UsageError,
1310                               o.parseOptions,
1311                               ["--format=LDMF"])
1312
1313     def test_put_with_nonexistent_alias(self):
1314         # when invoked with an alias that doesn't exist, 'tahoe put'
1315         # should output a useful error message, not a stack trace
1316         self.basedir = "cli/Put/put_with_nonexistent_alias"
1317         self.set_up_grid()
1318         d = self.do_cli("put", "somefile", "fake:afile")
1319         def _check((rc, out, err)):
1320             self.failUnlessReallyEqual(rc, 1)
1321             self.failUnlessIn("error:", err)
1322             self.failUnlessReallyEqual(out, "")
1323         d.addCallback(_check)
1324         return d
1325
1326     def test_immutable_from_file_unicode(self):
1327         # tahoe put "\u00E0 trier.txt" "\u00E0 trier.txt"
1328
1329         try:
1330             a_trier_arg = u"\u00E0 trier.txt".encode(get_io_encoding())
1331         except UnicodeEncodeError:
1332             raise unittest.SkipTest("A non-ASCII command argument could not be encoded on this platform.")
1333
1334         self.skip_if_cannot_represent_filename(u"\u00E0 trier.txt")
1335
1336         self.basedir = "cli/Put/immutable_from_file_unicode"
1337         self.set_up_grid()
1338
1339         rel_fn = os.path.join(unicode(self.basedir), u"\u00E0 trier.txt")
1340         # we make the file small enough to fit in a LIT file, for speed
1341         DATA = "short file"
1342         fileutil.write(rel_fn, DATA)
1343
1344         d = self.do_cli("create-alias", "tahoe")
1345
1346         d.addCallback(lambda res:
1347                       self.do_cli("put", rel_fn.encode(get_io_encoding()), a_trier_arg))
1348         def _uploaded((rc, out, err)):
1349             readcap = out.strip()
1350             self.failUnless(readcap.startswith("URI:LIT:"), readcap)
1351             self.failUnlessIn("201 Created", err)
1352             self.readcap = readcap
1353         d.addCallback(_uploaded)
1354
1355         d.addCallback(lambda res:
1356                       self.do_cli("get", "tahoe:" + a_trier_arg))
1357         d.addCallback(lambda (rc, out, err):
1358                       self.failUnlessReallyEqual(out, DATA))
1359
1360         return d
1361
1362 class Admin(unittest.TestCase):
1363     def do_cli(self, *args, **kwargs):
1364         argv = list(args)
1365         stdin = kwargs.get("stdin", "")
1366         stdout, stderr = StringIO(), StringIO()
1367         d = threads.deferToThread(runner.runner, argv, run_by_human=False,
1368                                   stdin=StringIO(stdin),
1369                                   stdout=stdout, stderr=stderr)
1370         def _done(res):
1371             return stdout.getvalue(), stderr.getvalue()
1372         d.addCallback(_done)
1373         return d
1374
1375     def test_generate_keypair(self):
1376         d = self.do_cli("admin", "generate-keypair")
1377         def _done( (stdout, stderr) ):
1378             lines = [line.strip() for line in stdout.splitlines()]
1379             privkey_bits = lines[0].split()
1380             pubkey_bits = lines[1].split()
1381             sk_header = "private:"
1382             vk_header = "public:"
1383             self.failUnlessEqual(privkey_bits[0], sk_header, lines[0])
1384             self.failUnlessEqual(pubkey_bits[0], vk_header, lines[1])
1385             self.failUnless(privkey_bits[1].startswith("priv-v0-"), lines[0])
1386             self.failUnless(pubkey_bits[1].startswith("pub-v0-"), lines[1])
1387             sk_bytes = base32.a2b(keyutil.remove_prefix(privkey_bits[1], "priv-v0-"))
1388             sk = ed25519.SigningKey(sk_bytes)
1389             vk_bytes = base32.a2b(keyutil.remove_prefix(pubkey_bits[1], "pub-v0-"))
1390             self.failUnlessEqual(sk.get_verifying_key_bytes(), vk_bytes)
1391         d.addCallback(_done)
1392         return d
1393
1394     def test_derive_pubkey(self):
1395         priv1,pub1 = keyutil.make_keypair()
1396         d = self.do_cli("admin", "derive-pubkey", priv1)
1397         def _done( (stdout, stderr) ):
1398             lines = stdout.split("\n")
1399             privkey_line = lines[0].strip()
1400             pubkey_line = lines[1].strip()
1401             sk_header = "private: priv-v0-"
1402             vk_header = "public: pub-v0-"
1403             self.failUnless(privkey_line.startswith(sk_header), privkey_line)
1404             self.failUnless(pubkey_line.startswith(vk_header), pubkey_line)
1405             pub2 = pubkey_line[len(vk_header):]
1406             self.failUnlessEqual("pub-v0-"+pub2, pub1)
1407         d.addCallback(_done)
1408         return d
1409
1410
1411 class List(GridTestMixin, CLITestMixin, unittest.TestCase):
1412     def test_list(self):
1413         self.basedir = "cli/List/list"
1414         self.set_up_grid()
1415         c0 = self.g.clients[0]
1416         small = "small"
1417
1418         # u"g\u00F6\u00F6d" might not be representable in the argv and/or output encodings.
1419         # It is initially included in the directory in any case.
1420         try:
1421             good_arg = u"g\u00F6\u00F6d".encode(get_io_encoding())
1422         except UnicodeEncodeError:
1423             good_arg = None
1424
1425         try:
1426             good_out = u"g\u00F6\u00F6d".encode(get_io_encoding())
1427         except UnicodeEncodeError:
1428             good_out = None
1429
1430         d = c0.create_dirnode()
1431         def _stash_root_and_create_file(n):
1432             self.rootnode = n
1433             self.rooturi = n.get_uri()
1434             return n.add_file(u"g\u00F6\u00F6d", upload.Data(small, convergence=""))
1435         d.addCallback(_stash_root_and_create_file)
1436         def _stash_goodcap(n):
1437             self.goodcap = n.get_uri()
1438         d.addCallback(_stash_goodcap)
1439         d.addCallback(lambda ign: self.rootnode.create_subdirectory(u"1share"))
1440         d.addCallback(lambda n:
1441                       self.delete_shares_numbered(n.get_uri(), range(1,10)))
1442         d.addCallback(lambda ign: self.rootnode.create_subdirectory(u"0share"))
1443         d.addCallback(lambda n:
1444                       self.delete_shares_numbered(n.get_uri(), range(0,10)))
1445         d.addCallback(lambda ign:
1446                       self.do_cli("add-alias", "tahoe", self.rooturi))
1447         d.addCallback(lambda ign: self.do_cli("ls"))
1448         def _check1((rc,out,err)):
1449             if good_out is None:
1450                 self.failUnlessReallyEqual(rc, 1)
1451                 self.failUnlessIn("files whose names could not be converted", err)
1452                 self.failUnlessIn(quote_output(u"g\u00F6\u00F6d"), err)
1453                 self.failUnlessReallyEqual(sorted(out.splitlines()), sorted(["0share", "1share"]))
1454             else:
1455                 self.failUnlessReallyEqual(rc, 0)
1456                 self.failUnlessReallyEqual(err, "")
1457                 self.failUnlessReallyEqual(sorted(out.splitlines()), sorted(["0share", "1share", good_out]))
1458         d.addCallback(_check1)
1459         d.addCallback(lambda ign: self.do_cli("ls", "missing"))
1460         def _check2((rc,out,err)):
1461             self.failIfEqual(rc, 0)
1462             self.failUnlessReallyEqual(err.strip(), "No such file or directory")
1463             self.failUnlessReallyEqual(out, "")
1464         d.addCallback(_check2)
1465         d.addCallback(lambda ign: self.do_cli("ls", "1share"))
1466         def _check3((rc,out,err)):
1467             self.failIfEqual(rc, 0)
1468             self.failUnlessIn("Error during GET: 410 Gone", err)
1469             self.failUnlessIn("UnrecoverableFileError:", err)
1470             self.failUnlessIn("could not be retrieved, because there were "
1471                               "insufficient good shares.", err)
1472             self.failUnlessReallyEqual(out, "")
1473         d.addCallback(_check3)
1474         d.addCallback(lambda ign: self.do_cli("ls", "0share"))
1475         d.addCallback(_check3)
1476         def _check4((rc, out, err)):
1477             if good_out is None:
1478                 self.failUnlessReallyEqual(rc, 1)
1479                 self.failUnlessIn("files whose names could not be converted", err)
1480                 self.failUnlessIn(quote_output(u"g\u00F6\u00F6d"), err)
1481                 self.failUnlessReallyEqual(out, "")
1482             else:
1483                 # listing a file (as dir/filename) should have the edge metadata,
1484                 # including the filename
1485                 self.failUnlessReallyEqual(rc, 0)
1486                 self.failUnlessIn(good_out, out)
1487                 self.failIfIn("-r-- %d -" % len(small), out,
1488                               "trailing hyphen means unknown date")
1489
1490         if good_arg is not None:
1491             d.addCallback(lambda ign: self.do_cli("ls", "-l", good_arg))
1492             d.addCallback(_check4)
1493             # listing a file as $DIRCAP/filename should work just like dir/filename
1494             d.addCallback(lambda ign: self.do_cli("ls", "-l", self.rooturi + "/" + good_arg))
1495             d.addCallback(_check4)
1496             # and similarly for $DIRCAP:./filename
1497             d.addCallback(lambda ign: self.do_cli("ls", "-l", self.rooturi + ":./" + good_arg))
1498             d.addCallback(_check4)
1499
1500         def _check5((rc, out, err)):
1501             # listing a raw filecap should not explode, but it will have no
1502             # metadata, just the size
1503             self.failUnlessReallyEqual(rc, 0)
1504             self.failUnlessReallyEqual("-r-- %d -" % len(small), out.strip())
1505         d.addCallback(lambda ign: self.do_cli("ls", "-l", self.goodcap))
1506         d.addCallback(_check5)
1507
1508         # Now rename 'g\u00F6\u00F6d' to 'good' and repeat the tests that might have been skipped due
1509         # to encoding problems.
1510         d.addCallback(lambda ign: self.rootnode.move_child_to(u"g\u00F6\u00F6d", self.rootnode, u"good"))
1511
1512         d.addCallback(lambda ign: self.do_cli("ls"))
1513         def _check1_ascii((rc,out,err)):
1514             self.failUnlessReallyEqual(rc, 0)
1515             self.failUnlessReallyEqual(err, "")
1516             self.failUnlessReallyEqual(sorted(out.splitlines()), sorted(["0share", "1share", "good"]))
1517         d.addCallback(_check1_ascii)
1518         def _check4_ascii((rc, out, err)):
1519             # listing a file (as dir/filename) should have the edge metadata,
1520             # including the filename
1521             self.failUnlessReallyEqual(rc, 0)
1522             self.failUnlessIn("good", out)
1523             self.failIfIn("-r-- %d -" % len(small), out,
1524                           "trailing hyphen means unknown date")
1525
1526         d.addCallback(lambda ign: self.do_cli("ls", "-l", "good"))
1527         d.addCallback(_check4_ascii)
1528         # listing a file as $DIRCAP/filename should work just like dir/filename
1529         d.addCallback(lambda ign: self.do_cli("ls", "-l", self.rooturi + "/good"))
1530         d.addCallback(_check4_ascii)
1531         # and similarly for $DIRCAP:./filename
1532         d.addCallback(lambda ign: self.do_cli("ls", "-l", self.rooturi + ":./good"))
1533         d.addCallback(_check4_ascii)
1534
1535         unknown_immcap = "imm.URI:unknown"
1536         def _create_unknown(ign):
1537             nm = c0.nodemaker
1538             kids = {u"unknownchild-imm": (nm.create_from_cap(unknown_immcap), {})}
1539             return self.rootnode.create_subdirectory(u"unknown", initial_children=kids,
1540                                                      mutable=False)
1541         d.addCallback(_create_unknown)
1542         def _check6((rc, out, err)):
1543             # listing a directory referencing an unknown object should print
1544             # an extra message to stderr
1545             self.failUnlessReallyEqual(rc, 0)
1546             self.failUnlessIn("?r-- ? - unknownchild-imm\n", out)
1547             self.failUnlessIn("included unknown objects", err)
1548         d.addCallback(lambda ign: self.do_cli("ls", "-l", "unknown"))
1549         d.addCallback(_check6)
1550         def _check7((rc, out, err)):
1551             # listing an unknown cap directly should print an extra message
1552             # to stderr (currently this only works if the URI starts with 'URI:'
1553             # after any 'ro.' or 'imm.' prefix, otherwise it will be confused
1554             # with an alias).
1555             self.failUnlessReallyEqual(rc, 0)
1556             self.failUnlessIn("?r-- ? -\n", out)
1557             self.failUnlessIn("included unknown objects", err)
1558         d.addCallback(lambda ign: self.do_cli("ls", "-l", unknown_immcap))
1559         d.addCallback(_check7)
1560         return d
1561
1562     def test_list_without_alias(self):
1563         # doing just 'tahoe ls' without specifying an alias or first
1564         # doing 'tahoe create-alias tahoe' should fail gracefully.
1565         self.basedir = "cli/List/list_without_alias"
1566         self.set_up_grid()
1567         d = self.do_cli("ls")
1568         def _check((rc, out, err)):
1569             self.failUnlessReallyEqual(rc, 1)
1570             self.failUnlessIn("error:", err)
1571             self.failUnlessReallyEqual(out, "")
1572         d.addCallback(_check)
1573         return d
1574
1575     def test_list_with_nonexistent_alias(self):
1576         # doing 'tahoe ls' while specifying an alias that doesn't already
1577         # exist should fail with an informative error message
1578         self.basedir = "cli/List/list_with_nonexistent_alias"
1579         self.set_up_grid()
1580         d = self.do_cli("ls", "nonexistent:")
1581         def _check((rc, out, err)):
1582             self.failUnlessReallyEqual(rc, 1)
1583             self.failUnlessIn("error:", err)
1584             self.failUnlessIn("nonexistent", err)
1585             self.failUnlessReallyEqual(out, "")
1586         d.addCallback(_check)
1587         return d
1588
1589     def _create_directory_structure(self):
1590         # Create a simple directory structure that we can use for MDMF,
1591         # SDMF, and immutable testing.
1592         assert self.g
1593
1594         client = self.g.clients[0]
1595         # Create a dirnode
1596         d = client.create_dirnode()
1597         def _got_rootnode(n):
1598             # Add a few nodes.
1599             self._dircap = n.get_uri()
1600             nm = n._nodemaker
1601             # The uploaders may run at the same time, so we need two
1602             # MutableData instances or they'll fight over offsets &c and
1603             # break.
1604             mutable_data = MutableData("data" * 100000)
1605             mutable_data2 = MutableData("data" * 100000)
1606             # Add both kinds of mutable node.
1607             d1 = nm.create_mutable_file(mutable_data,
1608                                         version=MDMF_VERSION)
1609             d2 = nm.create_mutable_file(mutable_data2,
1610                                         version=SDMF_VERSION)
1611             # Add an immutable node. We do this through the directory,
1612             # with add_file.
1613             immutable_data = upload.Data("immutable data" * 100000,
1614                                          convergence="")
1615             d3 = n.add_file(u"immutable", immutable_data)
1616             ds = [d1, d2, d3]
1617             dl = defer.DeferredList(ds)
1618             def _made_files((r1, r2, r3)):
1619                 self.failUnless(r1[0])
1620                 self.failUnless(r2[0])
1621                 self.failUnless(r3[0])
1622
1623                 # r1, r2, and r3 contain nodes.
1624                 mdmf_node = r1[1]
1625                 sdmf_node = r2[1]
1626                 imm_node = r3[1]
1627
1628                 self._mdmf_uri = mdmf_node.get_uri()
1629                 self._mdmf_readonly_uri = mdmf_node.get_readonly_uri()
1630                 self._sdmf_uri = mdmf_node.get_uri()
1631                 self._sdmf_readonly_uri = sdmf_node.get_readonly_uri()
1632                 self._imm_uri = imm_node.get_uri()
1633
1634                 d1 = n.set_node(u"mdmf", mdmf_node)
1635                 d2 = n.set_node(u"sdmf", sdmf_node)
1636                 return defer.DeferredList([d1, d2])
1637             # We can now list the directory by listing self._dircap.
1638             dl.addCallback(_made_files)
1639             return dl
1640         d.addCallback(_got_rootnode)
1641         return d
1642
1643     def test_list_mdmf(self):
1644         # 'tahoe ls' should include MDMF files.
1645         self.basedir = "cli/List/list_mdmf"
1646         self.set_up_grid()
1647         d = self._create_directory_structure()
1648         d.addCallback(lambda ignored:
1649             self.do_cli("ls", self._dircap))
1650         def _got_ls((rc, out, err)):
1651             self.failUnlessEqual(rc, 0)
1652             self.failUnlessEqual(err, "")
1653             self.failUnlessIn("immutable", out)
1654             self.failUnlessIn("mdmf", out)
1655             self.failUnlessIn("sdmf", out)
1656         d.addCallback(_got_ls)
1657         return d
1658
1659     def test_list_mdmf_json(self):
1660         # 'tahoe ls' should include MDMF caps when invoked with MDMF
1661         # caps.
1662         self.basedir = "cli/List/list_mdmf_json"
1663         self.set_up_grid()
1664         d = self._create_directory_structure()
1665         d.addCallback(lambda ignored:
1666             self.do_cli("ls", "--json", self._dircap))
1667         def _got_json((rc, out, err)):
1668             self.failUnlessEqual(rc, 0)
1669             self.failUnlessEqual(err, "")
1670             self.failUnlessIn(self._mdmf_uri, out)
1671             self.failUnlessIn(self._mdmf_readonly_uri, out)
1672             self.failUnlessIn(self._sdmf_uri, out)
1673             self.failUnlessIn(self._sdmf_readonly_uri, out)
1674             self.failUnlessIn(self._imm_uri, out)
1675             self.failUnlessIn('"format": "SDMF"', out)
1676             self.failUnlessIn('"format": "MDMF"', out)
1677         d.addCallback(_got_json)
1678         return d
1679
1680
1681 class Mv(GridTestMixin, CLITestMixin, unittest.TestCase):
1682     def test_mv_behavior(self):
1683         self.basedir = "cli/Mv/mv_behavior"
1684         self.set_up_grid()
1685         fn1 = os.path.join(self.basedir, "file1")
1686         DATA1 = "Nuclear launch codes"
1687         fileutil.write(fn1, DATA1)
1688         fn2 = os.path.join(self.basedir, "file2")
1689         DATA2 = "UML diagrams"
1690         fileutil.write(fn2, DATA2)
1691         # copy both files to the grid
1692         d = self.do_cli("create-alias", "tahoe")
1693         d.addCallback(lambda res:
1694             self.do_cli("cp", fn1, "tahoe:"))
1695         d.addCallback(lambda res:
1696             self.do_cli("cp", fn2, "tahoe:"))
1697
1698         # do mv file1 file3
1699         # (we should be able to rename files)
1700         d.addCallback(lambda res:
1701             self.do_cli("mv", "tahoe:file1", "tahoe:file3"))
1702         d.addCallback(lambda (rc, out, err):
1703             self.failUnlessIn("OK", out, "mv didn't rename a file"))
1704
1705         # do mv file3 file2
1706         # (This should succeed without issue)
1707         d.addCallback(lambda res:
1708             self.do_cli("mv", "tahoe:file3", "tahoe:file2"))
1709         # Out should contain "OK" to show that the transfer worked.
1710         d.addCallback(lambda (rc,out,err):
1711             self.failUnlessIn("OK", out, "mv didn't output OK after mving"))
1712
1713         # Next, make a remote directory.
1714         d.addCallback(lambda res:
1715             self.do_cli("mkdir", "tahoe:directory"))
1716
1717         # mv file2 directory
1718         # (should fail with a descriptive error message; the CLI mv
1719         #  client should support this)
1720         d.addCallback(lambda res:
1721             self.do_cli("mv", "tahoe:file2", "tahoe:directory"))
1722         d.addCallback(lambda (rc, out, err):
1723             self.failUnlessIn(
1724                 "Error: You can't overwrite a directory with a file", err,
1725                 "mv shouldn't overwrite directories" ))
1726
1727         # mv file2 directory/
1728         # (should succeed by making file2 a child node of directory)
1729         d.addCallback(lambda res:
1730             self.do_cli("mv", "tahoe:file2", "tahoe:directory/"))
1731         # We should see an "OK"...
1732         d.addCallback(lambda (rc, out, err):
1733             self.failUnlessIn("OK", out,
1734                             "mv didn't mv a file into a directory"))
1735         # ... and be able to GET the file
1736         d.addCallback(lambda res:
1737             self.do_cli("get", "tahoe:directory/file2", self.basedir + "new"))
1738         d.addCallback(lambda (rc, out, err):
1739             self.failUnless(os.path.exists(self.basedir + "new"),
1740                             "mv didn't write the destination file"))
1741         # ... and not find the file where it was before.
1742         d.addCallback(lambda res:
1743             self.do_cli("get", "tahoe:file2", "file2"))
1744         d.addCallback(lambda (rc, out, err):
1745             self.failUnlessIn("404", err,
1746                             "mv left the source file intact"))
1747
1748         # Let's build:
1749         # directory/directory2/some_file
1750         # directory3
1751         d.addCallback(lambda res:
1752             self.do_cli("mkdir", "tahoe:directory/directory2"))
1753         d.addCallback(lambda res:
1754             self.do_cli("cp", fn2, "tahoe:directory/directory2/some_file"))
1755         d.addCallback(lambda res:
1756             self.do_cli("mkdir", "tahoe:directory3"))
1757
1758         # Let's now try to mv directory/directory2/some_file to
1759         # directory3/some_file
1760         d.addCallback(lambda res:
1761             self.do_cli("mv", "tahoe:directory/directory2/some_file",
1762                         "tahoe:directory3/"))
1763         # We should have just some_file in tahoe:directory3
1764         d.addCallback(lambda res:
1765             self.do_cli("get", "tahoe:directory3/some_file", "some_file"))
1766         d.addCallback(lambda (rc, out, err):
1767             self.failUnless("404" not in err,
1768                               "mv didn't handle nested directories correctly"))
1769         d.addCallback(lambda res:
1770             self.do_cli("get", "tahoe:directory3/directory", "directory"))
1771         d.addCallback(lambda (rc, out, err):
1772             self.failUnlessIn("404", err,
1773                               "mv moved the wrong thing"))
1774         return d
1775
1776     def test_mv_error_if_DELETE_fails(self):
1777         self.basedir = "cli/Mv/mv_error_if_DELETE_fails"
1778         self.set_up_grid()
1779         fn1 = os.path.join(self.basedir, "file1")
1780         DATA1 = "Nuclear launch codes"
1781         fileutil.write(fn1, DATA1)
1782
1783         original_do_http = tahoe_mv.do_http
1784         def mock_do_http(method, url, body=""):
1785             if method == "DELETE":
1786                 class FakeResponse:
1787                     def read(self):
1788                         return "response"
1789                 resp = FakeResponse()
1790                 resp.status = '500 Something Went Wrong'
1791                 resp.reason = '*shrug*'
1792                 return resp
1793             else:
1794                 return original_do_http(method, url, body=body)
1795         tahoe_mv.do_http = mock_do_http
1796
1797         # copy file to the grid
1798         d = self.do_cli("create-alias", "tahoe")
1799         d.addCallback(lambda res:
1800             self.do_cli("cp", fn1, "tahoe:"))
1801
1802         # do mv file1 file2
1803         d.addCallback(lambda res:
1804             self.do_cli("mv", "tahoe:file1", "tahoe:file2"))
1805         def _check( (rc, out, err) ):
1806             self.failIfIn("OK", out, "mv printed 'OK' even though the DELETE failed")
1807             self.failUnlessEqual(rc, 2)
1808         d.addCallback(_check)
1809
1810         def _restore_do_http(res):
1811             tahoe_mv.do_http = original_do_http
1812             return res
1813         d.addBoth(_restore_do_http)
1814         return d
1815
1816     def test_mv_without_alias(self):
1817         # doing 'tahoe mv' without explicitly specifying an alias or
1818         # creating the default 'tahoe' alias should fail with a useful
1819         # error message.
1820         self.basedir = "cli/Mv/mv_without_alias"
1821         self.set_up_grid()
1822         d = self.do_cli("mv", "afile", "anotherfile")
1823         def _check((rc, out, err)):
1824             self.failUnlessReallyEqual(rc, 1)
1825             self.failUnlessIn("error:", err)
1826             self.failUnlessReallyEqual(out, "")
1827         d.addCallback(_check)
1828         # check to see that the validation extends to the
1829         # target argument by making an alias that will work with the first
1830         # one.
1831         d.addCallback(lambda ign: self.do_cli("create-alias", "havasu"))
1832         def _create_a_test_file(ign):
1833             self.test_file_path = os.path.join(self.basedir, "afile")
1834             fileutil.write(self.test_file_path, "puppies" * 100)
1835         d.addCallback(_create_a_test_file)
1836         d.addCallback(lambda ign: self.do_cli("put", self.test_file_path,
1837                                               "havasu:afile"))
1838         d.addCallback(lambda ign: self.do_cli("mv", "havasu:afile",
1839                                               "anotherfile"))
1840         d.addCallback(_check)
1841         return d
1842
1843     def test_mv_with_nonexistent_alias(self):
1844         # doing 'tahoe mv' with an alias that doesn't exist should fail
1845         # with an informative error message.
1846         self.basedir = "cli/Mv/mv_with_nonexistent_alias"
1847         self.set_up_grid()
1848         d = self.do_cli("mv", "fake:afile", "fake:anotherfile")
1849         def _check((rc, out, err)):
1850             self.failUnlessReallyEqual(rc, 1)
1851             self.failUnlessIn("error:", err)
1852             self.failUnlessIn("fake", err)
1853             self.failUnlessReallyEqual(out, "")
1854         d.addCallback(_check)
1855         # check to see that the validation extends to the
1856         # target argument by making an alias that will work with the first
1857         # one.
1858         d.addCallback(lambda ign: self.do_cli("create-alias", "havasu"))
1859         def _create_a_test_file(ign):
1860             self.test_file_path = os.path.join(self.basedir, "afile")
1861             fileutil.write(self.test_file_path, "puppies" * 100)
1862         d.addCallback(_create_a_test_file)
1863         d.addCallback(lambda ign: self.do_cli("put", self.test_file_path,
1864                                               "havasu:afile"))
1865         d.addCallback(lambda ign: self.do_cli("mv", "havasu:afile",
1866                                               "fake:anotherfile"))
1867         d.addCallback(_check)
1868         return d
1869
1870
1871 class Cp(GridTestMixin, CLITestMixin, unittest.TestCase):
1872
1873     def test_not_enough_args(self):
1874         o = cli.CpOptions()
1875         self.failUnlessRaises(usage.UsageError,
1876                               o.parseOptions, ["onearg"])
1877
1878     def test_unicode_filename(self):
1879         self.basedir = "cli/Cp/unicode_filename"
1880
1881         fn1 = os.path.join(unicode(self.basedir), u"\u00C4rtonwall")
1882         try:
1883             fn1_arg = fn1.encode(get_io_encoding())
1884             artonwall_arg = u"\u00C4rtonwall".encode(get_io_encoding())
1885         except UnicodeEncodeError:
1886             raise unittest.SkipTest("A non-ASCII command argument could not be encoded on this platform.")
1887
1888         self.skip_if_cannot_represent_filename(fn1)
1889
1890         self.set_up_grid()
1891
1892         DATA1 = "unicode file content"
1893         fileutil.write(fn1, DATA1)
1894
1895         fn2 = os.path.join(self.basedir, "Metallica")
1896         DATA2 = "non-unicode file content"
1897         fileutil.write(fn2, DATA2)
1898
1899         d = self.do_cli("create-alias", "tahoe")
1900
1901         d.addCallback(lambda res: self.do_cli("cp", fn1_arg, "tahoe:"))
1902
1903         d.addCallback(lambda res: self.do_cli("get", "tahoe:" + artonwall_arg))
1904         d.addCallback(lambda (rc,out,err): self.failUnlessReallyEqual(out, DATA1))
1905
1906         d.addCallback(lambda res: self.do_cli("cp", fn2, "tahoe:"))
1907
1908         d.addCallback(lambda res: self.do_cli("get", "tahoe:Metallica"))
1909         d.addCallback(lambda (rc,out,err): self.failUnlessReallyEqual(out, DATA2))
1910
1911         d.addCallback(lambda res: self.do_cli("ls", "tahoe:"))
1912         def _check((rc, out, err)):
1913             try:
1914                 unicode_to_output(u"\u00C4rtonwall")
1915             except UnicodeEncodeError:
1916                 self.failUnlessReallyEqual(rc, 1)
1917                 self.failUnlessReallyEqual(out, "Metallica\n")
1918                 self.failUnlessIn(quote_output(u"\u00C4rtonwall"), err)
1919                 self.failUnlessIn("files whose names could not be converted", err)
1920             else:
1921                 self.failUnlessReallyEqual(rc, 0)
1922                 self.failUnlessReallyEqual(out.decode(get_io_encoding()), u"Metallica\n\u00C4rtonwall\n")
1923                 self.failUnlessReallyEqual(err, "")
1924         d.addCallback(_check)
1925
1926         return d
1927
1928     def test_dangling_symlink_vs_recursion(self):
1929         if not hasattr(os, 'symlink'):
1930             raise unittest.SkipTest("Symlinks are not supported by Python on this platform.")
1931
1932         # cp -r on a directory containing a dangling symlink shouldn't assert
1933         self.basedir = "cli/Cp/dangling_symlink_vs_recursion"
1934         self.set_up_grid()
1935         dn = os.path.join(self.basedir, "dir")
1936         os.mkdir(dn)
1937         fn = os.path.join(dn, "Fakebandica")
1938         ln = os.path.join(dn, "link")
1939         os.symlink(fn, ln)
1940
1941         d = self.do_cli("create-alias", "tahoe")
1942         d.addCallback(lambda res: self.do_cli("cp", "--recursive",
1943                                               dn, "tahoe:"))
1944         return d
1945
1946     def test_copy_using_filecap(self):
1947         self.basedir = "cli/Cp/test_copy_using_filecap"
1948         self.set_up_grid()
1949         outdir = os.path.join(self.basedir, "outdir")
1950         os.mkdir(outdir)
1951         fn1 = os.path.join(self.basedir, "Metallica")
1952         fn2 = os.path.join(outdir, "Not Metallica")
1953         fn3 = os.path.join(outdir, "test2")
1954         DATA1 = "puppies" * 10000
1955         fileutil.write(fn1, DATA1)
1956
1957         d = self.do_cli("create-alias", "tahoe")
1958         d.addCallback(lambda ign: self.do_cli("put", fn1))
1959         def _put_file((rc, out, err)):
1960             self.failUnlessReallyEqual(rc, 0)
1961             self.failUnlessIn("200 OK", err)
1962             # keep track of the filecap
1963             self.filecap = out.strip()
1964         d.addCallback(_put_file)
1965
1966         # Let's try copying this to the disk using the filecap
1967         #  cp FILECAP filename
1968         d.addCallback(lambda ign: self.do_cli("cp", self.filecap, fn2))
1969         def _copy_file((rc, out, err)):
1970             self.failUnlessReallyEqual(rc, 0)
1971             results = fileutil.read(fn2)
1972             self.failUnlessReallyEqual(results, DATA1)
1973         d.addCallback(_copy_file)
1974
1975         # Test with ./ (see #761)
1976         #  cp FILECAP localdir
1977         d.addCallback(lambda ign: self.do_cli("cp", self.filecap, outdir))
1978         def _resp((rc, out, err)):
1979             self.failUnlessReallyEqual(rc, 1)
1980             self.failUnlessIn("error: you must specify a destination filename",
1981                               err)
1982             self.failUnlessReallyEqual(out, "")
1983         d.addCallback(_resp)
1984
1985         # Create a directory, linked at tahoe:test
1986         d.addCallback(lambda ign: self.do_cli("mkdir", "tahoe:test"))
1987         def _get_dir((rc, out, err)):
1988             self.failUnlessReallyEqual(rc, 0)
1989             self.dircap = out.strip()
1990         d.addCallback(_get_dir)
1991
1992         # Upload a file to the directory
1993         d.addCallback(lambda ign:
1994                       self.do_cli("put", fn1, "tahoe:test/test_file"))
1995         d.addCallback(lambda (rc, out, err): self.failUnlessReallyEqual(rc, 0))
1996
1997         #  cp DIRCAP/filename localdir
1998         d.addCallback(lambda ign:
1999                       self.do_cli("cp",  self.dircap + "/test_file", outdir))
2000         def _get_resp((rc, out, err)):
2001             self.failUnlessReallyEqual(rc, 0)
2002             results = fileutil.read(os.path.join(outdir, "test_file"))
2003             self.failUnlessReallyEqual(results, DATA1)
2004         d.addCallback(_get_resp)
2005
2006         #  cp -r DIRCAP/filename filename2
2007         d.addCallback(lambda ign:
2008                       self.do_cli("cp",  self.dircap + "/test_file", fn3))
2009         def _get_resp2((rc, out, err)):
2010             self.failUnlessReallyEqual(rc, 0)
2011             results = fileutil.read(fn3)
2012             self.failUnlessReallyEqual(results, DATA1)
2013         d.addCallback(_get_resp2)
2014         #  cp --verbose filename3 dircap:test_file
2015         d.addCallback(lambda ign:
2016                       self.do_cli("cp", "--verbose", '--recursive', self.basedir, self.dircap))
2017         def _test_for_wrong_indices((rc, out, err)):
2018             self.failUnless('examining 1 of 1\n' in err)
2019         d.addCallback(_test_for_wrong_indices)
2020         return d
2021
2022     def test_cp_with_nonexistent_alias(self):
2023         # when invoked with an alias or aliases that don't exist, 'tahoe cp'
2024         # should output a sensible error message rather than a stack trace.
2025         self.basedir = "cli/Cp/cp_with_nonexistent_alias"
2026         self.set_up_grid()
2027         d = self.do_cli("cp", "fake:file1", "fake:file2")
2028         def _check((rc, out, err)):
2029             self.failUnlessReallyEqual(rc, 1)
2030             self.failUnlessIn("error:", err)
2031         d.addCallback(_check)
2032         # 'tahoe cp' actually processes the target argument first, so we need
2033         # to check to make sure that validation extends to the source
2034         # argument.
2035         d.addCallback(lambda ign: self.do_cli("create-alias", "tahoe"))
2036         d.addCallback(lambda ign: self.do_cli("cp", "fake:file1",
2037                                               "tahoe:file2"))
2038         d.addCallback(_check)
2039         return d
2040
2041     def test_unicode_dirnames(self):
2042         self.basedir = "cli/Cp/unicode_dirnames"
2043
2044         fn1 = os.path.join(unicode(self.basedir), u"\u00C4rtonwall")
2045         try:
2046             fn1_arg = fn1.encode(get_io_encoding())
2047             del fn1_arg # hush pyflakes
2048             artonwall_arg = u"\u00C4rtonwall".encode(get_io_encoding())
2049         except UnicodeEncodeError:
2050             raise unittest.SkipTest("A non-ASCII command argument could not be encoded on this platform.")
2051
2052         self.skip_if_cannot_represent_filename(fn1)
2053
2054         self.set_up_grid()
2055
2056         d = self.do_cli("create-alias", "tahoe")
2057         d.addCallback(lambda res: self.do_cli("mkdir", "tahoe:test/" + artonwall_arg))
2058         d.addCallback(lambda res: self.do_cli("cp", "-r", "tahoe:test", "tahoe:test2"))
2059         d.addCallback(lambda res: self.do_cli("ls", "tahoe:test2"))
2060         def _check((rc, out, err)):
2061             try:
2062                 unicode_to_output(u"\u00C4rtonwall")
2063             except UnicodeEncodeError:
2064                 self.failUnlessReallyEqual(rc, 1)
2065                 self.failUnlessReallyEqual(out, "")
2066                 self.failUnlessIn(quote_output(u"\u00C4rtonwall"), err)
2067                 self.failUnlessIn("files whose names could not be converted", err)
2068             else:
2069                 self.failUnlessReallyEqual(rc, 0)
2070                 self.failUnlessReallyEqual(out.decode(get_io_encoding()), u"\u00C4rtonwall\n")
2071                 self.failUnlessReallyEqual(err, "")
2072         d.addCallback(_check)
2073
2074         return d
2075
2076     def test_cp_replaces_mutable_file_contents(self):
2077         self.basedir = "cli/Cp/cp_replaces_mutable_file_contents"
2078         self.set_up_grid()
2079
2080         # Write a test file, which we'll copy to the grid.
2081         test_txt_path = os.path.join(self.basedir, "test.txt")
2082         test_txt_contents = "foo bar baz"
2083         f = open(test_txt_path, "w")
2084         f.write(test_txt_contents)
2085         f.close()
2086
2087         d = self.do_cli("create-alias", "tahoe")
2088         d.addCallback(lambda ignored:
2089             self.do_cli("mkdir", "tahoe:test"))
2090         # We have to use 'tahoe put' here because 'tahoe cp' doesn't
2091         # know how to make mutable files at the destination.
2092         d.addCallback(lambda ignored:
2093             self.do_cli("put", "--mutable", test_txt_path, "tahoe:test/test.txt"))
2094         d.addCallback(lambda ignored:
2095             self.do_cli("get", "tahoe:test/test.txt"))
2096         def _check((rc, out, err)):
2097             self.failUnlessEqual(rc, 0)
2098             self.failUnlessEqual(out, test_txt_contents)
2099         d.addCallback(_check)
2100
2101         # We'll do ls --json to get the read uri and write uri for the
2102         # file we've just uploaded.
2103         d.addCallback(lambda ignored:
2104             self.do_cli("ls", "--json", "tahoe:test/test.txt"))
2105         def _get_test_txt_uris((rc, out, err)):
2106             self.failUnlessEqual(rc, 0)
2107             filetype, data = simplejson.loads(out)
2108
2109             self.failUnlessEqual(filetype, "filenode")
2110             self.failUnless(data['mutable'])
2111
2112             self.failUnlessIn("rw_uri", data)
2113             self.rw_uri = to_str(data["rw_uri"])
2114             self.failUnlessIn("ro_uri", data)
2115             self.ro_uri = to_str(data["ro_uri"])
2116         d.addCallback(_get_test_txt_uris)
2117
2118         # Now make a new file to copy in place of test.txt.
2119         new_txt_path = os.path.join(self.basedir, "new.txt")
2120         new_txt_contents = "baz bar foo" * 100000
2121         f = open(new_txt_path, "w")
2122         f.write(new_txt_contents)
2123         f.close()
2124
2125         # Copy the new file on top of the old file.
2126         d.addCallback(lambda ignored:
2127             self.do_cli("cp", new_txt_path, "tahoe:test/test.txt"))
2128
2129         # If we get test.txt now, we should see the new data.
2130         d.addCallback(lambda ignored:
2131             self.do_cli("get", "tahoe:test/test.txt"))
2132         d.addCallback(lambda (rc, out, err):
2133             self.failUnlessEqual(out, new_txt_contents))
2134         # If we get the json of the new file, we should see that the old
2135         # uri is there
2136         d.addCallback(lambda ignored:
2137             self.do_cli("ls", "--json", "tahoe:test/test.txt"))
2138         def _check_json((rc, out, err)):
2139             self.failUnlessEqual(rc, 0)
2140             filetype, data = simplejson.loads(out)
2141
2142             self.failUnlessEqual(filetype, "filenode")
2143             self.failUnless(data['mutable'])
2144
2145             self.failUnlessIn("ro_uri", data)
2146             self.failUnlessEqual(to_str(data["ro_uri"]), self.ro_uri)
2147             self.failUnlessIn("rw_uri", data)
2148             self.failUnlessEqual(to_str(data["rw_uri"]), self.rw_uri)
2149         d.addCallback(_check_json)
2150
2151         # and, finally, doing a GET directly on one of the old uris
2152         # should give us the new contents.
2153         d.addCallback(lambda ignored:
2154             self.do_cli("get", self.rw_uri))
2155         d.addCallback(lambda (rc, out, err):
2156             self.failUnlessEqual(out, new_txt_contents))
2157         # Now copy the old test.txt without an explicit destination
2158         # file. tahoe cp will match it to the existing file and
2159         # overwrite it appropriately.
2160         d.addCallback(lambda ignored:
2161             self.do_cli("cp", test_txt_path, "tahoe:test"))
2162         d.addCallback(lambda ignored:
2163             self.do_cli("get", "tahoe:test/test.txt"))
2164         d.addCallback(lambda (rc, out, err):
2165             self.failUnlessEqual(out, test_txt_contents))
2166         d.addCallback(lambda ignored:
2167             self.do_cli("ls", "--json", "tahoe:test/test.txt"))
2168         d.addCallback(_check_json)
2169         d.addCallback(lambda ignored:
2170             self.do_cli("get", self.rw_uri))
2171         d.addCallback(lambda (rc, out, err):
2172             self.failUnlessEqual(out, test_txt_contents))
2173
2174         # Now we'll make a more complicated directory structure.
2175         # test2/
2176         # test2/mutable1
2177         # test2/mutable2
2178         # test2/imm1
2179         # test2/imm2
2180         imm_test_txt_path = os.path.join(self.basedir, "imm_test.txt")
2181         imm_test_txt_contents = test_txt_contents * 10000
2182         fileutil.write(imm_test_txt_path, imm_test_txt_contents)
2183         d.addCallback(lambda ignored:
2184             self.do_cli("mkdir", "tahoe:test2"))
2185         d.addCallback(lambda ignored:
2186             self.do_cli("put", "--mutable", new_txt_path,
2187                         "tahoe:test2/mutable1"))
2188         d.addCallback(lambda ignored:
2189             self.do_cli("put", "--mutable", new_txt_path,
2190                         "tahoe:test2/mutable2"))
2191         d.addCallback(lambda ignored:
2192             self.do_cli('put', new_txt_path, "tahoe:test2/imm1"))
2193         d.addCallback(lambda ignored:
2194             self.do_cli("put", imm_test_txt_path, "tahoe:test2/imm2"))
2195         d.addCallback(lambda ignored:
2196             self.do_cli("ls", "--json", "tahoe:test2"))
2197         def _process_directory_json((rc, out, err)):
2198             self.failUnlessEqual(rc, 0)
2199
2200             filetype, data = simplejson.loads(out)
2201             self.failUnlessEqual(filetype, "dirnode")
2202             self.failUnless(data['mutable'])
2203             self.failUnlessIn("children", data)
2204             children = data['children']
2205
2206             # Store the URIs for later use.
2207             self.childuris = {}
2208             for k in ["mutable1", "mutable2", "imm1", "imm2"]:
2209                 self.failUnlessIn(k, children)
2210                 childtype, childdata = children[k]
2211                 self.failUnlessEqual(childtype, "filenode")
2212                 if "mutable" in k:
2213                     self.failUnless(childdata['mutable'])
2214                     self.failUnlessIn("rw_uri", childdata)
2215                     uri_key = "rw_uri"
2216                 else:
2217                     self.failIf(childdata['mutable'])
2218                     self.failUnlessIn("ro_uri", childdata)
2219                     uri_key = "ro_uri"
2220                 self.childuris[k] = to_str(childdata[uri_key])
2221         d.addCallback(_process_directory_json)
2222         # Now build a local directory to copy into place, like the following:
2223         # source1/
2224         # source1/mutable1
2225         # source1/mutable2
2226         # source1/imm1
2227         # source1/imm3
2228         def _build_local_directory(ignored):
2229             source1_path = os.path.join(self.basedir, "source1")
2230             fileutil.make_dirs(source1_path)
2231             for fn in ("mutable1", "mutable2", "imm1", "imm3"):
2232                 fileutil.write(os.path.join(source1_path, fn), fn * 1000)
2233             self.source1_path = source1_path
2234         d.addCallback(_build_local_directory)
2235         d.addCallback(lambda ignored:
2236             self.do_cli("cp", "-r", self.source1_path, "tahoe:test2"))
2237
2238         # We expect that mutable1 and mutable2 are overwritten in-place,
2239         # so they'll retain their URIs but have different content.
2240         def _process_file_json((rc, out, err), fn):
2241             self.failUnlessEqual(rc, 0)
2242             filetype, data = simplejson.loads(out)
2243             self.failUnlessEqual(filetype, "filenode")
2244
2245             if "mutable" in fn:
2246                 self.failUnless(data['mutable'])
2247                 self.failUnlessIn("rw_uri", data)
2248                 self.failUnlessEqual(to_str(data["rw_uri"]), self.childuris[fn])
2249             else:
2250                 self.failIf(data['mutable'])
2251                 self.failUnlessIn("ro_uri", data)
2252                 self.failIfEqual(to_str(data["ro_uri"]), self.childuris[fn])
2253
2254         for fn in ("mutable1", "mutable2"):
2255             d.addCallback(lambda ignored, fn=fn:
2256                 self.do_cli("get", "tahoe:test2/%s" % fn))
2257             d.addCallback(lambda (rc, out, err), fn=fn:
2258                 self.failUnlessEqual(out, fn * 1000))
2259             d.addCallback(lambda ignored, fn=fn:
2260                 self.do_cli("ls", "--json", "tahoe:test2/%s" % fn))
2261             d.addCallback(_process_file_json, fn=fn)
2262
2263         # imm1 should have been replaced, so both its uri and content
2264         # should be different.
2265         d.addCallback(lambda ignored:
2266             self.do_cli("get", "tahoe:test2/imm1"))
2267         d.addCallback(lambda (rc, out, err):
2268             self.failUnlessEqual(out, "imm1" * 1000))
2269         d.addCallback(lambda ignored:
2270             self.do_cli("ls", "--json", "tahoe:test2/imm1"))
2271         d.addCallback(_process_file_json, fn="imm1")
2272
2273         # imm3 should have been created.
2274         d.addCallback(lambda ignored:
2275             self.do_cli("get", "tahoe:test2/imm3"))
2276         d.addCallback(lambda (rc, out, err):
2277             self.failUnlessEqual(out, "imm3" * 1000))
2278
2279         # imm2 should be exactly as we left it, since our newly-copied
2280         # directory didn't contain an imm2 entry.
2281         d.addCallback(lambda ignored:
2282             self.do_cli("get", "tahoe:test2/imm2"))
2283         d.addCallback(lambda (rc, out, err):
2284             self.failUnlessEqual(out, imm_test_txt_contents))
2285         d.addCallback(lambda ignored:
2286             self.do_cli("ls", "--json", "tahoe:test2/imm2"))
2287         def _process_imm2_json((rc, out, err)):
2288             self.failUnlessEqual(rc, 0)
2289             filetype, data = simplejson.loads(out)
2290             self.failUnlessEqual(filetype, "filenode")
2291             self.failIf(data['mutable'])
2292             self.failUnlessIn("ro_uri", data)
2293             self.failUnlessEqual(to_str(data["ro_uri"]), self.childuris["imm2"])
2294         d.addCallback(_process_imm2_json)
2295         return d
2296
2297     def test_cp_overwrite_readonly_mutable_file(self):
2298         # tahoe cp should print an error when asked to overwrite a
2299         # mutable file that it can't overwrite.
2300         self.basedir = "cli/Cp/overwrite_readonly_mutable_file"
2301         self.set_up_grid()
2302
2303         # This is our initial file. We'll link its readcap into the
2304         # tahoe: alias.
2305         test_file_path = os.path.join(self.basedir, "test_file.txt")
2306         test_file_contents = "This is a test file."
2307         fileutil.write(test_file_path, test_file_contents)
2308
2309         # This is our replacement file. We'll try and fail to upload it
2310         # over the readcap that we linked into the tahoe: alias.
2311         replacement_file_path = os.path.join(self.basedir, "replacement.txt")
2312         replacement_file_contents = "These are new contents."
2313         fileutil.write(replacement_file_path, replacement_file_contents)
2314
2315         d = self.do_cli("create-alias", "tahoe:")
2316         d.addCallback(lambda ignored:
2317             self.do_cli("put", "--mutable", test_file_path))
2318         def _get_test_uri((rc, out, err)):
2319             self.failUnlessEqual(rc, 0)
2320             # this should be a write uri
2321             self._test_write_uri = out
2322         d.addCallback(_get_test_uri)
2323         d.addCallback(lambda ignored:
2324             self.do_cli("ls", "--json", self._test_write_uri))
2325         def _process_test_json((rc, out, err)):
2326             self.failUnlessEqual(rc, 0)
2327             filetype, data = simplejson.loads(out)
2328
2329             self.failUnlessEqual(filetype, "filenode")
2330             self.failUnless(data['mutable'])
2331             self.failUnlessIn("ro_uri", data)
2332             self._test_read_uri = to_str(data["ro_uri"])
2333         d.addCallback(_process_test_json)
2334         # Now we'll link the readonly URI into the tahoe: alias.
2335         d.addCallback(lambda ignored:
2336             self.do_cli("ln", self._test_read_uri, "tahoe:test_file.txt"))
2337         d.addCallback(lambda (rc, out, err):
2338             self.failUnlessEqual(rc, 0))
2339         # Let's grab the json of that to make sure that we did it right.
2340         d.addCallback(lambda ignored:
2341             self.do_cli("ls", "--json", "tahoe:"))
2342         def _process_tahoe_json((rc, out, err)):
2343             self.failUnlessEqual(rc, 0)
2344
2345             filetype, data = simplejson.loads(out)
2346             self.failUnlessEqual(filetype, "dirnode")
2347             self.failUnlessIn("children", data)
2348             kiddata = data['children']
2349
2350             self.failUnlessIn("test_file.txt", kiddata)
2351             testtype, testdata = kiddata['test_file.txt']
2352             self.failUnlessEqual(testtype, "filenode")
2353             self.failUnless(testdata['mutable'])
2354             self.failUnlessIn("ro_uri", testdata)
2355             self.failUnlessEqual(to_str(testdata["ro_uri"]), self._test_read_uri)
2356             self.failIfIn("rw_uri", testdata)
2357         d.addCallback(_process_tahoe_json)
2358         # Okay, now we're going to try uploading another mutable file in
2359         # place of that one. We should get an error.
2360         d.addCallback(lambda ignored:
2361             self.do_cli("cp", replacement_file_path, "tahoe:test_file.txt"))
2362         def _check_error_message((rc, out, err)):
2363             self.failUnlessEqual(rc, 1)
2364             self.failUnlessIn("replace or update requested with read-only cap", err)
2365         d.addCallback(_check_error_message)
2366         # Make extra sure that that didn't work.
2367         d.addCallback(lambda ignored:
2368             self.do_cli("get", "tahoe:test_file.txt"))
2369         d.addCallback(lambda (rc, out, err):
2370             self.failUnlessEqual(out, test_file_contents))
2371         d.addCallback(lambda ignored:
2372             self.do_cli("get", self._test_read_uri))
2373         d.addCallback(lambda (rc, out, err):
2374             self.failUnlessEqual(out, test_file_contents))
2375         # Now we'll do it without an explicit destination.
2376         d.addCallback(lambda ignored:
2377             self.do_cli("cp", test_file_path, "tahoe:"))
2378         d.addCallback(_check_error_message)
2379         d.addCallback(lambda ignored:
2380             self.do_cli("get", "tahoe:test_file.txt"))
2381         d.addCallback(lambda (rc, out, err):
2382             self.failUnlessEqual(out, test_file_contents))
2383         d.addCallback(lambda ignored:
2384             self.do_cli("get", self._test_read_uri))
2385         d.addCallback(lambda (rc, out, err):
2386             self.failUnlessEqual(out, test_file_contents))
2387         # Now we'll link a readonly file into a subdirectory.
2388         d.addCallback(lambda ignored:
2389             self.do_cli("mkdir", "tahoe:testdir"))
2390         d.addCallback(lambda (rc, out, err):
2391             self.failUnlessEqual(rc, 0))
2392         d.addCallback(lambda ignored:
2393             self.do_cli("ln", self._test_read_uri, "tahoe:test/file2.txt"))
2394         d.addCallback(lambda (rc, out, err):
2395             self.failUnlessEqual(rc, 0))
2396
2397         test_dir_path = os.path.join(self.basedir, "test")
2398         fileutil.make_dirs(test_dir_path)
2399         for f in ("file1.txt", "file2.txt"):
2400             fileutil.write(os.path.join(test_dir_path, f), f * 10000)
2401
2402         d.addCallback(lambda ignored:
2403             self.do_cli("cp", "-r", test_dir_path, "tahoe:test"))
2404         d.addCallback(_check_error_message)
2405         d.addCallback(lambda ignored:
2406             self.do_cli("ls", "--json", "tahoe:test"))
2407         def _got_testdir_json((rc, out, err)):
2408             self.failUnlessEqual(rc, 0)
2409
2410             filetype, data = simplejson.loads(out)
2411             self.failUnlessEqual(filetype, "dirnode")
2412
2413             self.failUnlessIn("children", data)
2414             childdata = data['children']
2415
2416             self.failUnlessIn("file2.txt", childdata)
2417             file2type, file2data = childdata['file2.txt']
2418             self.failUnlessEqual(file2type, "filenode")
2419             self.failUnless(file2data['mutable'])
2420             self.failUnlessIn("ro_uri", file2data)
2421             self.failUnlessEqual(to_str(file2data["ro_uri"]), self._test_read_uri)
2422             self.failIfIn("rw_uri", file2data)
2423         d.addCallback(_got_testdir_json)
2424         return d
2425
2426     def test_cp_verbose(self):
2427         self.basedir = "cli/Cp/cp_verbose"
2428         self.set_up_grid()
2429
2430         # Write two test files, which we'll copy to the grid.
2431         test1_path = os.path.join(self.basedir, "test1")
2432         test2_path = os.path.join(self.basedir, "test2")
2433         fileutil.write(test1_path, "test1")
2434         fileutil.write(test2_path, "test2")
2435
2436         d = self.do_cli("create-alias", "tahoe")
2437         d.addCallback(lambda ign:
2438             self.do_cli("cp", "--verbose", test1_path, test2_path, "tahoe:"))
2439         def _check(res):
2440             (rc, out, err) = res
2441             self.failUnlessEqual(rc, 0, str(res))
2442             self.failUnlessIn("Success: files copied", out, str(res))
2443             self.failUnlessEqual(err, """\
2444 attaching sources to targets, 2 files / 0 dirs in root
2445 targets assigned, 1 dirs, 2 files
2446 starting copy, 2 files, 1 directories
2447 1/2 files, 0/1 directories
2448 2/2 files, 0/1 directories
2449 1/1 directories
2450 """, str(res))
2451         d.addCallback(_check)
2452         return d
2453
2454
2455 class Backup(GridTestMixin, CLITestMixin, StallMixin, unittest.TestCase):
2456
2457     def writeto(self, path, data):
2458         full_path = os.path.join(self.basedir, "home", path)
2459         fileutil.make_dirs(os.path.dirname(full_path))
2460         fileutil.write(full_path, data)
2461
2462     def count_output(self, out):
2463         mo = re.search(r"(\d)+ files uploaded \((\d+) reused\), "
2464                         "(\d)+ files skipped, "
2465                         "(\d+) directories created \((\d+) reused\), "
2466                         "(\d+) directories skipped", out)
2467         return [int(s) for s in mo.groups()]
2468
2469     def count_output2(self, out):
2470         mo = re.search(r"(\d)+ files checked, (\d+) directories checked", out)
2471         return [int(s) for s in mo.groups()]
2472
2473     def test_backup(self):
2474         self.basedir = "cli/Backup/backup"
2475         self.set_up_grid()
2476
2477         # is the backupdb available? If so, we test that a second backup does
2478         # not create new directories.
2479         hush = StringIO()
2480         bdb = backupdb.get_backupdb(os.path.join(self.basedir, "dbtest"),
2481                                     hush)
2482         self.failUnless(bdb)
2483
2484         # create a small local directory with a couple of files
2485         source = os.path.join(self.basedir, "home")
2486         fileutil.make_dirs(os.path.join(source, "empty"))
2487         self.writeto("parent/subdir/foo.txt", "foo")
2488         self.writeto("parent/subdir/bar.txt", "bar\n" * 1000)
2489         self.writeto("parent/blah.txt", "blah")
2490
2491         def do_backup(verbose=False):
2492             cmd = ["backup"]
2493             if verbose:
2494                 cmd.append("--verbose")
2495             cmd.append(source)
2496             cmd.append("tahoe:backups")
2497             return self.do_cli(*cmd)
2498
2499         d = self.do_cli("create-alias", "tahoe")
2500
2501         d.addCallback(lambda res: do_backup())
2502         def _check0((rc, out, err)):
2503             self.failUnlessReallyEqual(err, "")
2504             self.failUnlessReallyEqual(rc, 0)
2505             fu, fr, fs, dc, dr, ds = self.count_output(out)
2506             # foo.txt, bar.txt, blah.txt
2507             self.failUnlessReallyEqual(fu, 3)
2508             self.failUnlessReallyEqual(fr, 0)
2509             self.failUnlessReallyEqual(fs, 0)
2510             # empty, home, home/parent, home/parent/subdir
2511             self.failUnlessReallyEqual(dc, 4)
2512             self.failUnlessReallyEqual(dr, 0)
2513             self.failUnlessReallyEqual(ds, 0)
2514         d.addCallback(_check0)
2515
2516         d.addCallback(lambda res: self.do_cli("ls", "--uri", "tahoe:backups"))
2517         def _check1((rc, out, err)):
2518             self.failUnlessReallyEqual(err, "")
2519             self.failUnlessReallyEqual(rc, 0)
2520             lines = out.split("\n")
2521             children = dict([line.split() for line in lines if line])
2522             latest_uri = children["Latest"]
2523             self.failUnless(latest_uri.startswith("URI:DIR2-CHK:"), latest_uri)
2524             childnames = children.keys()
2525             self.failUnlessReallyEqual(sorted(childnames), ["Archives", "Latest"])
2526         d.addCallback(_check1)
2527         d.addCallback(lambda res: self.do_cli("ls", "tahoe:backups/Latest"))
2528         def _check2((rc, out, err)):
2529             self.failUnlessReallyEqual(err, "")
2530             self.failUnlessReallyEqual(rc, 0)
2531             self.failUnlessReallyEqual(sorted(out.split()), ["empty", "parent"])
2532         d.addCallback(_check2)
2533         d.addCallback(lambda res: self.do_cli("ls", "tahoe:backups/Latest/empty"))
2534         def _check2a((rc, out, err)):
2535             self.failUnlessReallyEqual(err, "")
2536             self.failUnlessReallyEqual(rc, 0)
2537             self.failUnlessReallyEqual(out.strip(), "")
2538         d.addCallback(_check2a)
2539         d.addCallback(lambda res: self.do_cli("get", "tahoe:backups/Latest/parent/subdir/foo.txt"))
2540         def _check3((rc, out, err)):
2541             self.failUnlessReallyEqual(err, "")
2542             self.failUnlessReallyEqual(rc, 0)
2543             self.failUnlessReallyEqual(out, "foo")
2544         d.addCallback(_check3)
2545         d.addCallback(lambda res: self.do_cli("ls", "tahoe:backups/Archives"))
2546         def _check4((rc, out, err)):
2547             self.failUnlessReallyEqual(err, "")
2548             self.failUnlessReallyEqual(rc, 0)
2549             self.old_archives = out.split()
2550             self.failUnlessReallyEqual(len(self.old_archives), 1)
2551         d.addCallback(_check4)
2552
2553
2554         d.addCallback(self.stall, 1.1)
2555         d.addCallback(lambda res: do_backup())
2556         def _check4a((rc, out, err)):
2557             # second backup should reuse everything, if the backupdb is
2558             # available
2559             self.failUnlessReallyEqual(err, "")
2560             self.failUnlessReallyEqual(rc, 0)
2561             fu, fr, fs, dc, dr, ds = self.count_output(out)
2562             # foo.txt, bar.txt, blah.txt
2563             self.failUnlessReallyEqual(fu, 0)
2564             self.failUnlessReallyEqual(fr, 3)
2565             self.failUnlessReallyEqual(fs, 0)
2566             # empty, home, home/parent, home/parent/subdir
2567             self.failUnlessReallyEqual(dc, 0)
2568             self.failUnlessReallyEqual(dr, 4)
2569             self.failUnlessReallyEqual(ds, 0)
2570         d.addCallback(_check4a)
2571
2572         # sneak into the backupdb, crank back the "last checked"
2573         # timestamp to force a check on all files
2574         def _reset_last_checked(res):
2575             dbfile = os.path.join(self.get_clientdir(),
2576                                   "private", "backupdb.sqlite")
2577             self.failUnless(os.path.exists(dbfile), dbfile)
2578             bdb = backupdb.get_backupdb(dbfile)
2579             bdb.cursor.execute("UPDATE last_upload SET last_checked=0")
2580             bdb.cursor.execute("UPDATE directories SET last_checked=0")
2581             bdb.connection.commit()
2582
2583         d.addCallback(_reset_last_checked)
2584
2585         d.addCallback(self.stall, 1.1)
2586         d.addCallback(lambda res: do_backup(verbose=True))
2587         def _check4b((rc, out, err)):
2588             # we should check all files, and re-use all of them. None of
2589             # the directories should have been changed, so we should
2590             # re-use all of them too.
2591             self.failUnlessReallyEqual(err, "")
2592             self.failUnlessReallyEqual(rc, 0)
2593             fu, fr, fs, dc, dr, ds = self.count_output(out)
2594             fchecked, dchecked = self.count_output2(out)
2595             self.failUnlessReallyEqual(fchecked, 3)
2596             self.failUnlessReallyEqual(fu, 0)
2597             self.failUnlessReallyEqual(fr, 3)
2598             self.failUnlessReallyEqual(fs, 0)
2599             self.failUnlessReallyEqual(dchecked, 4)
2600             self.failUnlessReallyEqual(dc, 0)
2601             self.failUnlessReallyEqual(dr, 4)
2602             self.failUnlessReallyEqual(ds, 0)
2603         d.addCallback(_check4b)
2604
2605         d.addCallback(lambda res: self.do_cli("ls", "tahoe:backups/Archives"))
2606         def _check5((rc, out, err)):
2607             self.failUnlessReallyEqual(err, "")
2608             self.failUnlessReallyEqual(rc, 0)
2609             self.new_archives = out.split()
2610             self.failUnlessReallyEqual(len(self.new_archives), 3, out)
2611             # the original backup should still be the oldest (i.e. sorts
2612             # alphabetically towards the beginning)
2613             self.failUnlessReallyEqual(sorted(self.new_archives)[0],
2614                                  self.old_archives[0])
2615         d.addCallback(_check5)
2616
2617         d.addCallback(self.stall, 1.1)
2618         def _modify(res):
2619             self.writeto("parent/subdir/foo.txt", "FOOF!")
2620             # and turn a file into a directory
2621             os.unlink(os.path.join(source, "parent/blah.txt"))
2622             os.mkdir(os.path.join(source, "parent/blah.txt"))
2623             self.writeto("parent/blah.txt/surprise file", "surprise")
2624             self.writeto("parent/blah.txt/surprisedir/subfile", "surprise")
2625             # turn a directory into a file
2626             os.rmdir(os.path.join(source, "empty"))
2627             self.writeto("empty", "imagine nothing being here")
2628             return do_backup()
2629         d.addCallback(_modify)
2630         def _check5a((rc, out, err)):
2631             # second backup should reuse bar.txt (if backupdb is available),
2632             # and upload the rest. None of the directories can be reused.
2633             self.failUnlessReallyEqual(err, "")
2634             self.failUnlessReallyEqual(rc, 0)
2635             fu, fr, fs, dc, dr, ds = self.count_output(out)
2636             # new foo.txt, surprise file, subfile, empty
2637             self.failUnlessReallyEqual(fu, 4)
2638             # old bar.txt
2639             self.failUnlessReallyEqual(fr, 1)
2640             self.failUnlessReallyEqual(fs, 0)
2641             # home, parent, subdir, blah.txt, surprisedir
2642             self.failUnlessReallyEqual(dc, 5)
2643             self.failUnlessReallyEqual(dr, 0)
2644             self.failUnlessReallyEqual(ds, 0)
2645         d.addCallback(_check5a)
2646         d.addCallback(lambda res: self.do_cli("ls", "tahoe:backups/Archives"))
2647         def _check6((rc, out, err)):
2648             self.failUnlessReallyEqual(err, "")
2649             self.failUnlessReallyEqual(rc, 0)
2650             self.new_archives = out.split()
2651             self.failUnlessReallyEqual(len(self.new_archives), 4)
2652             self.failUnlessReallyEqual(sorted(self.new_archives)[0],
2653                                  self.old_archives[0])
2654         d.addCallback(_check6)
2655         d.addCallback(lambda res: self.do_cli("get", "tahoe:backups/Latest/parent/subdir/foo.txt"))
2656         def _check7((rc, out, err)):
2657             self.failUnlessReallyEqual(err, "")
2658             self.failUnlessReallyEqual(rc, 0)
2659             self.failUnlessReallyEqual(out, "FOOF!")
2660             # the old snapshot should not be modified
2661             return self.do_cli("get", "tahoe:backups/Archives/%s/parent/subdir/foo.txt" % self.old_archives[0])
2662         d.addCallback(_check7)
2663         def _check8((rc, out, err)):
2664             self.failUnlessReallyEqual(err, "")
2665             self.failUnlessReallyEqual(rc, 0)
2666             self.failUnlessReallyEqual(out, "foo")
2667         d.addCallback(_check8)
2668
2669         return d
2670
2671     # on our old dapper buildslave, this test takes a long time (usually
2672     # 130s), so we have to bump up the default 120s timeout. The create-alias
2673     # and initial backup alone take 60s, probably because of the handful of
2674     # dirnodes being created (RSA key generation). The backup between check4
2675     # and check4a takes 6s, as does the backup before check4b.
2676     test_backup.timeout = 3000
2677
2678     def _check_filtering(self, filtered, all, included, excluded):
2679         filtered = set(filtered)
2680         all = set(all)
2681         included = set(included)
2682         excluded = set(excluded)
2683         self.failUnlessReallyEqual(filtered, included)
2684         self.failUnlessReallyEqual(all.difference(filtered), excluded)
2685
2686     def test_exclude_options(self):
2687         root_listdir = (u'lib.a', u'_darcs', u'subdir', u'nice_doc.lyx')
2688         subdir_listdir = (u'another_doc.lyx', u'run_snake_run.py', u'CVS', u'.svn', u'_darcs')
2689         basedir = "cli/Backup/exclude_options"
2690         fileutil.make_dirs(basedir)
2691         nodeurl_path = os.path.join(basedir, 'node.url')
2692         fileutil.write(nodeurl_path, 'http://example.net:2357/')
2693         def parse(args): return parse_options(basedir, "backup", args)
2694
2695         # test simple exclude
2696         backup_options = parse(['--exclude', '*lyx', 'from', 'to'])
2697         filtered = list(backup_options.filter_listdir(root_listdir))
2698         self._check_filtering(filtered, root_listdir, (u'lib.a', u'_darcs', u'subdir'),
2699                               (u'nice_doc.lyx',))
2700         # multiple exclude
2701         backup_options = parse(['--exclude', '*lyx', '--exclude', 'lib.?', 'from', 'to'])
2702         filtered = list(backup_options.filter_listdir(root_listdir))
2703         self._check_filtering(filtered, root_listdir, (u'_darcs', u'subdir'),
2704                               (u'nice_doc.lyx', u'lib.a'))
2705         # vcs metadata exclusion
2706         backup_options = parse(['--exclude-vcs', 'from', 'to'])
2707         filtered = list(backup_options.filter_listdir(subdir_listdir))
2708         self._check_filtering(filtered, subdir_listdir, (u'another_doc.lyx', u'run_snake_run.py',),
2709                               (u'CVS', u'.svn', u'_darcs'))
2710         # read exclude patterns from file
2711         exclusion_string = "_darcs\n*py\n.svn"
2712         excl_filepath = os.path.join(basedir, 'exclusion')
2713         fileutil.write(excl_filepath, exclusion_string)
2714         backup_options = parse(['--exclude-from', excl_filepath, 'from', 'to'])
2715         filtered = list(backup_options.filter_listdir(subdir_listdir))
2716         self._check_filtering(filtered, subdir_listdir, (u'another_doc.lyx', u'CVS'),
2717                               (u'.svn', u'_darcs', u'run_snake_run.py'))
2718         # test BackupConfigurationError
2719         self.failUnlessRaises(cli.BackupConfigurationError,
2720                               parse,
2721                               ['--exclude-from', excl_filepath + '.no', 'from', 'to'])
2722
2723         # test that an iterator works too
2724         backup_options = parse(['--exclude', '*lyx', 'from', 'to'])
2725         filtered = list(backup_options.filter_listdir(iter(root_listdir)))
2726         self._check_filtering(filtered, root_listdir, (u'lib.a', u'_darcs', u'subdir'),
2727                               (u'nice_doc.lyx',))
2728
2729     def test_exclude_options_unicode(self):
2730         nice_doc = u"nice_d\u00F8c.lyx"
2731         try:
2732             doc_pattern_arg = u"*d\u00F8c*".encode(get_io_encoding())
2733         except UnicodeEncodeError:
2734             raise unittest.SkipTest("A non-ASCII command argument could not be encoded on this platform.")
2735
2736         root_listdir = (u'lib.a', u'_darcs', u'subdir', nice_doc)
2737         basedir = "cli/Backup/exclude_options_unicode"
2738         fileutil.make_dirs(basedir)
2739         nodeurl_path = os.path.join(basedir, 'node.url')
2740         fileutil.write(nodeurl_path, 'http://example.net:2357/')
2741         def parse(args): return parse_options(basedir, "backup", args)
2742
2743         # test simple exclude
2744         backup_options = parse(['--exclude', doc_pattern_arg, 'from', 'to'])
2745         filtered = list(backup_options.filter_listdir(root_listdir))
2746         self._check_filtering(filtered, root_listdir, (u'lib.a', u'_darcs', u'subdir'),
2747                               (nice_doc,))
2748         # multiple exclude
2749         backup_options = parse(['--exclude', doc_pattern_arg, '--exclude', 'lib.?', 'from', 'to'])
2750         filtered = list(backup_options.filter_listdir(root_listdir))
2751         self._check_filtering(filtered, root_listdir, (u'_darcs', u'subdir'),
2752                              (nice_doc, u'lib.a'))
2753         # read exclude patterns from file
2754         exclusion_string = doc_pattern_arg + "\nlib.?"
2755         excl_filepath = os.path.join(basedir, 'exclusion')
2756         fileutil.write(excl_filepath, exclusion_string)
2757         backup_options = parse(['--exclude-from', excl_filepath, 'from', 'to'])
2758         filtered = list(backup_options.filter_listdir(root_listdir))
2759         self._check_filtering(filtered, root_listdir, (u'_darcs', u'subdir'),
2760                              (nice_doc, u'lib.a'))
2761
2762         # test that an iterator works too
2763         backup_options = parse(['--exclude', doc_pattern_arg, 'from', 'to'])
2764         filtered = list(backup_options.filter_listdir(iter(root_listdir)))
2765         self._check_filtering(filtered, root_listdir, (u'lib.a', u'_darcs', u'subdir'),
2766                               (nice_doc,))
2767
2768     @patch('__builtin__.file')
2769     def test_exclude_from_tilde_expansion(self, mock):
2770         basedir = "cli/Backup/exclude_from_tilde_expansion"
2771         fileutil.make_dirs(basedir)
2772         nodeurl_path = os.path.join(basedir, 'node.url')
2773         fileutil.write(nodeurl_path, 'http://example.net:2357/')
2774         def parse(args): return parse_options(basedir, "backup", args)
2775
2776         # ensure that tilde expansion is performed on exclude-from argument
2777         exclude_file = u'~/.tahoe/excludes.dummy'
2778
2779         mock.return_value = StringIO()
2780         parse(['--exclude-from', unicode_to_argv(exclude_file), 'from', 'to'])
2781         self.failUnlessIn(((abspath_expanduser_unicode(exclude_file),), {}), mock.call_args_list)
2782
2783     def test_ignore_symlinks(self):
2784         if not hasattr(os, 'symlink'):
2785             raise unittest.SkipTest("Symlinks are not supported by Python on this platform.")
2786
2787         self.basedir = os.path.dirname(self.mktemp())
2788         self.set_up_grid()
2789
2790         source = os.path.join(self.basedir, "home")
2791         self.writeto("foo.txt", "foo")
2792         os.symlink(os.path.join(source, "foo.txt"), os.path.join(source, "foo2.txt"))
2793
2794         d = self.do_cli("create-alias", "tahoe")
2795         d.addCallback(lambda res: self.do_cli("backup", "--verbose", source, "tahoe:test"))
2796
2797         def _check((rc, out, err)):
2798             self.failUnlessReallyEqual(rc, 2)
2799             foo2 = os.path.join(source, "foo2.txt")
2800             self.failUnlessReallyEqual(err, "WARNING: cannot backup symlink '%s'\n" % foo2)
2801
2802             fu, fr, fs, dc, dr, ds = self.count_output(out)
2803             # foo.txt
2804             self.failUnlessReallyEqual(fu, 1)
2805             self.failUnlessReallyEqual(fr, 0)
2806             # foo2.txt
2807             self.failUnlessReallyEqual(fs, 1)
2808             # home
2809             self.failUnlessReallyEqual(dc, 1)
2810             self.failUnlessReallyEqual(dr, 0)
2811             self.failUnlessReallyEqual(ds, 0)
2812
2813         d.addCallback(_check)
2814         return d
2815
2816     def test_ignore_unreadable_file(self):
2817         self.basedir = os.path.dirname(self.mktemp())
2818         self.set_up_grid()
2819
2820         source = os.path.join(self.basedir, "home")
2821         self.writeto("foo.txt", "foo")
2822         os.chmod(os.path.join(source, "foo.txt"), 0000)
2823
2824         d = self.do_cli("create-alias", "tahoe")
2825         d.addCallback(lambda res: self.do_cli("backup", source, "tahoe:test"))
2826
2827         def _check((rc, out, err)):
2828             self.failUnlessReallyEqual(rc, 2)
2829             self.failUnlessReallyEqual(err, "WARNING: permission denied on file %s\n" % os.path.join(source, "foo.txt"))
2830
2831             fu, fr, fs, dc, dr, ds = self.count_output(out)
2832             self.failUnlessReallyEqual(fu, 0)
2833             self.failUnlessReallyEqual(fr, 0)
2834             # foo.txt
2835             self.failUnlessReallyEqual(fs, 1)
2836             # home
2837             self.failUnlessReallyEqual(dc, 1)
2838             self.failUnlessReallyEqual(dr, 0)
2839             self.failUnlessReallyEqual(ds, 0)
2840         d.addCallback(_check)
2841
2842         # This is necessary for the temp files to be correctly removed
2843         def _cleanup(self):
2844             os.chmod(os.path.join(source, "foo.txt"), 0644)
2845         d.addCallback(_cleanup)
2846         d.addErrback(_cleanup)
2847
2848         return d
2849
2850     def test_ignore_unreadable_directory(self):
2851         self.basedir = os.path.dirname(self.mktemp())
2852         self.set_up_grid()
2853
2854         source = os.path.join(self.basedir, "home")
2855         os.mkdir(source)
2856         os.mkdir(os.path.join(source, "test"))
2857         os.chmod(os.path.join(source, "test"), 0000)
2858
2859         d = self.do_cli("create-alias", "tahoe")
2860         d.addCallback(lambda res: self.do_cli("backup", source, "tahoe:test"))
2861
2862         def _check((rc, out, err)):
2863             self.failUnlessReallyEqual(rc, 2)
2864             self.failUnlessReallyEqual(err, "WARNING: permission denied on directory %s\n" % os.path.join(source, "test"))
2865
2866             fu, fr, fs, dc, dr, ds = self.count_output(out)
2867             self.failUnlessReallyEqual(fu, 0)
2868             self.failUnlessReallyEqual(fr, 0)
2869             self.failUnlessReallyEqual(fs, 0)
2870             # home, test
2871             self.failUnlessReallyEqual(dc, 2)
2872             self.failUnlessReallyEqual(dr, 0)
2873             # test
2874             self.failUnlessReallyEqual(ds, 1)
2875         d.addCallback(_check)
2876
2877         # This is necessary for the temp files to be correctly removed
2878         def _cleanup(self):
2879             os.chmod(os.path.join(source, "test"), 0655)
2880         d.addCallback(_cleanup)
2881         d.addErrback(_cleanup)
2882         return d
2883
2884     def test_backup_without_alias(self):
2885         # 'tahoe backup' should output a sensible error message when invoked
2886         # without an alias instead of a stack trace.
2887         self.basedir = os.path.dirname(self.mktemp())
2888         self.set_up_grid()
2889         source = os.path.join(self.basedir, "file1")
2890         d = self.do_cli('backup', source, source)
2891         def _check((rc, out, err)):
2892             self.failUnlessReallyEqual(rc, 1)
2893             self.failUnlessIn("error:", err)
2894             self.failUnlessReallyEqual(out, "")
2895         d.addCallback(_check)
2896         return d
2897
2898     def test_backup_with_nonexistent_alias(self):
2899         # 'tahoe backup' should output a sensible error message when invoked
2900         # with a nonexistent alias.
2901         self.basedir = os.path.dirname(self.mktemp())
2902         self.set_up_grid()
2903         source = os.path.join(self.basedir, "file1")
2904         d = self.do_cli("backup", source, "nonexistent:" + source)
2905         def _check((rc, out, err)):
2906             self.failUnlessReallyEqual(rc, 1)
2907             self.failUnlessIn("error:", err)
2908             self.failUnlessIn("nonexistent", err)
2909             self.failUnlessReallyEqual(out, "")
2910         d.addCallback(_check)
2911         return d
2912
2913
2914 class Check(GridTestMixin, CLITestMixin, unittest.TestCase):
2915
2916     def test_check(self):
2917         self.basedir = "cli/Check/check"
2918         self.set_up_grid()
2919         c0 = self.g.clients[0]
2920         DATA = "data" * 100
2921         DATA_uploadable = MutableData(DATA)
2922         d = c0.create_mutable_file(DATA_uploadable)
2923         def _stash_uri(n):
2924             self.uri = n.get_uri()
2925         d.addCallback(_stash_uri)
2926
2927         d.addCallback(lambda ign: self.do_cli("check", self.uri))
2928         def _check1((rc, out, err)):
2929             self.failUnlessReallyEqual(err, "")
2930             self.failUnlessReallyEqual(rc, 0)
2931             lines = out.splitlines()
2932             self.failUnless("Summary: Healthy" in lines, out)
2933             self.failUnless(" good-shares: 10 (encoding is 3-of-10)" in lines, out)
2934         d.addCallback(_check1)
2935
2936         d.addCallback(lambda ign: self.do_cli("check", "--raw", self.uri))
2937         def _check2((rc, out, err)):
2938             self.failUnlessReallyEqual(err, "")
2939             self.failUnlessReallyEqual(rc, 0)
2940             data = simplejson.loads(out)
2941             self.failUnlessReallyEqual(to_str(data["summary"]), "Healthy")
2942             self.failUnlessReallyEqual(data["results"]["healthy"], True)
2943         d.addCallback(_check2)
2944
2945         d.addCallback(lambda ign: c0.upload(upload.Data("literal", convergence="")))
2946         def _stash_lit_uri(n):
2947             self.lit_uri = n.get_uri()
2948         d.addCallback(_stash_lit_uri)
2949
2950         d.addCallback(lambda ign: self.do_cli("check", self.lit_uri))
2951         def _check_lit((rc, out, err)):
2952             self.failUnlessReallyEqual(err, "")
2953             self.failUnlessReallyEqual(rc, 0)
2954             lines = out.splitlines()
2955             self.failUnless("Summary: Healthy (LIT)" in lines, out)
2956         d.addCallback(_check_lit)
2957
2958         d.addCallback(lambda ign: self.do_cli("check", "--raw", self.lit_uri))
2959         def _check_lit_raw((rc, out, err)):
2960             self.failUnlessReallyEqual(err, "")
2961             self.failUnlessReallyEqual(rc, 0)
2962             data = simplejson.loads(out)
2963             self.failUnlessReallyEqual(data["results"]["healthy"], True)
2964         d.addCallback(_check_lit_raw)
2965
2966         d.addCallback(lambda ign: c0.create_immutable_dirnode({}, convergence=""))
2967         def _stash_lit_dir_uri(n):
2968             self.lit_dir_uri = n.get_uri()
2969         d.addCallback(_stash_lit_dir_uri)
2970
2971         d.addCallback(lambda ign: self.do_cli("check", self.lit_dir_uri))
2972         d.addCallback(_check_lit)
2973
2974         d.addCallback(lambda ign: self.do_cli("check", "--raw", self.lit_uri))
2975         d.addCallback(_check_lit_raw)
2976
2977         def _clobber_shares(ignored):
2978             # delete one, corrupt a second
2979             shares = self.find_uri_shares(self.uri)
2980             self.failUnlessReallyEqual(len(shares), 10)
2981             os.unlink(shares[0][2])
2982             cso = debug.CorruptShareOptions()
2983             cso.stdout = StringIO()
2984             cso.parseOptions([shares[1][2]])
2985             storage_index = uri.from_string(self.uri).get_storage_index()
2986             self._corrupt_share_line = "  server %s, SI %s, shnum %d" % \
2987                                        (base32.b2a(shares[1][1]),
2988                                         base32.b2a(storage_index),
2989                                         shares[1][0])
2990             debug.corrupt_share(cso)
2991         d.addCallback(_clobber_shares)
2992
2993         d.addCallback(lambda ign: self.do_cli("check", "--verify", self.uri))
2994         def _check3((rc, out, err)):
2995             self.failUnlessReallyEqual(err, "")
2996             self.failUnlessReallyEqual(rc, 0)
2997             lines = out.splitlines()
2998             summary = [l for l in lines if l.startswith("Summary")][0]
2999             self.failUnless("Summary: Unhealthy: 8 shares (enc 3-of-10)"
3000                             in summary, summary)
3001             self.failUnless(" good-shares: 8 (encoding is 3-of-10)" in lines, out)
3002             self.failUnless(" corrupt shares:" in lines, out)
3003             self.failUnless(self._corrupt_share_line in lines, out)
3004         d.addCallback(_check3)
3005
3006         d.addCallback(lambda ign: self.do_cli("check", "--verify", "--raw", self.uri))
3007         def _check3_raw((rc, out, err)):
3008             self.failUnlessReallyEqual(err, "")
3009             self.failUnlessReallyEqual(rc, 0)
3010             data = simplejson.loads(out)
3011             self.failUnlessReallyEqual(data["results"]["healthy"], False)
3012             self.failUnlessIn("Unhealthy: 8 shares (enc 3-of-10)", data["summary"])
3013             self.failUnlessReallyEqual(data["results"]["count-shares-good"], 8)
3014             self.failUnlessReallyEqual(data["results"]["count-corrupt-shares"], 1)
3015             self.failUnlessIn("list-corrupt-shares", data["results"])
3016         d.addCallback(_check3_raw)
3017
3018         d.addCallback(lambda ign:
3019                       self.do_cli("check", "--verify", "--repair", self.uri))
3020         def _check4((rc, out, err)):
3021             self.failUnlessReallyEqual(err, "")
3022             self.failUnlessReallyEqual(rc, 0)
3023             lines = out.splitlines()
3024             self.failUnless("Summary: not healthy" in lines, out)
3025             self.failUnless(" good-shares: 8 (encoding is 3-of-10)" in lines, out)
3026             self.failUnless(" corrupt shares:" in lines, out)
3027             self.failUnless(self._corrupt_share_line in lines, out)
3028             self.failUnless(" repair successful" in lines, out)
3029         d.addCallback(_check4)
3030
3031         d.addCallback(lambda ign:
3032                       self.do_cli("check", "--verify", "--repair", self.uri))
3033         def _check5((rc, out, err)):
3034             self.failUnlessReallyEqual(err, "")
3035             self.failUnlessReallyEqual(rc, 0)
3036             lines = out.splitlines()
3037             self.failUnless("Summary: healthy" in lines, out)
3038             self.failUnless(" good-shares: 10 (encoding is 3-of-10)" in lines, out)
3039             self.failIf(" corrupt shares:" in lines, out)
3040         d.addCallback(_check5)
3041
3042         return d
3043
3044     def test_deep_check(self):
3045         self.basedir = "cli/Check/deep_check"
3046         self.set_up_grid()
3047         c0 = self.g.clients[0]
3048         self.uris = {}
3049         self.fileurls = {}
3050         DATA = "data" * 100
3051         quoted_good = quote_output(u"g\u00F6\u00F6d")
3052
3053         d = c0.create_dirnode()
3054         def _stash_root_and_create_file(n):
3055             self.rootnode = n
3056             self.rooturi = n.get_uri()
3057             return n.add_file(u"g\u00F6\u00F6d", upload.Data(DATA, convergence=""))
3058         d.addCallback(_stash_root_and_create_file)
3059         def _stash_uri(fn, which):
3060             self.uris[which] = fn.get_uri()
3061             return fn
3062         d.addCallback(_stash_uri, u"g\u00F6\u00F6d")
3063         d.addCallback(lambda ign:
3064                       self.rootnode.add_file(u"small",
3065                                            upload.Data("literal",
3066                                                         convergence="")))
3067         d.addCallback(_stash_uri, "small")
3068         d.addCallback(lambda ign:
3069             c0.create_mutable_file(MutableData(DATA+"1")))
3070         d.addCallback(lambda fn: self.rootnode.set_node(u"mutable", fn))
3071         d.addCallback(_stash_uri, "mutable")
3072
3073         d.addCallback(lambda ign: self.do_cli("deep-check", self.rooturi))
3074         def _check1((rc, out, err)):
3075             self.failUnlessReallyEqual(err, "")
3076             self.failUnlessReallyEqual(rc, 0)
3077             lines = out.splitlines()
3078             self.failUnless("done: 4 objects checked, 4 healthy, 0 unhealthy"
3079                             in lines, out)
3080         d.addCallback(_check1)
3081
3082         # root
3083         # root/g\u00F6\u00F6d
3084         # root/small
3085         # root/mutable
3086
3087         d.addCallback(lambda ign: self.do_cli("deep-check", "--verbose",
3088                                               self.rooturi))
3089         def _check2((rc, out, err)):
3090             self.failUnlessReallyEqual(err, "")
3091             self.failUnlessReallyEqual(rc, 0)
3092             lines = out.splitlines()
3093             self.failUnless("'<root>': Healthy" in lines, out)
3094             self.failUnless("'small': Healthy (LIT)" in lines, out)
3095             self.failUnless((quoted_good + ": Healthy") in lines, out)
3096             self.failUnless("'mutable': Healthy" in lines, out)
3097             self.failUnless("done: 4 objects checked, 4 healthy, 0 unhealthy"
3098                             in lines, out)
3099         d.addCallback(_check2)
3100
3101         d.addCallback(lambda ign: self.do_cli("stats", self.rooturi))
3102         def _check_stats((rc, out, err)):
3103             self.failUnlessReallyEqual(err, "")
3104             self.failUnlessReallyEqual(rc, 0)
3105             lines = out.splitlines()
3106             self.failUnlessIn(" count-immutable-files: 1", lines)
3107             self.failUnlessIn("   count-mutable-files: 1", lines)
3108             self.failUnlessIn("   count-literal-files: 1", lines)
3109             self.failUnlessIn("     count-directories: 1", lines)
3110             self.failUnlessIn("  size-immutable-files: 400", lines)
3111             self.failUnlessIn("Size Histogram:", lines)
3112             self.failUnlessIn("   4-10   : 1    (10 B, 10 B)", lines)
3113             self.failUnlessIn(" 317-1000 : 1    (1000 B, 1000 B)", lines)
3114         d.addCallback(_check_stats)
3115
3116         def _clobber_shares(ignored):
3117             shares = self.find_uri_shares(self.uris[u"g\u00F6\u00F6d"])
3118             self.failUnlessReallyEqual(len(shares), 10)
3119             os.unlink(shares[0][2])
3120
3121             shares = self.find_uri_shares(self.uris["mutable"])
3122             cso = debug.CorruptShareOptions()
3123             cso.stdout = StringIO()
3124             cso.parseOptions([shares[1][2]])
3125             storage_index = uri.from_string(self.uris["mutable"]).get_storage_index()
3126             self._corrupt_share_line = " corrupt: server %s, SI %s, shnum %d" % \
3127                                        (base32.b2a(shares[1][1]),
3128                                         base32.b2a(storage_index),
3129                                         shares[1][0])
3130             debug.corrupt_share(cso)
3131         d.addCallback(_clobber_shares)
3132
3133         # root
3134         # root/g\u00F6\u00F6d  [9 shares]
3135         # root/small
3136         # root/mutable [1 corrupt share]
3137
3138         d.addCallback(lambda ign:
3139                       self.do_cli("deep-check", "--verbose", self.rooturi))
3140         def _check3((rc, out, err)):
3141             self.failUnlessReallyEqual(err, "")
3142             self.failUnlessReallyEqual(rc, 0)
3143             lines = out.splitlines()
3144             self.failUnless("'<root>': Healthy" in lines, out)
3145             self.failUnless("'small': Healthy (LIT)" in lines, out)
3146             self.failUnless("'mutable': Healthy" in lines, out) # needs verifier
3147             self.failUnless((quoted_good + ": Not Healthy: 9 shares (enc 3-of-10)") in lines, out)
3148             self.failIf(self._corrupt_share_line in lines, out)
3149             self.failUnless("done: 4 objects checked, 3 healthy, 1 unhealthy"
3150                             in lines, out)
3151         d.addCallback(_check3)
3152
3153         d.addCallback(lambda ign:
3154                       self.do_cli("deep-check", "--verbose", "--verify",
3155                                   self.rooturi))
3156         def _check4((rc, out, err)):
3157             self.failUnlessReallyEqual(err, "")
3158             self.failUnlessReallyEqual(rc, 0)
3159             lines = out.splitlines()
3160             self.failUnless("'<root>': Healthy" in lines, out)
3161             self.failUnless("'small': Healthy (LIT)" in lines, out)
3162             mutable = [l for l in lines if l.startswith("'mutable'")][0]
3163             self.failUnless(mutable.startswith("'mutable': Unhealthy: 9 shares (enc 3-of-10)"),
3164                             mutable)
3165             self.failUnless(self._corrupt_share_line in lines, out)
3166             self.failUnless((quoted_good + ": Not Healthy: 9 shares (enc 3-of-10)") in lines, out)
3167             self.failUnless("done: 4 objects checked, 2 healthy, 2 unhealthy"
3168                             in lines, out)
3169         d.addCallback(_check4)
3170
3171         d.addCallback(lambda ign:
3172                       self.do_cli("deep-check", "--raw",
3173                                   self.rooturi))
3174         def _check5((rc, out, err)):
3175             self.failUnlessReallyEqual(err, "")
3176             self.failUnlessReallyEqual(rc, 0)
3177             lines = out.splitlines()
3178             units = [simplejson.loads(line) for line in lines]
3179             # root, small, g\u00F6\u00F6d, mutable,  stats
3180             self.failUnlessReallyEqual(len(units), 4+1)
3181         d.addCallback(_check5)
3182
3183         d.addCallback(lambda ign:
3184                       self.do_cli("deep-check",
3185                                   "--verbose", "--verify", "--repair",
3186                                   self.rooturi))
3187         def _check6((rc, out, err)):
3188             self.failUnlessReallyEqual(err, "")
3189             self.failUnlessReallyEqual(rc, 0)
3190             lines = out.splitlines()
3191             self.failUnless("'<root>': healthy" in lines, out)
3192             self.failUnless("'small': healthy" in lines, out)
3193             self.failUnless("'mutable': not healthy" in lines, out)
3194             self.failUnless(self._corrupt_share_line in lines, out)
3195             self.failUnless((quoted_good + ": not healthy") in lines, out)
3196             self.failUnless("done: 4 objects checked" in lines, out)
3197             self.failUnless(" pre-repair: 2 healthy, 2 unhealthy" in lines, out)
3198             self.failUnless(" 2 repairs attempted, 2 successful, 0 failed"
3199                             in lines, out)
3200             self.failUnless(" post-repair: 4 healthy, 0 unhealthy" in lines,out)
3201         d.addCallback(_check6)
3202
3203         # now add a subdir, and a file below that, then make the subdir
3204         # unrecoverable
3205
3206         d.addCallback(lambda ign: self.rootnode.create_subdirectory(u"subdir"))
3207         d.addCallback(_stash_uri, "subdir")
3208         d.addCallback(lambda fn:
3209                       fn.add_file(u"subfile", upload.Data(DATA+"2", "")))
3210         d.addCallback(lambda ign:
3211                       self.delete_shares_numbered(self.uris["subdir"],
3212                                                   range(10)))
3213
3214         # root
3215         # rootg\u00F6\u00F6d/
3216         # root/small
3217         # root/mutable
3218         # root/subdir [unrecoverable: 0 shares]
3219         # root/subfile
3220
3221         d.addCallback(lambda ign: self.do_cli("manifest", self.rooturi))
3222         def _manifest_failed((rc, out, err)):
3223             self.failIfEqual(rc, 0)
3224             self.failUnlessIn("ERROR: UnrecoverableFileError", err)
3225             # the fatal directory should still show up, as the last line
3226             self.failUnlessIn(" subdir\n", out)
3227         d.addCallback(_manifest_failed)
3228
3229         d.addCallback(lambda ign: self.do_cli("deep-check", self.rooturi))
3230         def _deep_check_failed((rc, out, err)):
3231             self.failIfEqual(rc, 0)
3232             self.failUnlessIn("ERROR: UnrecoverableFileError", err)
3233             # we want to make sure that the error indication is the last
3234             # thing that gets emitted
3235             self.failIf("done:" in out, out)
3236         d.addCallback(_deep_check_failed)
3237
3238         # this test is disabled until the deep-repair response to an
3239         # unrepairable directory is fixed. The failure-to-repair should not
3240         # throw an exception, but the failure-to-traverse that follows
3241         # should throw UnrecoverableFileError.
3242
3243         #d.addCallback(lambda ign:
3244         #              self.do_cli("deep-check", "--repair", self.rooturi))
3245         #def _deep_check_repair_failed((rc, out, err)):
3246         #    self.failIfEqual(rc, 0)
3247         #    print err
3248         #    self.failUnlessIn("ERROR: UnrecoverableFileError", err)
3249         #    self.failIf("done:" in out, out)
3250         #d.addCallback(_deep_check_repair_failed)
3251
3252         return d
3253
3254     def test_check_without_alias(self):
3255         # 'tahoe check' should output a sensible error message if it needs to
3256         # find the default alias and can't
3257         self.basedir = "cli/Check/check_without_alias"
3258         self.set_up_grid()
3259         d = self.do_cli("check")
3260         def _check((rc, out, err)):
3261             self.failUnlessReallyEqual(rc, 1)
3262             self.failUnlessIn("error:", err)
3263             self.failUnlessReallyEqual(out, "")
3264         d.addCallback(_check)
3265         d.addCallback(lambda ign: self.do_cli("deep-check"))
3266         d.addCallback(_check)
3267         return d
3268
3269     def test_check_with_nonexistent_alias(self):
3270         # 'tahoe check' should output a sensible error message if it needs to
3271         # find an alias and can't.
3272         self.basedir = "cli/Check/check_with_nonexistent_alias"
3273         self.set_up_grid()
3274         d = self.do_cli("check", "nonexistent:")
3275         def _check((rc, out, err)):
3276             self.failUnlessReallyEqual(rc, 1)
3277             self.failUnlessIn("error:", err)
3278             self.failUnlessIn("nonexistent", err)
3279             self.failUnlessReallyEqual(out, "")
3280         d.addCallback(_check)
3281         return d
3282
3283
3284 class Errors(GridTestMixin, CLITestMixin, unittest.TestCase):
3285     def test_get(self):
3286         self.basedir = "cli/Errors/get"
3287         self.set_up_grid()
3288         c0 = self.g.clients[0]
3289         self.fileurls = {}
3290         DATA = "data" * 100
3291         d = c0.upload(upload.Data(DATA, convergence=""))
3292         def _stash_bad(ur):
3293             self.uri_1share = ur.get_uri()
3294             self.delete_shares_numbered(ur.get_uri(), range(1,10))
3295         d.addCallback(_stash_bad)
3296
3297         # the download is abandoned as soon as it's clear that we won't get
3298         # enough shares. The one remaining share might be in either the
3299         # COMPLETE or the PENDING state.
3300         in_complete_msg = "ran out of shares: complete=sh0 pending= overdue= unused= need 3"
3301         in_pending_msg = "ran out of shares: complete= pending=Share(sh0-on-fob7vqgd) overdue= unused= need 3"
3302
3303         d.addCallback(lambda ign: self.do_cli("get", self.uri_1share))
3304         def _check1((rc, out, err)):
3305             self.failIfEqual(rc, 0)
3306             self.failUnless("410 Gone" in err, err)
3307             self.failUnlessIn("NotEnoughSharesError: ", err)
3308             self.failUnless(in_complete_msg in err or in_pending_msg in err,
3309                             err)
3310         d.addCallback(_check1)
3311
3312         targetf = os.path.join(self.basedir, "output")
3313         d.addCallback(lambda ign: self.do_cli("get", self.uri_1share, targetf))
3314         def _check2((rc, out, err)):
3315             self.failIfEqual(rc, 0)
3316             self.failUnless("410 Gone" in err, err)
3317             self.failUnlessIn("NotEnoughSharesError: ", err)
3318             self.failUnless(in_complete_msg in err or in_pending_msg in err,
3319                             err)
3320             self.failIf(os.path.exists(targetf))
3321         d.addCallback(_check2)
3322
3323         return d
3324
3325     def test_broken_socket(self):
3326         # When the http connection breaks (such as when node.url is overwritten
3327         # by a confused user), a user friendly error message should be printed.
3328         self.basedir = "cli/Errors/test_broken_socket"
3329         self.set_up_grid()
3330
3331         # Simulate a connection error
3332         def _socket_error(*args, **kwargs):
3333             raise socket_error('test error')
3334         self.patch(allmydata.scripts.common_http.httplib.HTTPConnection,
3335                    "endheaders", _socket_error)
3336
3337         d = self.do_cli("mkdir")
3338         def _check_invalid((rc,stdout,stderr)):
3339             self.failIfEqual(rc, 0)
3340             self.failUnlessIn("Error trying to connect to http://127.0.0.1", stderr)
3341         d.addCallback(_check_invalid)
3342         return d
3343
3344
3345 class Get(GridTestMixin, CLITestMixin, unittest.TestCase):
3346     def test_get_without_alias(self):
3347         # 'tahoe get' should output a useful error message when invoked
3348         # without an explicit alias and when the default 'tahoe' alias
3349         # hasn't been created yet.
3350         self.basedir = "cli/Get/get_without_alias"
3351         self.set_up_grid()
3352         d = self.do_cli('get', 'file')
3353         def _check((rc, out, err)):
3354             self.failUnlessReallyEqual(rc, 1)
3355             self.failUnlessIn("error:", err)
3356             self.failUnlessReallyEqual(out, "")
3357         d.addCallback(_check)
3358         return d
3359
3360     def test_get_with_nonexistent_alias(self):
3361         # 'tahoe get' should output a useful error message when invoked with
3362         # an explicit alias that doesn't exist.
3363         self.basedir = "cli/Get/get_with_nonexistent_alias"
3364         self.set_up_grid()
3365         d = self.do_cli("get", "nonexistent:file")
3366         def _check((rc, out, err)):
3367             self.failUnlessReallyEqual(rc, 1)
3368             self.failUnlessIn("error:", err)
3369             self.failUnlessIn("nonexistent", err)
3370             self.failUnlessReallyEqual(out, "")
3371         d.addCallback(_check)
3372         return d
3373
3374
3375 class Manifest(GridTestMixin, CLITestMixin, unittest.TestCase):
3376     def test_manifest_without_alias(self):
3377         # 'tahoe manifest' should output a useful error message when invoked
3378         # without an explicit alias when the default 'tahoe' alias is
3379         # missing.
3380         self.basedir = "cli/Manifest/manifest_without_alias"
3381         self.set_up_grid()
3382         d = self.do_cli("manifest")
3383         def _check((rc, out, err)):
3384             self.failUnlessReallyEqual(rc, 1)
3385             self.failUnlessIn("error:", err)
3386             self.failUnlessReallyEqual(out, "")
3387         d.addCallback(_check)
3388         return d
3389
3390     def test_manifest_with_nonexistent_alias(self):
3391         # 'tahoe manifest' should output a useful error message when invoked
3392         # with an explicit alias that doesn't exist.
3393         self.basedir = "cli/Manifest/manifest_with_nonexistent_alias"
3394         self.set_up_grid()
3395         d = self.do_cli("manifest", "nonexistent:")
3396         def _check((rc, out, err)):
3397             self.failUnlessReallyEqual(rc, 1)
3398             self.failUnlessIn("error:", err)
3399             self.failUnlessIn("nonexistent", err)
3400             self.failUnlessReallyEqual(out, "")
3401         d.addCallback(_check)
3402         return d
3403
3404
3405 class Mkdir(GridTestMixin, CLITestMixin, unittest.TestCase):
3406     def test_mkdir(self):
3407         self.basedir = os.path.dirname(self.mktemp())
3408         self.set_up_grid()
3409
3410         d = self.do_cli("create-alias", "tahoe")
3411         d.addCallback(lambda res: self.do_cli("mkdir", "test"))
3412         def _check((rc, out, err)):
3413             self.failUnlessReallyEqual(rc, 0)
3414             self.failUnlessReallyEqual(err, "")
3415             self.failUnlessIn("URI:", out)
3416         d.addCallback(_check)
3417
3418         return d
3419
3420     def test_mkdir_mutable_type(self):
3421         self.basedir = os.path.dirname(self.mktemp())
3422         self.set_up_grid()
3423         d = self.do_cli("create-alias", "tahoe")
3424         def _check((rc, out, err), st):
3425             self.failUnlessReallyEqual(rc, 0)
3426             self.failUnlessReallyEqual(err, "")
3427             self.failUnlessIn(st, out)
3428             return out
3429         def _mkdir(ign, mutable_type, uri_prefix, dirname):
3430             d2 = self.do_cli("mkdir", "--format="+mutable_type, dirname)
3431             d2.addCallback(_check, uri_prefix)
3432             def _stash_filecap(cap):
3433                 u = uri.from_string(cap)
3434                 fn_uri = u.get_filenode_cap()
3435                 self._filecap = fn_uri.to_string()
3436             d2.addCallback(_stash_filecap)
3437             d2.addCallback(lambda ign: self.do_cli("ls", "--json", dirname))
3438             d2.addCallback(_check, uri_prefix)
3439             d2.addCallback(lambda ign: self.do_cli("ls", "--json", self._filecap))
3440             d2.addCallback(_check, '"format": "%s"' % (mutable_type.upper(),))
3441             return d2
3442
3443         d.addCallback(_mkdir, "sdmf", "URI:DIR2", "tahoe:foo")
3444         d.addCallback(_mkdir, "SDMF", "URI:DIR2", "tahoe:foo2")
3445         d.addCallback(_mkdir, "mdmf", "URI:DIR2-MDMF", "tahoe:bar")
3446         d.addCallback(_mkdir, "MDMF", "URI:DIR2-MDMF", "tahoe:bar2")
3447         return d
3448
3449     def test_mkdir_mutable_type_unlinked(self):
3450         self.basedir = os.path.dirname(self.mktemp())
3451         self.set_up_grid()
3452         d = self.do_cli("mkdir", "--format=SDMF")
3453         def _check((rc, out, err), st):
3454             self.failUnlessReallyEqual(rc, 0)
3455             self.failUnlessReallyEqual(err, "")
3456             self.failUnlessIn(st, out)
3457             return out
3458         d.addCallback(_check, "URI:DIR2")
3459         def _stash_dircap(cap):
3460             self._dircap = cap
3461             # Now we're going to feed the cap into uri.from_string...
3462             u = uri.from_string(cap)
3463             # ...grab the underlying filenode uri.
3464             fn_uri = u.get_filenode_cap()
3465             # ...and stash that.
3466             self._filecap = fn_uri.to_string()
3467         d.addCallback(_stash_dircap)
3468         d.addCallback(lambda res: self.do_cli("ls", "--json",
3469                                               self._filecap))
3470         d.addCallback(_check, '"format": "SDMF"')
3471         d.addCallback(lambda res: self.do_cli("mkdir", "--format=MDMF"))
3472         d.addCallback(_check, "URI:DIR2-MDMF")
3473         d.addCallback(_stash_dircap)
3474         d.addCallback(lambda res: self.do_cli("ls", "--json",
3475                                               self._filecap))
3476         d.addCallback(_check, '"format": "MDMF"')
3477         return d
3478
3479     def test_mkdir_bad_mutable_type(self):
3480         o = cli.MakeDirectoryOptions()
3481         self.failUnlessRaises(usage.UsageError,
3482                               o.parseOptions,
3483                               ["--format=LDMF"])
3484
3485     def test_mkdir_unicode(self):
3486         self.basedir = os.path.dirname(self.mktemp())
3487         self.set_up_grid()
3488
3489         try:
3490             motorhead_arg = u"tahoe:Mot\u00F6rhead".encode(get_io_encoding())
3491         except UnicodeEncodeError:
3492             raise unittest.SkipTest("A non-ASCII command argument could not be encoded on this platform.")
3493
3494         d = self.do_cli("create-alias", "tahoe")
3495         d.addCallback(lambda res: self.do_cli("mkdir", motorhead_arg))
3496         def _check((rc, out, err)):
3497             self.failUnlessReallyEqual(rc, 0)
3498             self.failUnlessReallyEqual(err, "")
3499             self.failUnlessIn("URI:", out)
3500         d.addCallback(_check)
3501
3502         return d
3503
3504     def test_mkdir_with_nonexistent_alias(self):
3505         # when invoked with an alias that doesn't exist, 'tahoe mkdir' should
3506         # output a sensible error message rather than a stack trace.
3507         self.basedir = "cli/Mkdir/mkdir_with_nonexistent_alias"
3508         self.set_up_grid()
3509         d = self.do_cli("mkdir", "havasu:")
3510         def _check((rc, out, err)):
3511             self.failUnlessReallyEqual(rc, 1)
3512             self.failUnlessIn("error:", err)
3513             self.failUnlessReallyEqual(out, "")
3514         d.addCallback(_check)
3515         return d
3516
3517
3518 class Unlink(GridTestMixin, CLITestMixin, unittest.TestCase):
3519     command = "unlink"
3520
3521     def _create_test_file(self):
3522         data = "puppies" * 1000
3523         path = os.path.join(self.basedir, "datafile")
3524         fileutil.write(path, data)
3525         self.datafile = path
3526
3527     def test_unlink_without_alias(self):
3528         # 'tahoe unlink' should behave sensibly when invoked without an explicit
3529         # alias before the default 'tahoe' alias has been created.
3530         self.basedir = "cli/Unlink/%s_without_alias" % (self.command,)
3531         self.set_up_grid()
3532         d = self.do_cli(self.command, "afile")
3533         def _check((rc, out, err)):
3534             self.failUnlessReallyEqual(rc, 1)
3535             self.failUnlessIn("error:", err)
3536             self.failUnlessReallyEqual(out, "")
3537         d.addCallback(_check)
3538
3539         d.addCallback(lambda ign: self.do_cli(self.command, "afile"))
3540         d.addCallback(_check)
3541         return d
3542
3543     def test_unlink_with_nonexistent_alias(self):
3544         # 'tahoe unlink' should behave sensibly when invoked with an explicit
3545         # alias that doesn't exist.
3546         self.basedir = "cli/Unlink/%s_with_nonexistent_alias" % (self.command,)
3547         self.set_up_grid()
3548         d = self.do_cli(self.command, "nonexistent:afile")
3549         def _check((rc, out, err)):
3550             self.failUnlessReallyEqual(rc, 1)
3551             self.failUnlessIn("error:", err)
3552             self.failUnlessIn("nonexistent", err)
3553             self.failUnlessReallyEqual(out, "")
3554         d.addCallback(_check)
3555
3556         d.addCallback(lambda ign: self.do_cli(self.command, "nonexistent:afile"))
3557         d.addCallback(_check)
3558         return d
3559
3560     def test_unlink_without_path(self):
3561         # 'tahoe unlink' should give a sensible error message when invoked without a path.
3562         self.basedir = "cli/Unlink/%s_without_path" % (self.command,)
3563         self.set_up_grid()
3564         self._create_test_file()
3565         d = self.do_cli("create-alias", "tahoe")
3566         d.addCallback(lambda ign: self.do_cli("put", self.datafile, "tahoe:test"))
3567         def _do_unlink((rc, out, err)):
3568             self.failUnlessReallyEqual(rc, 0)
3569             self.failUnless(out.startswith("URI:"), out)
3570             return self.do_cli(self.command, out.strip('\n'))
3571         d.addCallback(_do_unlink)
3572
3573         def _check((rc, out, err)):
3574             self.failUnlessReallyEqual(rc, 1)
3575             self.failUnlessIn("'tahoe %s'" % (self.command,), err)
3576             self.failUnlessIn("path must be given", err)
3577             self.failUnlessReallyEqual(out, "")
3578         d.addCallback(_check)
3579         return d
3580
3581
3582 class Rm(Unlink):
3583     """Test that 'tahoe rm' behaves in the same way as 'tahoe unlink'."""
3584     command = "rm"
3585
3586
3587 class Stats(GridTestMixin, CLITestMixin, unittest.TestCase):
3588     def test_empty_directory(self):
3589         self.basedir = "cli/Stats/empty_directory"
3590         self.set_up_grid()
3591         c0 = self.g.clients[0]
3592         self.fileurls = {}
3593         d = c0.create_dirnode()
3594         def _stash_root(n):
3595             self.rootnode = n
3596             self.rooturi = n.get_uri()
3597         d.addCallback(_stash_root)
3598
3599         # make sure we can get stats on an empty directory too
3600         d.addCallback(lambda ign: self.do_cli("stats", self.rooturi))
3601         def _check_stats((rc, out, err)):
3602             self.failUnlessReallyEqual(err, "")
3603             self.failUnlessReallyEqual(rc, 0)
3604             lines = out.splitlines()
3605             self.failUnlessIn(" count-immutable-files: 0", lines)
3606             self.failUnlessIn("   count-mutable-files: 0", lines)
3607             self.failUnlessIn("   count-literal-files: 0", lines)
3608             self.failUnlessIn("     count-directories: 1", lines)
3609             self.failUnlessIn("  size-immutable-files: 0", lines)
3610             self.failIfIn("Size Histogram:", lines)
3611         d.addCallback(_check_stats)
3612
3613         return d
3614
3615     def test_stats_without_alias(self):
3616         # when invoked with no explicit alias and before the default 'tahoe'
3617         # alias is created, 'tahoe stats' should output an informative error
3618         # message, not a stack trace.
3619         self.basedir = "cli/Stats/stats_without_alias"
3620         self.set_up_grid()
3621         d = self.do_cli("stats")
3622         def _check((rc, out, err)):
3623             self.failUnlessReallyEqual(rc, 1)
3624             self.failUnlessIn("error:", err)
3625             self.failUnlessReallyEqual(out, "")
3626         d.addCallback(_check)
3627         return d
3628
3629     def test_stats_with_nonexistent_alias(self):
3630         # when invoked with an explicit alias that doesn't exist,
3631         # 'tahoe stats' should output a useful error message.
3632         self.basedir = "cli/Stats/stats_with_nonexistent_alias"
3633         self.set_up_grid()
3634         d = self.do_cli("stats", "havasu:")
3635         def _check((rc, out, err)):
3636             self.failUnlessReallyEqual(rc, 1)
3637             self.failUnlessIn("error:", err)
3638             self.failUnlessReallyEqual(out, "")
3639         d.addCallback(_check)
3640         return d
3641
3642
3643 class Webopen(GridTestMixin, CLITestMixin, unittest.TestCase):
3644     def test_webopen_with_nonexistent_alias(self):
3645         # when invoked with an alias that doesn't exist, 'tahoe webopen'
3646         # should output an informative error message instead of a stack
3647         # trace.
3648         self.basedir = "cli/Webopen/webopen_with_nonexistent_alias"
3649         self.set_up_grid()
3650         d = self.do_cli("webopen", "fake:")
3651         def _check((rc, out, err)):
3652             self.failUnlessReallyEqual(rc, 1)
3653             self.failUnlessIn("error:", err)
3654             self.failUnlessReallyEqual(out, "")
3655         d.addCallback(_check)
3656         return d
3657
3658     def test_webopen(self):
3659         # TODO: replace with @patch that supports Deferreds.
3660         import webbrowser
3661         def call_webbrowser_open(url):
3662             self.failUnlessIn(self.alias_uri.replace(':', '%3A'), url)
3663             self.webbrowser_open_called = True
3664         def _cleanup(res):
3665             webbrowser.open = self.old_webbrowser_open
3666             return res
3667
3668         self.old_webbrowser_open = webbrowser.open
3669         try:
3670             webbrowser.open = call_webbrowser_open
3671
3672             self.basedir = "cli/Webopen/webopen"
3673             self.set_up_grid()
3674             d = self.do_cli("create-alias", "alias:")
3675             def _check_alias((rc, out, err)):
3676                 self.failUnlessReallyEqual(rc, 0, repr((rc, out, err)))
3677                 self.failUnlessIn("Alias 'alias' created", out)
3678                 self.failUnlessReallyEqual(err, "")
3679                 self.alias_uri = get_aliases(self.get_clientdir())["alias"]
3680             d.addCallback(_check_alias)
3681             d.addCallback(lambda res: self.do_cli("webopen", "alias:"))
3682             def _check_webopen((rc, out, err)):
3683                 self.failUnlessReallyEqual(rc, 0, repr((rc, out, err)))
3684                 self.failUnlessReallyEqual(out, "")
3685                 self.failUnlessReallyEqual(err, "")
3686                 self.failUnless(self.webbrowser_open_called)
3687             d.addCallback(_check_webopen)
3688             d.addBoth(_cleanup)
3689         except:
3690             _cleanup(None)
3691             raise
3692         return d
3693
3694 class Options(unittest.TestCase):
3695     # this test case only looks at argument-processing and simple stuff.
3696
3697     def parse(self, args, stdout=None):
3698         o = runner.Options()
3699         if stdout is not None:
3700             o.stdout = stdout
3701         o.parseOptions(args)
3702         while hasattr(o, "subOptions"):
3703             o = o.subOptions
3704         return o
3705
3706     def test_list(self):
3707         fileutil.rm_dir("cli/test_options")
3708         fileutil.make_dirs("cli/test_options")
3709         fileutil.make_dirs("cli/test_options/private")
3710         fileutil.write("cli/test_options/node.url", "http://localhost:8080/\n")
3711         filenode_uri = uri.WriteableSSKFileURI(writekey="\x00"*16,
3712                                                fingerprint="\x00"*32)
3713         private_uri = uri.DirectoryURI(filenode_uri).to_string()
3714         fileutil.write("cli/test_options/private/root_dir.cap", private_uri + "\n")
3715         def parse2(args): return parse_options("cli/test_options", "ls", args)
3716         o = parse2([])
3717         self.failUnlessEqual(o['node-url'], "http://localhost:8080/")
3718         self.failUnlessEqual(o.aliases[DEFAULT_ALIAS], private_uri)
3719         self.failUnlessEqual(o.where, u"")
3720
3721         o = parse2(["--node-url", "http://example.org:8111/"])
3722         self.failUnlessEqual(o['node-url'], "http://example.org:8111/")
3723         self.failUnlessEqual(o.aliases[DEFAULT_ALIAS], private_uri)
3724         self.failUnlessEqual(o.where, u"")
3725
3726         o = parse2(["--dir-cap", "root"])
3727         self.failUnlessEqual(o['node-url'], "http://localhost:8080/")
3728         self.failUnlessEqual(o.aliases[DEFAULT_ALIAS], "root")
3729         self.failUnlessEqual(o.where, u"")
3730
3731         other_filenode_uri = uri.WriteableSSKFileURI(writekey="\x11"*16,
3732                                                      fingerprint="\x11"*32)
3733         other_uri = uri.DirectoryURI(other_filenode_uri).to_string()
3734         o = parse2(["--dir-cap", other_uri])
3735         self.failUnlessEqual(o['node-url'], "http://localhost:8080/")
3736         self.failUnlessEqual(o.aliases[DEFAULT_ALIAS], other_uri)
3737         self.failUnlessEqual(o.where, u"")
3738
3739         o = parse2(["--dir-cap", other_uri, "subdir"])
3740         self.failUnlessEqual(o['node-url'], "http://localhost:8080/")
3741         self.failUnlessEqual(o.aliases[DEFAULT_ALIAS], other_uri)
3742         self.failUnlessEqual(o.where, u"subdir")
3743
3744         self.failUnlessRaises(usage.UsageError, parse2,
3745                               ["--node-url", "NOT-A-URL"])
3746
3747         o = parse2(["--node-url", "http://localhost:8080"])
3748         self.failUnlessEqual(o["node-url"], "http://localhost:8080/")
3749
3750         o = parse2(["--node-url", "https://localhost/"])
3751         self.failUnlessEqual(o["node-url"], "https://localhost/")
3752
3753     def test_version(self):
3754         # "tahoe --version" dumps text to stdout and exits
3755         stdout = StringIO()
3756         self.failUnlessRaises(SystemExit, self.parse, ["--version"], stdout)
3757         self.failUnlessIn("allmydata-tahoe", stdout.getvalue())
3758         # but "tahoe SUBCOMMAND --version" should be rejected
3759         self.failUnlessRaises(usage.UsageError, self.parse,
3760                               ["start", "--version"])
3761         self.failUnlessRaises(usage.UsageError, self.parse,
3762                               ["start", "--version-and-path"])
3763
3764     def test_quiet(self):
3765         # accepted as an overall option, but not on subcommands
3766         o = self.parse(["--quiet", "start"])
3767         self.failUnless(o.parent["quiet"])
3768         self.failUnlessRaises(usage.UsageError, self.parse,
3769                               ["start", "--quiet"])
3770
3771     def test_basedir(self):
3772         # accept a --node-directory option before the verb, or a --basedir
3773         # option after, or a basedir argument after, but none in the wrong
3774         # place, and not more than one of the three.
3775         o = self.parse(["start"])
3776         self.failUnlessEqual(o["basedir"], os.path.join(os.path.expanduser("~"),
3777                                                         ".tahoe"))
3778         o = self.parse(["start", "here"])
3779         self.failUnlessEqual(o["basedir"], os.path.abspath("here"))
3780         o = self.parse(["start", "--basedir", "there"])
3781         self.failUnlessEqual(o["basedir"], os.path.abspath("there"))
3782         o = self.parse(["--node-directory", "there", "start"])
3783         self.failUnlessEqual(o["basedir"], os.path.abspath("there"))
3784
3785         self.failUnlessRaises(usage.UsageError, self.parse,
3786                               ["--basedir", "there", "start"])
3787         self.failUnlessRaises(usage.UsageError, self.parse,
3788                               ["start", "--node-directory", "there"])
3789
3790         self.failUnlessRaises(usage.UsageError, self.parse,
3791                               ["--node-directory=there",
3792                                "start", "--basedir=here"])
3793         self.failUnlessRaises(usage.UsageError, self.parse,
3794                               ["start", "--basedir=here", "anywhere"])
3795         self.failUnlessRaises(usage.UsageError, self.parse,
3796                               ["--node-directory=there",
3797                                "start", "anywhere"])
3798         self.failUnlessRaises(usage.UsageError, self.parse,
3799                               ["--node-directory=there",
3800                                "start", "--basedir=here", "anywhere"])
3801