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