]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/test/test_cli.py
Merge branch 'pr138': fix long paths on windows
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / test / test_cli.py
1
2 import os.path
3 from twisted.trial import unittest
4 from cStringIO import StringIO
5 import urllib, re, sys
6 import simplejson
7
8 from mock import patch, Mock, call
9
10 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     def test_ticket_2027(self):
2513         # This test ensures that tahoe will copy a file from the grid to
2514         # a local directory without a specified file name.
2515         # https://tahoe-lafs.org/trac/tahoe-lafs/ticket/2027
2516         self.basedir = "cli/Cp/cp_verbose"
2517         self.set_up_grid()
2518
2519         # Write a test file, which we'll copy to the grid.
2520         test1_path = os.path.join(self.basedir, "test1")
2521         fileutil.write(test1_path, "test1")
2522
2523         d = self.do_cli("create-alias", "tahoe")
2524         d.addCallback(lambda ign:
2525             self.do_cli("cp", test1_path, "tahoe:"))
2526         d.addCallback(lambda ign:
2527             self.do_cli("cp", "tahoe:test1", self.basedir))
2528         def _check(res):
2529             (rc, out, err) = res
2530             self.failUnlessIn("Success: file copied", out, str(res))
2531         return d
2532
2533
2534 class Backup(GridTestMixin, CLITestMixin, StallMixin, unittest.TestCase):
2535
2536     def writeto(self, path, data):
2537         full_path = os.path.join(self.basedir, "home", path)
2538         fileutil.make_dirs(os.path.dirname(full_path))
2539         fileutil.write(full_path, data)
2540
2541     def count_output(self, out):
2542         mo = re.search(r"(\d)+ files uploaded \((\d+) reused\), "
2543                         "(\d)+ files skipped, "
2544                         "(\d+) directories created \((\d+) reused\), "
2545                         "(\d+) directories skipped", out)
2546         return [int(s) for s in mo.groups()]
2547
2548     def count_output2(self, out):
2549         mo = re.search(r"(\d)+ files checked, (\d+) directories checked", out)
2550         return [int(s) for s in mo.groups()]
2551
2552     def test_backup(self):
2553         self.basedir = "cli/Backup/backup"
2554         self.set_up_grid()
2555
2556         # is the backupdb available? If so, we test that a second backup does
2557         # not create new directories.
2558         hush = StringIO()
2559         bdb = backupdb.get_backupdb(os.path.join(self.basedir, "dbtest"),
2560                                     hush)
2561         self.failUnless(bdb)
2562
2563         # create a small local directory with a couple of files
2564         source = os.path.join(self.basedir, "home")
2565         fileutil.make_dirs(os.path.join(source, "empty"))
2566         self.writeto("parent/subdir/foo.txt", "foo")
2567         self.writeto("parent/subdir/bar.txt", "bar\n" * 1000)
2568         self.writeto("parent/blah.txt", "blah")
2569
2570         def do_backup(verbose=False):
2571             cmd = ["backup"]
2572             if verbose:
2573                 cmd.append("--verbose")
2574             cmd.append(source)
2575             cmd.append("tahoe:backups")
2576             return self.do_cli(*cmd)
2577
2578         d = self.do_cli("create-alias", "tahoe")
2579
2580         d.addCallback(lambda res: do_backup())
2581         def _check0((rc, out, err)):
2582             self.failUnlessReallyEqual(err, "")
2583             self.failUnlessReallyEqual(rc, 0)
2584             fu, fr, fs, dc, dr, ds = self.count_output(out)
2585             # foo.txt, bar.txt, blah.txt
2586             self.failUnlessReallyEqual(fu, 3)
2587             self.failUnlessReallyEqual(fr, 0)
2588             self.failUnlessReallyEqual(fs, 0)
2589             # empty, home, home/parent, home/parent/subdir
2590             self.failUnlessReallyEqual(dc, 4)
2591             self.failUnlessReallyEqual(dr, 0)
2592             self.failUnlessReallyEqual(ds, 0)
2593         d.addCallback(_check0)
2594
2595         d.addCallback(lambda res: self.do_cli("ls", "--uri", "tahoe:backups"))
2596         def _check1((rc, out, err)):
2597             self.failUnlessReallyEqual(err, "")
2598             self.failUnlessReallyEqual(rc, 0)
2599             lines = out.split("\n")
2600             children = dict([line.split() for line in lines if line])
2601             latest_uri = children["Latest"]
2602             self.failUnless(latest_uri.startswith("URI:DIR2-CHK:"), latest_uri)
2603             childnames = children.keys()
2604             self.failUnlessReallyEqual(sorted(childnames), ["Archives", "Latest"])
2605         d.addCallback(_check1)
2606         d.addCallback(lambda res: self.do_cli("ls", "tahoe:backups/Latest"))
2607         def _check2((rc, out, err)):
2608             self.failUnlessReallyEqual(err, "")
2609             self.failUnlessReallyEqual(rc, 0)
2610             self.failUnlessReallyEqual(sorted(out.split()), ["empty", "parent"])
2611         d.addCallback(_check2)
2612         d.addCallback(lambda res: self.do_cli("ls", "tahoe:backups/Latest/empty"))
2613         def _check2a((rc, out, err)):
2614             self.failUnlessReallyEqual(err, "")
2615             self.failUnlessReallyEqual(rc, 0)
2616             self.failUnlessReallyEqual(out.strip(), "")
2617         d.addCallback(_check2a)
2618         d.addCallback(lambda res: self.do_cli("get", "tahoe:backups/Latest/parent/subdir/foo.txt"))
2619         def _check3((rc, out, err)):
2620             self.failUnlessReallyEqual(err, "")
2621             self.failUnlessReallyEqual(rc, 0)
2622             self.failUnlessReallyEqual(out, "foo")
2623         d.addCallback(_check3)
2624         d.addCallback(lambda res: self.do_cli("ls", "tahoe:backups/Archives"))
2625         def _check4((rc, out, err)):
2626             self.failUnlessReallyEqual(err, "")
2627             self.failUnlessReallyEqual(rc, 0)
2628             self.old_archives = out.split()
2629             self.failUnlessReallyEqual(len(self.old_archives), 1)
2630         d.addCallback(_check4)
2631
2632
2633         d.addCallback(self.stall, 1.1)
2634         d.addCallback(lambda res: do_backup())
2635         def _check4a((rc, out, err)):
2636             # second backup should reuse everything, if the backupdb is
2637             # available
2638             self.failUnlessReallyEqual(err, "")
2639             self.failUnlessReallyEqual(rc, 0)
2640             fu, fr, fs, dc, dr, ds = self.count_output(out)
2641             # foo.txt, bar.txt, blah.txt
2642             self.failUnlessReallyEqual(fu, 0)
2643             self.failUnlessReallyEqual(fr, 3)
2644             self.failUnlessReallyEqual(fs, 0)
2645             # empty, home, home/parent, home/parent/subdir
2646             self.failUnlessReallyEqual(dc, 0)
2647             self.failUnlessReallyEqual(dr, 4)
2648             self.failUnlessReallyEqual(ds, 0)
2649         d.addCallback(_check4a)
2650
2651         # sneak into the backupdb, crank back the "last checked"
2652         # timestamp to force a check on all files
2653         def _reset_last_checked(res):
2654             dbfile = os.path.join(self.get_clientdir(),
2655                                   "private", "backupdb.sqlite")
2656             self.failUnless(os.path.exists(dbfile), dbfile)
2657             bdb = backupdb.get_backupdb(dbfile)
2658             bdb.cursor.execute("UPDATE last_upload SET last_checked=0")
2659             bdb.cursor.execute("UPDATE directories SET last_checked=0")
2660             bdb.connection.commit()
2661
2662         d.addCallback(_reset_last_checked)
2663
2664         d.addCallback(self.stall, 1.1)
2665         d.addCallback(lambda res: do_backup(verbose=True))
2666         def _check4b((rc, out, err)):
2667             # we should check all files, and re-use all of them. None of
2668             # the directories should have been changed, so we should
2669             # re-use all of them too.
2670             self.failUnlessReallyEqual(err, "")
2671             self.failUnlessReallyEqual(rc, 0)
2672             fu, fr, fs, dc, dr, ds = self.count_output(out)
2673             fchecked, dchecked = self.count_output2(out)
2674             self.failUnlessReallyEqual(fchecked, 3)
2675             self.failUnlessReallyEqual(fu, 0)
2676             self.failUnlessReallyEqual(fr, 3)
2677             self.failUnlessReallyEqual(fs, 0)
2678             self.failUnlessReallyEqual(dchecked, 4)
2679             self.failUnlessReallyEqual(dc, 0)
2680             self.failUnlessReallyEqual(dr, 4)
2681             self.failUnlessReallyEqual(ds, 0)
2682         d.addCallback(_check4b)
2683
2684         d.addCallback(lambda res: self.do_cli("ls", "tahoe:backups/Archives"))
2685         def _check5((rc, out, err)):
2686             self.failUnlessReallyEqual(err, "")
2687             self.failUnlessReallyEqual(rc, 0)
2688             self.new_archives = out.split()
2689             self.failUnlessReallyEqual(len(self.new_archives), 3, out)
2690             # the original backup should still be the oldest (i.e. sorts
2691             # alphabetically towards the beginning)
2692             self.failUnlessReallyEqual(sorted(self.new_archives)[0],
2693                                  self.old_archives[0])
2694         d.addCallback(_check5)
2695
2696         d.addCallback(self.stall, 1.1)
2697         def _modify(res):
2698             self.writeto("parent/subdir/foo.txt", "FOOF!")
2699             # and turn a file into a directory
2700             os.unlink(os.path.join(source, "parent/blah.txt"))
2701             os.mkdir(os.path.join(source, "parent/blah.txt"))
2702             self.writeto("parent/blah.txt/surprise file", "surprise")
2703             self.writeto("parent/blah.txt/surprisedir/subfile", "surprise")
2704             # turn a directory into a file
2705             os.rmdir(os.path.join(source, "empty"))
2706             self.writeto("empty", "imagine nothing being here")
2707             return do_backup()
2708         d.addCallback(_modify)
2709         def _check5a((rc, out, err)):
2710             # second backup should reuse bar.txt (if backupdb is available),
2711             # and upload the rest. None of the directories can be reused.
2712             self.failUnlessReallyEqual(err, "")
2713             self.failUnlessReallyEqual(rc, 0)
2714             fu, fr, fs, dc, dr, ds = self.count_output(out)
2715             # new foo.txt, surprise file, subfile, empty
2716             self.failUnlessReallyEqual(fu, 4)
2717             # old bar.txt
2718             self.failUnlessReallyEqual(fr, 1)
2719             self.failUnlessReallyEqual(fs, 0)
2720             # home, parent, subdir, blah.txt, surprisedir
2721             self.failUnlessReallyEqual(dc, 5)
2722             self.failUnlessReallyEqual(dr, 0)
2723             self.failUnlessReallyEqual(ds, 0)
2724         d.addCallback(_check5a)
2725         d.addCallback(lambda res: self.do_cli("ls", "tahoe:backups/Archives"))
2726         def _check6((rc, out, err)):
2727             self.failUnlessReallyEqual(err, "")
2728             self.failUnlessReallyEqual(rc, 0)
2729             self.new_archives = out.split()
2730             self.failUnlessReallyEqual(len(self.new_archives), 4)
2731             self.failUnlessReallyEqual(sorted(self.new_archives)[0],
2732                                  self.old_archives[0])
2733         d.addCallback(_check6)
2734         d.addCallback(lambda res: self.do_cli("get", "tahoe:backups/Latest/parent/subdir/foo.txt"))
2735         def _check7((rc, out, err)):
2736             self.failUnlessReallyEqual(err, "")
2737             self.failUnlessReallyEqual(rc, 0)
2738             self.failUnlessReallyEqual(out, "FOOF!")
2739             # the old snapshot should not be modified
2740             return self.do_cli("get", "tahoe:backups/Archives/%s/parent/subdir/foo.txt" % self.old_archives[0])
2741         d.addCallback(_check7)
2742         def _check8((rc, out, err)):
2743             self.failUnlessReallyEqual(err, "")
2744             self.failUnlessReallyEqual(rc, 0)
2745             self.failUnlessReallyEqual(out, "foo")
2746         d.addCallback(_check8)
2747
2748         return d
2749
2750     # on our old dapper buildslave, this test takes a long time (usually
2751     # 130s), so we have to bump up the default 120s timeout. The create-alias
2752     # and initial backup alone take 60s, probably because of the handful of
2753     # dirnodes being created (RSA key generation). The backup between check4
2754     # and check4a takes 6s, as does the backup before check4b.
2755     test_backup.timeout = 3000
2756
2757     def _check_filtering(self, filtered, all, included, excluded):
2758         filtered = set(filtered)
2759         all = set(all)
2760         included = set(included)
2761         excluded = set(excluded)
2762         self.failUnlessReallyEqual(filtered, included)
2763         self.failUnlessReallyEqual(all.difference(filtered), excluded)
2764
2765     def test_exclude_options(self):
2766         root_listdir = (u'lib.a', u'_darcs', u'subdir', u'nice_doc.lyx')
2767         subdir_listdir = (u'another_doc.lyx', u'run_snake_run.py', u'CVS', u'.svn', u'_darcs')
2768         basedir = "cli/Backup/exclude_options"
2769         fileutil.make_dirs(basedir)
2770         nodeurl_path = os.path.join(basedir, 'node.url')
2771         fileutil.write(nodeurl_path, 'http://example.net:2357/')
2772         def parse(args): return parse_options(basedir, "backup", args)
2773
2774         # test simple exclude
2775         backup_options = parse(['--exclude', '*lyx', 'from', 'to'])
2776         filtered = list(backup_options.filter_listdir(root_listdir))
2777         self._check_filtering(filtered, root_listdir, (u'lib.a', u'_darcs', u'subdir'),
2778                               (u'nice_doc.lyx',))
2779         # multiple exclude
2780         backup_options = parse(['--exclude', '*lyx', '--exclude', 'lib.?', 'from', 'to'])
2781         filtered = list(backup_options.filter_listdir(root_listdir))
2782         self._check_filtering(filtered, root_listdir, (u'_darcs', u'subdir'),
2783                               (u'nice_doc.lyx', u'lib.a'))
2784         # vcs metadata exclusion
2785         backup_options = parse(['--exclude-vcs', 'from', 'to'])
2786         filtered = list(backup_options.filter_listdir(subdir_listdir))
2787         self._check_filtering(filtered, subdir_listdir, (u'another_doc.lyx', u'run_snake_run.py',),
2788                               (u'CVS', u'.svn', u'_darcs'))
2789         # read exclude patterns from file
2790         exclusion_string = "_darcs\n*py\n.svn"
2791         excl_filepath = os.path.join(basedir, 'exclusion')
2792         fileutil.write(excl_filepath, exclusion_string)
2793         backup_options = parse(['--exclude-from', excl_filepath, 'from', 'to'])
2794         filtered = list(backup_options.filter_listdir(subdir_listdir))
2795         self._check_filtering(filtered, subdir_listdir, (u'another_doc.lyx', u'CVS'),
2796                               (u'.svn', u'_darcs', u'run_snake_run.py'))
2797         # test BackupConfigurationError
2798         self.failUnlessRaises(cli.BackupConfigurationError,
2799                               parse,
2800                               ['--exclude-from', excl_filepath + '.no', 'from', 'to'])
2801
2802         # test that an iterator works too
2803         backup_options = parse(['--exclude', '*lyx', 'from', 'to'])
2804         filtered = list(backup_options.filter_listdir(iter(root_listdir)))
2805         self._check_filtering(filtered, root_listdir, (u'lib.a', u'_darcs', u'subdir'),
2806                               (u'nice_doc.lyx',))
2807
2808     def test_exclude_options_unicode(self):
2809         nice_doc = u"nice_d\u00F8c.lyx"
2810         try:
2811             doc_pattern_arg = u"*d\u00F8c*".encode(get_io_encoding())
2812         except UnicodeEncodeError:
2813             raise unittest.SkipTest("A non-ASCII command argument could not be encoded on this platform.")
2814
2815         root_listdir = (u'lib.a', u'_darcs', u'subdir', nice_doc)
2816         basedir = "cli/Backup/exclude_options_unicode"
2817         fileutil.make_dirs(basedir)
2818         nodeurl_path = os.path.join(basedir, 'node.url')
2819         fileutil.write(nodeurl_path, 'http://example.net:2357/')
2820         def parse(args): return parse_options(basedir, "backup", args)
2821
2822         # test simple exclude
2823         backup_options = parse(['--exclude', doc_pattern_arg, 'from', 'to'])
2824         filtered = list(backup_options.filter_listdir(root_listdir))
2825         self._check_filtering(filtered, root_listdir, (u'lib.a', u'_darcs', u'subdir'),
2826                               (nice_doc,))
2827         # multiple exclude
2828         backup_options = parse(['--exclude', doc_pattern_arg, '--exclude', 'lib.?', 'from', 'to'])
2829         filtered = list(backup_options.filter_listdir(root_listdir))
2830         self._check_filtering(filtered, root_listdir, (u'_darcs', u'subdir'),
2831                              (nice_doc, u'lib.a'))
2832         # read exclude patterns from file
2833         exclusion_string = doc_pattern_arg + "\nlib.?"
2834         excl_filepath = os.path.join(basedir, 'exclusion')
2835         fileutil.write(excl_filepath, exclusion_string)
2836         backup_options = parse(['--exclude-from', excl_filepath, 'from', 'to'])
2837         filtered = list(backup_options.filter_listdir(root_listdir))
2838         self._check_filtering(filtered, root_listdir, (u'_darcs', u'subdir'),
2839                              (nice_doc, u'lib.a'))
2840
2841         # test that an iterator works too
2842         backup_options = parse(['--exclude', doc_pattern_arg, 'from', 'to'])
2843         filtered = list(backup_options.filter_listdir(iter(root_listdir)))
2844         self._check_filtering(filtered, root_listdir, (u'lib.a', u'_darcs', u'subdir'),
2845                               (nice_doc,))
2846
2847     @patch('__builtin__.file')
2848     def test_exclude_from_tilde_expansion(self, mock):
2849         basedir = "cli/Backup/exclude_from_tilde_expansion"
2850         fileutil.make_dirs(basedir)
2851         nodeurl_path = os.path.join(basedir, 'node.url')
2852         fileutil.write(nodeurl_path, 'http://example.net:2357/')
2853         def parse(args): return parse_options(basedir, "backup", args)
2854
2855         # ensure that tilde expansion is performed on exclude-from argument
2856         exclude_file = u'~/.tahoe/excludes.dummy'
2857
2858         mock.return_value = StringIO()
2859         parse(['--exclude-from', unicode_to_argv(exclude_file), 'from', 'to'])
2860         self.failUnlessIn(((abspath_expanduser_unicode(exclude_file),), {}), mock.call_args_list)
2861
2862     def test_ignore_symlinks(self):
2863         if not hasattr(os, 'symlink'):
2864             raise unittest.SkipTest("Symlinks are not supported by Python on this platform.")
2865
2866         self.basedir = os.path.dirname(self.mktemp())
2867         self.set_up_grid()
2868
2869         source = os.path.join(self.basedir, "home")
2870         self.writeto("foo.txt", "foo")
2871         os.symlink(os.path.join(source, "foo.txt"), os.path.join(source, "foo2.txt"))
2872
2873         d = self.do_cli("create-alias", "tahoe")
2874         d.addCallback(lambda res: self.do_cli("backup", "--verbose", source, "tahoe:test"))
2875
2876         def _check((rc, out, err)):
2877             self.failUnlessReallyEqual(rc, 2)
2878             foo2 = os.path.join(source, "foo2.txt")
2879             self.failUnlessIn("WARNING: cannot backup symlink ", err)
2880             self.failUnlessIn(foo2, err)
2881
2882             fu, fr, fs, dc, dr, ds = self.count_output(out)
2883             # foo.txt
2884             self.failUnlessReallyEqual(fu, 1)
2885             self.failUnlessReallyEqual(fr, 0)
2886             # foo2.txt
2887             self.failUnlessReallyEqual(fs, 1)
2888             # home
2889             self.failUnlessReallyEqual(dc, 1)
2890             self.failUnlessReallyEqual(dr, 0)
2891             self.failUnlessReallyEqual(ds, 0)
2892
2893         d.addCallback(_check)
2894         return d
2895
2896     def test_ignore_unreadable_file(self):
2897         self.basedir = os.path.dirname(self.mktemp())
2898         self.set_up_grid()
2899
2900         source = os.path.join(self.basedir, "home")
2901         self.writeto("foo.txt", "foo")
2902         os.chmod(os.path.join(source, "foo.txt"), 0000)
2903
2904         d = self.do_cli("create-alias", "tahoe")
2905         d.addCallback(lambda res: self.do_cli("backup", source, "tahoe:test"))
2906
2907         def _check((rc, out, err)):
2908             self.failUnlessReallyEqual(rc, 2)
2909             self.failUnlessReallyEqual(err, "WARNING: permission denied on file %s\n" % os.path.join(source, "foo.txt"))
2910
2911             fu, fr, fs, dc, dr, ds = self.count_output(out)
2912             self.failUnlessReallyEqual(fu, 0)
2913             self.failUnlessReallyEqual(fr, 0)
2914             # foo.txt
2915             self.failUnlessReallyEqual(fs, 1)
2916             # home
2917             self.failUnlessReallyEqual(dc, 1)
2918             self.failUnlessReallyEqual(dr, 0)
2919             self.failUnlessReallyEqual(ds, 0)
2920         d.addCallback(_check)
2921
2922         # This is necessary for the temp files to be correctly removed
2923         def _cleanup(self):
2924             os.chmod(os.path.join(source, "foo.txt"), 0644)
2925         d.addCallback(_cleanup)
2926         d.addErrback(_cleanup)
2927
2928         return d
2929
2930     def test_ignore_unreadable_directory(self):
2931         self.basedir = os.path.dirname(self.mktemp())
2932         self.set_up_grid()
2933
2934         source = os.path.join(self.basedir, "home")
2935         os.mkdir(source)
2936         os.mkdir(os.path.join(source, "test"))
2937         os.chmod(os.path.join(source, "test"), 0000)
2938
2939         d = self.do_cli("create-alias", "tahoe")
2940         d.addCallback(lambda res: self.do_cli("backup", source, "tahoe:test"))
2941
2942         def _check((rc, out, err)):
2943             self.failUnlessReallyEqual(rc, 2)
2944             self.failUnlessReallyEqual(err, "WARNING: permission denied on directory %s\n" % os.path.join(source, "test"))
2945
2946             fu, fr, fs, dc, dr, ds = self.count_output(out)
2947             self.failUnlessReallyEqual(fu, 0)
2948             self.failUnlessReallyEqual(fr, 0)
2949             self.failUnlessReallyEqual(fs, 0)
2950             # home, test
2951             self.failUnlessReallyEqual(dc, 2)
2952             self.failUnlessReallyEqual(dr, 0)
2953             # test
2954             self.failUnlessReallyEqual(ds, 1)
2955         d.addCallback(_check)
2956
2957         # This is necessary for the temp files to be correctly removed
2958         def _cleanup(self):
2959             os.chmod(os.path.join(source, "test"), 0655)
2960         d.addCallback(_cleanup)
2961         d.addErrback(_cleanup)
2962         return d
2963
2964     def test_backup_without_alias(self):
2965         # 'tahoe backup' should output a sensible error message when invoked
2966         # without an alias instead of a stack trace.
2967         self.basedir = os.path.dirname(self.mktemp())
2968         self.set_up_grid()
2969         source = os.path.join(self.basedir, "file1")
2970         d = self.do_cli('backup', source, source)
2971         def _check((rc, out, err)):
2972             self.failUnlessReallyEqual(rc, 1)
2973             self.failUnlessIn("error:", err)
2974             self.failUnlessReallyEqual(out, "")
2975         d.addCallback(_check)
2976         return d
2977
2978     def test_backup_with_nonexistent_alias(self):
2979         # 'tahoe backup' should output a sensible error message when invoked
2980         # with a nonexistent alias.
2981         self.basedir = os.path.dirname(self.mktemp())
2982         self.set_up_grid()
2983         source = os.path.join(self.basedir, "file1")
2984         d = self.do_cli("backup", source, "nonexistent:" + source)
2985         def _check((rc, out, err)):
2986             self.failUnlessReallyEqual(rc, 1)
2987             self.failUnlessIn("error:", err)
2988             self.failUnlessIn("nonexistent", err)
2989             self.failUnlessReallyEqual(out, "")
2990         d.addCallback(_check)
2991         return d
2992
2993
2994 class Check(GridTestMixin, CLITestMixin, unittest.TestCase):
2995
2996     def test_check(self):
2997         self.basedir = "cli/Check/check"
2998         self.set_up_grid()
2999         c0 = self.g.clients[0]
3000         DATA = "data" * 100
3001         DATA_uploadable = MutableData(DATA)
3002         d = c0.create_mutable_file(DATA_uploadable)
3003         def _stash_uri(n):
3004             self.uri = n.get_uri()
3005         d.addCallback(_stash_uri)
3006
3007         d.addCallback(lambda ign: self.do_cli("check", self.uri))
3008         def _check1((rc, out, err)):
3009             self.failUnlessReallyEqual(err, "")
3010             self.failUnlessReallyEqual(rc, 0)
3011             lines = out.splitlines()
3012             self.failUnless("Summary: Healthy" in lines, out)
3013             self.failUnless(" good-shares: 10 (encoding is 3-of-10)" in lines, out)
3014         d.addCallback(_check1)
3015
3016         d.addCallback(lambda ign: self.do_cli("check", "--raw", self.uri))
3017         def _check2((rc, out, err)):
3018             self.failUnlessReallyEqual(err, "")
3019             self.failUnlessReallyEqual(rc, 0)
3020             data = simplejson.loads(out)
3021             self.failUnlessReallyEqual(to_str(data["summary"]), "Healthy")
3022             self.failUnlessReallyEqual(data["results"]["healthy"], True)
3023         d.addCallback(_check2)
3024
3025         d.addCallback(lambda ign: c0.upload(upload.Data("literal", convergence="")))
3026         def _stash_lit_uri(n):
3027             self.lit_uri = n.get_uri()
3028         d.addCallback(_stash_lit_uri)
3029
3030         d.addCallback(lambda ign: self.do_cli("check", self.lit_uri))
3031         def _check_lit((rc, out, err)):
3032             self.failUnlessReallyEqual(err, "")
3033             self.failUnlessReallyEqual(rc, 0)
3034             lines = out.splitlines()
3035             self.failUnless("Summary: Healthy (LIT)" in lines, out)
3036         d.addCallback(_check_lit)
3037
3038         d.addCallback(lambda ign: self.do_cli("check", "--raw", self.lit_uri))
3039         def _check_lit_raw((rc, out, err)):
3040             self.failUnlessReallyEqual(err, "")
3041             self.failUnlessReallyEqual(rc, 0)
3042             data = simplejson.loads(out)
3043             self.failUnlessReallyEqual(data["results"]["healthy"], True)
3044         d.addCallback(_check_lit_raw)
3045
3046         d.addCallback(lambda ign: c0.create_immutable_dirnode({}, convergence=""))
3047         def _stash_lit_dir_uri(n):
3048             self.lit_dir_uri = n.get_uri()
3049         d.addCallback(_stash_lit_dir_uri)
3050
3051         d.addCallback(lambda ign: self.do_cli("check", self.lit_dir_uri))
3052         d.addCallback(_check_lit)
3053
3054         d.addCallback(lambda ign: self.do_cli("check", "--raw", self.lit_uri))
3055         d.addCallback(_check_lit_raw)
3056
3057         def _clobber_shares(ignored):
3058             # delete one, corrupt a second
3059             shares = self.find_uri_shares(self.uri)
3060             self.failUnlessReallyEqual(len(shares), 10)
3061             os.unlink(shares[0][2])
3062             cso = debug.CorruptShareOptions()
3063             cso.stdout = StringIO()
3064             cso.parseOptions([shares[1][2]])
3065             storage_index = uri.from_string(self.uri).get_storage_index()
3066             self._corrupt_share_line = "  server %s, SI %s, shnum %d" % \
3067                                        (base32.b2a(shares[1][1]),
3068                                         base32.b2a(storage_index),
3069                                         shares[1][0])
3070             debug.corrupt_share(cso)
3071         d.addCallback(_clobber_shares)
3072
3073         d.addCallback(lambda ign: self.do_cli("check", "--verify", self.uri))
3074         def _check3((rc, out, err)):
3075             self.failUnlessReallyEqual(err, "")
3076             self.failUnlessReallyEqual(rc, 0)
3077             lines = out.splitlines()
3078             summary = [l for l in lines if l.startswith("Summary")][0]
3079             self.failUnless("Summary: Unhealthy: 8 shares (enc 3-of-10)"
3080                             in summary, summary)
3081             self.failUnless(" good-shares: 8 (encoding is 3-of-10)" in lines, out)
3082             self.failUnless(" corrupt shares:" in lines, out)
3083             self.failUnless(self._corrupt_share_line in lines, out)
3084         d.addCallback(_check3)
3085
3086         d.addCallback(lambda ign: self.do_cli("check", "--verify", "--raw", self.uri))
3087         def _check3_raw((rc, out, err)):
3088             self.failUnlessReallyEqual(err, "")
3089             self.failUnlessReallyEqual(rc, 0)
3090             data = simplejson.loads(out)
3091             self.failUnlessReallyEqual(data["results"]["healthy"], False)
3092             self.failUnlessIn("Unhealthy: 8 shares (enc 3-of-10)", data["summary"])
3093             self.failUnlessReallyEqual(data["results"]["count-shares-good"], 8)
3094             self.failUnlessReallyEqual(data["results"]["count-corrupt-shares"], 1)
3095             self.failUnlessIn("list-corrupt-shares", data["results"])
3096         d.addCallback(_check3_raw)
3097
3098         d.addCallback(lambda ign:
3099                       self.do_cli("check", "--verify", "--repair", self.uri))
3100         def _check4((rc, out, err)):
3101             self.failUnlessReallyEqual(err, "")
3102             self.failUnlessReallyEqual(rc, 0)
3103             lines = out.splitlines()
3104             self.failUnless("Summary: not healthy" in lines, out)
3105             self.failUnless(" good-shares: 8 (encoding is 3-of-10)" in lines, out)
3106             self.failUnless(" corrupt shares:" in lines, out)
3107             self.failUnless(self._corrupt_share_line in lines, out)
3108             self.failUnless(" repair successful" in lines, out)
3109         d.addCallback(_check4)
3110
3111         d.addCallback(lambda ign:
3112                       self.do_cli("check", "--verify", "--repair", self.uri))
3113         def _check5((rc, out, err)):
3114             self.failUnlessReallyEqual(err, "")
3115             self.failUnlessReallyEqual(rc, 0)
3116             lines = out.splitlines()
3117             self.failUnless("Summary: healthy" in lines, out)
3118             self.failUnless(" good-shares: 10 (encoding is 3-of-10)" in lines, out)
3119             self.failIf(" corrupt shares:" in lines, out)
3120         d.addCallback(_check5)
3121
3122         return d
3123
3124     def test_deep_check(self):
3125         self.basedir = "cli/Check/deep_check"
3126         self.set_up_grid()
3127         c0 = self.g.clients[0]
3128         self.uris = {}
3129         self.fileurls = {}
3130         DATA = "data" * 100
3131         quoted_good = quote_output(u"g\u00F6\u00F6d")
3132
3133         d = c0.create_dirnode()
3134         def _stash_root_and_create_file(n):
3135             self.rootnode = n
3136             self.rooturi = n.get_uri()
3137             return n.add_file(u"g\u00F6\u00F6d", upload.Data(DATA, convergence=""))
3138         d.addCallback(_stash_root_and_create_file)
3139         def _stash_uri(fn, which):
3140             self.uris[which] = fn.get_uri()
3141             return fn
3142         d.addCallback(_stash_uri, u"g\u00F6\u00F6d")
3143         d.addCallback(lambda ign:
3144                       self.rootnode.add_file(u"small",
3145                                            upload.Data("literal",
3146                                                         convergence="")))
3147         d.addCallback(_stash_uri, "small")
3148         d.addCallback(lambda ign:
3149             c0.create_mutable_file(MutableData(DATA+"1")))
3150         d.addCallback(lambda fn: self.rootnode.set_node(u"mutable", fn))
3151         d.addCallback(_stash_uri, "mutable")
3152
3153         d.addCallback(lambda ign: self.do_cli("deep-check", self.rooturi))
3154         def _check1((rc, out, err)):
3155             self.failUnlessReallyEqual(err, "")
3156             self.failUnlessReallyEqual(rc, 0)
3157             lines = out.splitlines()
3158             self.failUnless("done: 4 objects checked, 4 healthy, 0 unhealthy"
3159                             in lines, out)
3160         d.addCallback(_check1)
3161
3162         # root
3163         # root/g\u00F6\u00F6d
3164         # root/small
3165         # root/mutable
3166
3167         d.addCallback(lambda ign: self.do_cli("deep-check", "--verbose",
3168                                               self.rooturi))
3169         def _check2((rc, out, err)):
3170             self.failUnlessReallyEqual(err, "")
3171             self.failUnlessReallyEqual(rc, 0)
3172             lines = out.splitlines()
3173             self.failUnless("'<root>': Healthy" in lines, out)
3174             self.failUnless("'small': Healthy (LIT)" in lines, out)
3175             self.failUnless((quoted_good + ": Healthy") in lines, out)
3176             self.failUnless("'mutable': Healthy" in lines, out)
3177             self.failUnless("done: 4 objects checked, 4 healthy, 0 unhealthy"
3178                             in lines, out)
3179         d.addCallback(_check2)
3180
3181         d.addCallback(lambda ign: self.do_cli("stats", self.rooturi))
3182         def _check_stats((rc, out, err)):
3183             self.failUnlessReallyEqual(err, "")
3184             self.failUnlessReallyEqual(rc, 0)
3185             lines = out.splitlines()
3186             self.failUnlessIn(" count-immutable-files: 1", lines)
3187             self.failUnlessIn("   count-mutable-files: 1", lines)
3188             self.failUnlessIn("   count-literal-files: 1", lines)
3189             self.failUnlessIn("     count-directories: 1", lines)
3190             self.failUnlessIn("  size-immutable-files: 400", lines)
3191             self.failUnlessIn("Size Histogram:", lines)
3192             self.failUnlessIn("   4-10   : 1    (10 B, 10 B)", lines)
3193             self.failUnlessIn(" 317-1000 : 1    (1000 B, 1000 B)", lines)
3194         d.addCallback(_check_stats)
3195
3196         def _clobber_shares(ignored):
3197             shares = self.find_uri_shares(self.uris[u"g\u00F6\u00F6d"])
3198             self.failUnlessReallyEqual(len(shares), 10)
3199             os.unlink(shares[0][2])
3200
3201             shares = self.find_uri_shares(self.uris["mutable"])
3202             cso = debug.CorruptShareOptions()
3203             cso.stdout = StringIO()
3204             cso.parseOptions([shares[1][2]])
3205             storage_index = uri.from_string(self.uris["mutable"]).get_storage_index()
3206             self._corrupt_share_line = " corrupt: server %s, SI %s, shnum %d" % \
3207                                        (base32.b2a(shares[1][1]),
3208                                         base32.b2a(storage_index),
3209                                         shares[1][0])
3210             debug.corrupt_share(cso)
3211         d.addCallback(_clobber_shares)
3212
3213         # root
3214         # root/g\u00F6\u00F6d  [9 shares]
3215         # root/small
3216         # root/mutable [1 corrupt share]
3217
3218         d.addCallback(lambda ign:
3219                       self.do_cli("deep-check", "--verbose", self.rooturi))
3220         def _check3((rc, out, err)):
3221             self.failUnlessReallyEqual(err, "")
3222             self.failUnlessReallyEqual(rc, 0)
3223             lines = out.splitlines()
3224             self.failUnless("'<root>': Healthy" in lines, out)
3225             self.failUnless("'small': Healthy (LIT)" in lines, out)
3226             self.failUnless("'mutable': Healthy" in lines, out) # needs verifier
3227             self.failUnless((quoted_good + ": Not Healthy: 9 shares (enc 3-of-10)") in lines, out)
3228             self.failIf(self._corrupt_share_line in lines, out)
3229             self.failUnless("done: 4 objects checked, 3 healthy, 1 unhealthy"
3230                             in lines, out)
3231         d.addCallback(_check3)
3232
3233         d.addCallback(lambda ign:
3234                       self.do_cli("deep-check", "--verbose", "--verify",
3235                                   self.rooturi))
3236         def _check4((rc, out, err)):
3237             self.failUnlessReallyEqual(err, "")
3238             self.failUnlessReallyEqual(rc, 0)
3239             lines = out.splitlines()
3240             self.failUnless("'<root>': Healthy" in lines, out)
3241             self.failUnless("'small': Healthy (LIT)" in lines, out)
3242             mutable = [l for l in lines if l.startswith("'mutable'")][0]
3243             self.failUnless(mutable.startswith("'mutable': Unhealthy: 9 shares (enc 3-of-10)"),
3244                             mutable)
3245             self.failUnless(self._corrupt_share_line in lines, out)
3246             self.failUnless((quoted_good + ": Not Healthy: 9 shares (enc 3-of-10)") in lines, out)
3247             self.failUnless("done: 4 objects checked, 2 healthy, 2 unhealthy"
3248                             in lines, out)
3249         d.addCallback(_check4)
3250
3251         d.addCallback(lambda ign:
3252                       self.do_cli("deep-check", "--raw",
3253                                   self.rooturi))
3254         def _check5((rc, out, err)):
3255             self.failUnlessReallyEqual(err, "")
3256             self.failUnlessReallyEqual(rc, 0)
3257             lines = out.splitlines()
3258             units = [simplejson.loads(line) for line in lines]
3259             # root, small, g\u00F6\u00F6d, mutable,  stats
3260             self.failUnlessReallyEqual(len(units), 4+1)
3261         d.addCallback(_check5)
3262
3263         d.addCallback(lambda ign:
3264                       self.do_cli("deep-check",
3265                                   "--verbose", "--verify", "--repair",
3266                                   self.rooturi))
3267         def _check6((rc, out, err)):
3268             self.failUnlessReallyEqual(err, "")
3269             self.failUnlessReallyEqual(rc, 0)
3270             lines = out.splitlines()
3271             self.failUnless("'<root>': healthy" in lines, out)
3272             self.failUnless("'small': healthy" in lines, out)
3273             self.failUnless("'mutable': not healthy" in lines, out)
3274             self.failUnless(self._corrupt_share_line in lines, out)
3275             self.failUnless((quoted_good + ": not healthy") in lines, out)
3276             self.failUnless("done: 4 objects checked" in lines, out)
3277             self.failUnless(" pre-repair: 2 healthy, 2 unhealthy" in lines, out)
3278             self.failUnless(" 2 repairs attempted, 2 successful, 0 failed"
3279                             in lines, out)
3280             self.failUnless(" post-repair: 4 healthy, 0 unhealthy" in lines,out)
3281         d.addCallback(_check6)
3282
3283         # now add a subdir, and a file below that, then make the subdir
3284         # unrecoverable
3285
3286         d.addCallback(lambda ign: self.rootnode.create_subdirectory(u"subdir"))
3287         d.addCallback(_stash_uri, "subdir")
3288         d.addCallback(lambda fn:
3289                       fn.add_file(u"subfile", upload.Data(DATA+"2", "")))
3290         d.addCallback(lambda ign:
3291                       self.delete_shares_numbered(self.uris["subdir"],
3292                                                   range(10)))
3293
3294         # root
3295         # rootg\u00F6\u00F6d/
3296         # root/small
3297         # root/mutable
3298         # root/subdir [unrecoverable: 0 shares]
3299         # root/subfile
3300
3301         d.addCallback(lambda ign: self.do_cli("manifest", self.rooturi))
3302         def _manifest_failed((rc, out, err)):
3303             self.failIfEqual(rc, 0)
3304             self.failUnlessIn("ERROR: UnrecoverableFileError", err)
3305             # the fatal directory should still show up, as the last line
3306             self.failUnlessIn(" subdir\n", out)
3307         d.addCallback(_manifest_failed)
3308
3309         d.addCallback(lambda ign: self.do_cli("deep-check", self.rooturi))
3310         def _deep_check_failed((rc, out, err)):
3311             self.failIfEqual(rc, 0)
3312             self.failUnlessIn("ERROR: UnrecoverableFileError", err)
3313             # we want to make sure that the error indication is the last
3314             # thing that gets emitted
3315             self.failIf("done:" in out, out)
3316         d.addCallback(_deep_check_failed)
3317
3318         # this test is disabled until the deep-repair response to an
3319         # unrepairable directory is fixed. The failure-to-repair should not
3320         # throw an exception, but the failure-to-traverse that follows
3321         # should throw UnrecoverableFileError.
3322
3323         #d.addCallback(lambda ign:
3324         #              self.do_cli("deep-check", "--repair", self.rooturi))
3325         #def _deep_check_repair_failed((rc, out, err)):
3326         #    self.failIfEqual(rc, 0)
3327         #    print err
3328         #    self.failUnlessIn("ERROR: UnrecoverableFileError", err)
3329         #    self.failIf("done:" in out, out)
3330         #d.addCallback(_deep_check_repair_failed)
3331
3332         return d
3333
3334     def test_check_without_alias(self):
3335         # 'tahoe check' should output a sensible error message if it needs to
3336         # find the default alias and can't
3337         self.basedir = "cli/Check/check_without_alias"
3338         self.set_up_grid()
3339         d = self.do_cli("check")
3340         def _check((rc, out, err)):
3341             self.failUnlessReallyEqual(rc, 1)
3342             self.failUnlessIn("error:", err)
3343             self.failUnlessReallyEqual(out, "")
3344         d.addCallback(_check)
3345         d.addCallback(lambda ign: self.do_cli("deep-check"))
3346         d.addCallback(_check)
3347         return d
3348
3349     def test_check_with_nonexistent_alias(self):
3350         # 'tahoe check' should output a sensible error message if it needs to
3351         # find an alias and can't.
3352         self.basedir = "cli/Check/check_with_nonexistent_alias"
3353         self.set_up_grid()
3354         d = self.do_cli("check", "nonexistent:")
3355         def _check((rc, out, err)):
3356             self.failUnlessReallyEqual(rc, 1)
3357             self.failUnlessIn("error:", err)
3358             self.failUnlessIn("nonexistent", err)
3359             self.failUnlessReallyEqual(out, "")
3360         d.addCallback(_check)
3361         return d
3362
3363     def test_check_with_multiple_aliases(self):
3364         self.basedir = "cli/Check/check_with_multiple_aliases"
3365         self.set_up_grid()
3366         self.uriList = []
3367         c0 = self.g.clients[0]
3368         d = c0.create_dirnode()
3369         def _stash_uri(n):
3370             self.uriList.append(n.get_uri()) 
3371         d.addCallback(_stash_uri)
3372         d = c0.create_dirnode()
3373         d.addCallback(_stash_uri)
3374         
3375         d.addCallback(lambda ign: self.do_cli("check", self.uriList[0], self.uriList[1]))
3376         def _check((rc, out, err)):
3377             self.failUnlessReallyEqual(rc, 0)
3378             self.failUnlessReallyEqual(err, "")
3379             #Ensure healthy appears for each uri
3380             self.failUnlessIn("Healthy", out[:len(out)/2])
3381             self.failUnlessIn("Healthy", out[len(out)/2:])
3382         d.addCallback(_check)
3383         
3384         d.addCallback(lambda ign: self.do_cli("check", self.uriList[0], "nonexistent:"))
3385         def _check2((rc, out, err)):
3386             self.failUnlessReallyEqual(rc, 1)
3387             self.failUnlessIn("Healthy", out)
3388             self.failUnlessIn("error:", err)
3389             self.failUnlessIn("nonexistent", err)
3390         d.addCallback(_check2)
3391         
3392         return d
3393
3394
3395 class Errors(GridTestMixin, CLITestMixin, unittest.TestCase):
3396     def test_get(self):
3397         self.basedir = "cli/Errors/get"
3398         self.set_up_grid()
3399         c0 = self.g.clients[0]
3400         self.fileurls = {}
3401         DATA = "data" * 100
3402         d = c0.upload(upload.Data(DATA, convergence=""))
3403         def _stash_bad(ur):
3404             self.uri_1share = ur.get_uri()
3405             self.delete_shares_numbered(ur.get_uri(), range(1,10))
3406         d.addCallback(_stash_bad)
3407
3408         # the download is abandoned as soon as it's clear that we won't get
3409         # enough shares. The one remaining share might be in either the
3410         # COMPLETE or the PENDING state.
3411         in_complete_msg = "ran out of shares: complete=sh0 pending= overdue= unused= need 3"
3412         in_pending_msg = "ran out of shares: complete= pending=Share(sh0-on-fob7vqgd) overdue= unused= need 3"
3413
3414         d.addCallback(lambda ign: self.do_cli("get", self.uri_1share))
3415         def _check1((rc, out, err)):
3416             self.failIfEqual(rc, 0)
3417             self.failUnless("410 Gone" in err, err)
3418             self.failUnlessIn("NotEnoughSharesError: ", err)
3419             self.failUnless(in_complete_msg in err or in_pending_msg in err,
3420                             err)
3421         d.addCallback(_check1)
3422
3423         targetf = os.path.join(self.basedir, "output")
3424         d.addCallback(lambda ign: self.do_cli("get", self.uri_1share, targetf))
3425         def _check2((rc, out, err)):
3426             self.failIfEqual(rc, 0)
3427             self.failUnless("410 Gone" in err, err)
3428             self.failUnlessIn("NotEnoughSharesError: ", err)
3429             self.failUnless(in_complete_msg in err or in_pending_msg in err,
3430                             err)
3431             self.failIf(os.path.exists(targetf))
3432         d.addCallback(_check2)
3433
3434         return d
3435
3436     def test_broken_socket(self):
3437         # When the http connection breaks (such as when node.url is overwritten
3438         # by a confused user), a user friendly error message should be printed.
3439         self.basedir = "cli/Errors/test_broken_socket"
3440         self.set_up_grid()
3441
3442         # Simulate a connection error
3443         def _socket_error(*args, **kwargs):
3444             raise socket_error('test error')
3445         self.patch(allmydata.scripts.common_http.httplib.HTTPConnection,
3446                    "endheaders", _socket_error)
3447
3448         d = self.do_cli("mkdir")
3449         def _check_invalid((rc,stdout,stderr)):
3450             self.failIfEqual(rc, 0)
3451             self.failUnlessIn("Error trying to connect to http://127.0.0.1", stderr)
3452         d.addCallback(_check_invalid)
3453         return d
3454
3455
3456 class Get(GridTestMixin, CLITestMixin, unittest.TestCase):
3457     def test_get_without_alias(self):
3458         # 'tahoe get' should output a useful error message when invoked
3459         # without an explicit alias and when the default 'tahoe' alias
3460         # hasn't been created yet.
3461         self.basedir = "cli/Get/get_without_alias"
3462         self.set_up_grid()
3463         d = self.do_cli('get', 'file')
3464         def _check((rc, out, err)):
3465             self.failUnlessReallyEqual(rc, 1)
3466             self.failUnlessIn("error:", err)
3467             self.failUnlessReallyEqual(out, "")
3468         d.addCallback(_check)
3469         return d
3470
3471     def test_get_with_nonexistent_alias(self):
3472         # 'tahoe get' should output a useful error message when invoked with
3473         # an explicit alias that doesn't exist.
3474         self.basedir = "cli/Get/get_with_nonexistent_alias"
3475         self.set_up_grid()
3476         d = self.do_cli("get", "nonexistent:file")
3477         def _check((rc, out, err)):
3478             self.failUnlessReallyEqual(rc, 1)
3479             self.failUnlessIn("error:", err)
3480             self.failUnlessIn("nonexistent", err)
3481             self.failUnlessReallyEqual(out, "")
3482         d.addCallback(_check)
3483         return d
3484
3485
3486 class Manifest(GridTestMixin, CLITestMixin, unittest.TestCase):
3487     def test_manifest_without_alias(self):
3488         # 'tahoe manifest' should output a useful error message when invoked
3489         # without an explicit alias when the default 'tahoe' alias is
3490         # missing.
3491         self.basedir = "cli/Manifest/manifest_without_alias"
3492         self.set_up_grid()
3493         d = self.do_cli("manifest")
3494         def _check((rc, out, err)):
3495             self.failUnlessReallyEqual(rc, 1)
3496             self.failUnlessIn("error:", err)
3497             self.failUnlessReallyEqual(out, "")
3498         d.addCallback(_check)
3499         return d
3500
3501     def test_manifest_with_nonexistent_alias(self):
3502         # 'tahoe manifest' should output a useful error message when invoked
3503         # with an explicit alias that doesn't exist.
3504         self.basedir = "cli/Manifest/manifest_with_nonexistent_alias"
3505         self.set_up_grid()
3506         d = self.do_cli("manifest", "nonexistent:")
3507         def _check((rc, out, err)):
3508             self.failUnlessReallyEqual(rc, 1)
3509             self.failUnlessIn("error:", err)
3510             self.failUnlessIn("nonexistent", err)
3511             self.failUnlessReallyEqual(out, "")
3512         d.addCallback(_check)
3513         return d
3514
3515
3516 class Mkdir(GridTestMixin, CLITestMixin, unittest.TestCase):
3517     def test_mkdir(self):
3518         self.basedir = os.path.dirname(self.mktemp())
3519         self.set_up_grid()
3520
3521         d = self.do_cli("create-alias", "tahoe")
3522         d.addCallback(lambda res: self.do_cli("mkdir", "test"))
3523         def _check((rc, out, err)):
3524             self.failUnlessReallyEqual(rc, 0)
3525             self.failUnlessReallyEqual(err, "")
3526             self.failUnlessIn("URI:", out)
3527         d.addCallback(_check)
3528
3529         return d
3530
3531     def test_mkdir_mutable_type(self):
3532         self.basedir = os.path.dirname(self.mktemp())
3533         self.set_up_grid()
3534         d = self.do_cli("create-alias", "tahoe")
3535         def _check((rc, out, err), st):
3536             self.failUnlessReallyEqual(rc, 0)
3537             self.failUnlessReallyEqual(err, "")
3538             self.failUnlessIn(st, out)
3539             return out
3540         def _mkdir(ign, mutable_type, uri_prefix, dirname):
3541             d2 = self.do_cli("mkdir", "--format="+mutable_type, dirname)
3542             d2.addCallback(_check, uri_prefix)
3543             def _stash_filecap(cap):
3544                 u = uri.from_string(cap)
3545                 fn_uri = u.get_filenode_cap()
3546                 self._filecap = fn_uri.to_string()
3547             d2.addCallback(_stash_filecap)
3548             d2.addCallback(lambda ign: self.do_cli("ls", "--json", dirname))
3549             d2.addCallback(_check, uri_prefix)
3550             d2.addCallback(lambda ign: self.do_cli("ls", "--json", self._filecap))
3551             d2.addCallback(_check, '"format": "%s"' % (mutable_type.upper(),))
3552             return d2
3553
3554         d.addCallback(_mkdir, "sdmf", "URI:DIR2", "tahoe:foo")
3555         d.addCallback(_mkdir, "SDMF", "URI:DIR2", "tahoe:foo2")
3556         d.addCallback(_mkdir, "mdmf", "URI:DIR2-MDMF", "tahoe:bar")
3557         d.addCallback(_mkdir, "MDMF", "URI:DIR2-MDMF", "tahoe:bar2")
3558         return d
3559
3560     def test_mkdir_mutable_type_unlinked(self):
3561         self.basedir = os.path.dirname(self.mktemp())
3562         self.set_up_grid()
3563         d = self.do_cli("mkdir", "--format=SDMF")
3564         def _check((rc, out, err), st):
3565             self.failUnlessReallyEqual(rc, 0)
3566             self.failUnlessReallyEqual(err, "")
3567             self.failUnlessIn(st, out)
3568             return out
3569         d.addCallback(_check, "URI:DIR2")
3570         def _stash_dircap(cap):
3571             self._dircap = cap
3572             # Now we're going to feed the cap into uri.from_string...
3573             u = uri.from_string(cap)
3574             # ...grab the underlying filenode uri.
3575             fn_uri = u.get_filenode_cap()
3576             # ...and stash that.
3577             self._filecap = fn_uri.to_string()
3578         d.addCallback(_stash_dircap)
3579         d.addCallback(lambda res: self.do_cli("ls", "--json",
3580                                               self._filecap))
3581         d.addCallback(_check, '"format": "SDMF"')
3582         d.addCallback(lambda res: self.do_cli("mkdir", "--format=MDMF"))
3583         d.addCallback(_check, "URI:DIR2-MDMF")
3584         d.addCallback(_stash_dircap)
3585         d.addCallback(lambda res: self.do_cli("ls", "--json",
3586                                               self._filecap))
3587         d.addCallback(_check, '"format": "MDMF"')
3588         return d
3589
3590     def test_mkdir_bad_mutable_type(self):
3591         o = cli.MakeDirectoryOptions()
3592         self.failUnlessRaises(usage.UsageError,
3593                               o.parseOptions,
3594                               ["--format=LDMF"])
3595
3596     def test_mkdir_unicode(self):
3597         self.basedir = os.path.dirname(self.mktemp())
3598         self.set_up_grid()
3599
3600         try:
3601             motorhead_arg = u"tahoe:Mot\u00F6rhead".encode(get_io_encoding())
3602         except UnicodeEncodeError:
3603             raise unittest.SkipTest("A non-ASCII command argument could not be encoded on this platform.")
3604
3605         d = self.do_cli("create-alias", "tahoe")
3606         d.addCallback(lambda res: self.do_cli("mkdir", motorhead_arg))
3607         def _check((rc, out, err)):
3608             self.failUnlessReallyEqual(rc, 0)
3609             self.failUnlessReallyEqual(err, "")
3610             self.failUnlessIn("URI:", out)
3611         d.addCallback(_check)
3612
3613         return d
3614
3615     def test_mkdir_with_nonexistent_alias(self):
3616         # when invoked with an alias that doesn't exist, 'tahoe mkdir' should
3617         # output a sensible error message rather than a stack trace.
3618         self.basedir = "cli/Mkdir/mkdir_with_nonexistent_alias"
3619         self.set_up_grid()
3620         d = self.do_cli("mkdir", "havasu:")
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         return d
3627
3628
3629 class Unlink(GridTestMixin, CLITestMixin, unittest.TestCase):
3630     command = "unlink"
3631
3632     def _create_test_file(self):
3633         data = "puppies" * 1000
3634         path = os.path.join(self.basedir, "datafile")
3635         fileutil.write(path, data)
3636         self.datafile = path
3637
3638     def test_unlink_without_alias(self):
3639         # 'tahoe unlink' should behave sensibly when invoked without an explicit
3640         # alias before the default 'tahoe' alias has been created.
3641         self.basedir = "cli/Unlink/%s_without_alias" % (self.command,)
3642         self.set_up_grid()
3643         d = self.do_cli(self.command, "afile")
3644         def _check((rc, out, err)):
3645             self.failUnlessReallyEqual(rc, 1)
3646             self.failUnlessIn("error:", err)
3647             self.failUnlessReallyEqual(out, "")
3648         d.addCallback(_check)
3649
3650         d.addCallback(lambda ign: self.do_cli(self.command, "afile"))
3651         d.addCallback(_check)
3652         return d
3653
3654     def test_unlink_with_nonexistent_alias(self):
3655         # 'tahoe unlink' should behave sensibly when invoked with an explicit
3656         # alias that doesn't exist.
3657         self.basedir = "cli/Unlink/%s_with_nonexistent_alias" % (self.command,)
3658         self.set_up_grid()
3659         d = self.do_cli(self.command, "nonexistent:afile")
3660         def _check((rc, out, err)):
3661             self.failUnlessReallyEqual(rc, 1)
3662             self.failUnlessIn("error:", err)
3663             self.failUnlessIn("nonexistent", err)
3664             self.failUnlessReallyEqual(out, "")
3665         d.addCallback(_check)
3666
3667         d.addCallback(lambda ign: self.do_cli(self.command, "nonexistent:afile"))
3668         d.addCallback(_check)
3669         return d
3670
3671     def test_unlink_without_path(self):
3672         # 'tahoe unlink' should give a sensible error message when invoked without a path.
3673         self.basedir = "cli/Unlink/%s_without_path" % (self.command,)
3674         self.set_up_grid()
3675         self._create_test_file()
3676         d = self.do_cli("create-alias", "tahoe")
3677         d.addCallback(lambda ign: self.do_cli("put", self.datafile, "tahoe:test"))
3678         def _do_unlink((rc, out, err)):
3679             self.failUnlessReallyEqual(rc, 0)
3680             self.failUnless(out.startswith("URI:"), out)
3681             return self.do_cli(self.command, out.strip('\n'))
3682         d.addCallback(_do_unlink)
3683
3684         def _check((rc, out, err)):
3685             self.failUnlessReallyEqual(rc, 1)
3686             self.failUnlessIn("'tahoe %s'" % (self.command,), err)
3687             self.failUnlessIn("path must be given", err)
3688             self.failUnlessReallyEqual(out, "")
3689         d.addCallback(_check)
3690         return d
3691
3692
3693 class Rm(Unlink):
3694     """Test that 'tahoe rm' behaves in the same way as 'tahoe unlink'."""
3695     command = "rm"
3696
3697
3698 class Stats(GridTestMixin, CLITestMixin, unittest.TestCase):
3699     def test_empty_directory(self):
3700         self.basedir = "cli/Stats/empty_directory"
3701         self.set_up_grid()
3702         c0 = self.g.clients[0]
3703         self.fileurls = {}
3704         d = c0.create_dirnode()
3705         def _stash_root(n):
3706             self.rootnode = n
3707             self.rooturi = n.get_uri()
3708         d.addCallback(_stash_root)
3709
3710         # make sure we can get stats on an empty directory too
3711         d.addCallback(lambda ign: self.do_cli("stats", self.rooturi))
3712         def _check_stats((rc, out, err)):
3713             self.failUnlessReallyEqual(err, "")
3714             self.failUnlessReallyEqual(rc, 0)
3715             lines = out.splitlines()
3716             self.failUnlessIn(" count-immutable-files: 0", lines)
3717             self.failUnlessIn("   count-mutable-files: 0", lines)
3718             self.failUnlessIn("   count-literal-files: 0", lines)
3719             self.failUnlessIn("     count-directories: 1", lines)
3720             self.failUnlessIn("  size-immutable-files: 0", lines)
3721             self.failIfIn("Size Histogram:", lines)
3722         d.addCallback(_check_stats)
3723
3724         return d
3725
3726     def test_stats_without_alias(self):
3727         # when invoked with no explicit alias and before the default 'tahoe'
3728         # alias is created, 'tahoe stats' should output an informative error
3729         # message, not a stack trace.
3730         self.basedir = "cli/Stats/stats_without_alias"
3731         self.set_up_grid()
3732         d = self.do_cli("stats")
3733         def _check((rc, out, err)):
3734             self.failUnlessReallyEqual(rc, 1)
3735             self.failUnlessIn("error:", err)
3736             self.failUnlessReallyEqual(out, "")
3737         d.addCallback(_check)
3738         return d
3739
3740     def test_stats_with_nonexistent_alias(self):
3741         # when invoked with an explicit alias that doesn't exist,
3742         # 'tahoe stats' should output a useful error message.
3743         self.basedir = "cli/Stats/stats_with_nonexistent_alias"
3744         self.set_up_grid()
3745         d = self.do_cli("stats", "havasu:")
3746         def _check((rc, out, err)):
3747             self.failUnlessReallyEqual(rc, 1)
3748             self.failUnlessIn("error:", err)
3749             self.failUnlessReallyEqual(out, "")
3750         d.addCallback(_check)
3751         return d
3752
3753
3754 class Webopen(GridTestMixin, CLITestMixin, unittest.TestCase):
3755     def test_webopen_with_nonexistent_alias(self):
3756         # when invoked with an alias that doesn't exist, 'tahoe webopen'
3757         # should output an informative error message instead of a stack
3758         # trace.
3759         self.basedir = "cli/Webopen/webopen_with_nonexistent_alias"
3760         self.set_up_grid()
3761         d = self.do_cli("webopen", "fake:")
3762         def _check((rc, out, err)):
3763             self.failUnlessReallyEqual(rc, 1)
3764             self.failUnlessIn("error:", err)
3765             self.failUnlessReallyEqual(out, "")
3766         d.addCallback(_check)
3767         return d
3768
3769     def test_webopen(self):
3770         # TODO: replace with @patch that supports Deferreds.
3771         import webbrowser
3772         def call_webbrowser_open(url):
3773             self.failUnlessIn(self.alias_uri.replace(':', '%3A'), url)
3774             self.webbrowser_open_called = True
3775         def _cleanup(res):
3776             webbrowser.open = self.old_webbrowser_open
3777             return res
3778
3779         self.old_webbrowser_open = webbrowser.open
3780         try:
3781             webbrowser.open = call_webbrowser_open
3782
3783             self.basedir = "cli/Webopen/webopen"
3784             self.set_up_grid()
3785             d = self.do_cli("create-alias", "alias:")
3786             def _check_alias((rc, out, err)):
3787                 self.failUnlessReallyEqual(rc, 0, repr((rc, out, err)))
3788                 self.failUnlessIn("Alias 'alias' created", out)
3789                 self.failUnlessReallyEqual(err, "")
3790                 self.alias_uri = get_aliases(self.get_clientdir())["alias"]
3791             d.addCallback(_check_alias)
3792             d.addCallback(lambda res: self.do_cli("webopen", "alias:"))
3793             def _check_webopen((rc, out, err)):
3794                 self.failUnlessReallyEqual(rc, 0, repr((rc, out, err)))
3795                 self.failUnlessReallyEqual(out, "")
3796                 self.failUnlessReallyEqual(err, "")
3797                 self.failUnless(self.webbrowser_open_called)
3798             d.addCallback(_check_webopen)
3799             d.addBoth(_cleanup)
3800         except:
3801             _cleanup(None)
3802             raise
3803         return d
3804
3805 class Options(ReallyEqualMixin, unittest.TestCase):
3806     # this test case only looks at argument-processing and simple stuff.
3807
3808     def parse(self, args, stdout=None):
3809         o = runner.Options()
3810         if stdout is not None:
3811             o.stdout = stdout
3812         o.parseOptions(args)
3813         while hasattr(o, "subOptions"):
3814             o = o.subOptions
3815         return o
3816
3817     def test_list(self):
3818         fileutil.rm_dir("cli/test_options")
3819         fileutil.make_dirs("cli/test_options")
3820         fileutil.make_dirs("cli/test_options/private")
3821         fileutil.write("cli/test_options/node.url", "http://localhost:8080/\n")
3822         filenode_uri = uri.WriteableSSKFileURI(writekey="\x00"*16,
3823                                                fingerprint="\x00"*32)
3824         private_uri = uri.DirectoryURI(filenode_uri).to_string()
3825         fileutil.write("cli/test_options/private/root_dir.cap", private_uri + "\n")
3826         def parse2(args): return parse_options("cli/test_options", "ls", args)
3827         o = parse2([])
3828         self.failUnlessEqual(o['node-url'], "http://localhost:8080/")
3829         self.failUnlessEqual(o.aliases[DEFAULT_ALIAS], private_uri)
3830         self.failUnlessEqual(o.where, u"")
3831
3832         o = parse2(["--node-url", "http://example.org:8111/"])
3833         self.failUnlessEqual(o['node-url'], "http://example.org:8111/")
3834         self.failUnlessEqual(o.aliases[DEFAULT_ALIAS], private_uri)
3835         self.failUnlessEqual(o.where, u"")
3836
3837         o = parse2(["--dir-cap", "root"])
3838         self.failUnlessEqual(o['node-url'], "http://localhost:8080/")
3839         self.failUnlessEqual(o.aliases[DEFAULT_ALIAS], "root")
3840         self.failUnlessEqual(o.where, u"")
3841
3842         other_filenode_uri = uri.WriteableSSKFileURI(writekey="\x11"*16,
3843                                                      fingerprint="\x11"*32)
3844         other_uri = uri.DirectoryURI(other_filenode_uri).to_string()
3845         o = parse2(["--dir-cap", other_uri])
3846         self.failUnlessEqual(o['node-url'], "http://localhost:8080/")
3847         self.failUnlessEqual(o.aliases[DEFAULT_ALIAS], other_uri)
3848         self.failUnlessEqual(o.where, u"")
3849
3850         o = parse2(["--dir-cap", other_uri, "subdir"])
3851         self.failUnlessEqual(o['node-url'], "http://localhost:8080/")
3852         self.failUnlessEqual(o.aliases[DEFAULT_ALIAS], other_uri)
3853         self.failUnlessEqual(o.where, u"subdir")
3854
3855         self.failUnlessRaises(usage.UsageError, parse2,
3856                               ["--node-url", "NOT-A-URL"])
3857
3858         o = parse2(["--node-url", "http://localhost:8080"])
3859         self.failUnlessEqual(o["node-url"], "http://localhost:8080/")
3860
3861         o = parse2(["--node-url", "https://localhost/"])
3862         self.failUnlessEqual(o["node-url"], "https://localhost/")
3863
3864     def test_version(self):
3865         # "tahoe --version" dumps text to stdout and exits
3866         stdout = StringIO()
3867         self.failUnlessRaises(SystemExit, self.parse, ["--version"], stdout)
3868         self.failUnlessIn(allmydata.__appname__ + ":", stdout.getvalue())
3869         # but "tahoe SUBCOMMAND --version" should be rejected
3870         self.failUnlessRaises(usage.UsageError, self.parse,
3871                               ["start", "--version"])
3872         self.failUnlessRaises(usage.UsageError, self.parse,
3873                               ["start", "--version-and-path"])
3874
3875     def test_quiet(self):
3876         # accepted as an overall option, but not on subcommands
3877         o = self.parse(["--quiet", "start"])
3878         self.failUnless(o.parent["quiet"])
3879         self.failUnlessRaises(usage.UsageError, self.parse,
3880                               ["start", "--quiet"])
3881
3882     def test_basedir(self):
3883         # accept a --node-directory option before the verb, or a --basedir
3884         # option after, or a basedir argument after, but none in the wrong
3885         # place, and not more than one of the three.
3886         o = self.parse(["start"])
3887         self.failUnlessReallyEqual(o["basedir"], os.path.join(fileutil.abspath_expanduser_unicode(u"~"),
3888                                                               u".tahoe"))
3889         o = self.parse(["start", "here"])
3890         self.failUnlessReallyEqual(o["basedir"], fileutil.abspath_expanduser_unicode(u"here"))
3891         o = self.parse(["start", "--basedir", "there"])
3892         self.failUnlessReallyEqual(o["basedir"], fileutil.abspath_expanduser_unicode(u"there"))
3893         o = self.parse(["--node-directory", "there", "start"])
3894         self.failUnlessReallyEqual(o["basedir"], fileutil.abspath_expanduser_unicode(u"there"))
3895
3896         o = self.parse(["start", "here", "--nodaemon"])
3897         self.failUnlessReallyEqual(o["basedir"], fileutil.abspath_expanduser_unicode(u"here"))
3898
3899         self.failUnlessRaises(usage.UsageError, self.parse,
3900                               ["--basedir", "there", "start"])
3901         self.failUnlessRaises(usage.UsageError, self.parse,
3902                               ["start", "--node-directory", "there"])
3903
3904         self.failUnlessRaises(usage.UsageError, self.parse,
3905                               ["--node-directory=there",
3906                                "start", "--basedir=here"])
3907         self.failUnlessRaises(usage.UsageError, self.parse,
3908                               ["start", "--basedir=here", "anywhere"])
3909         self.failUnlessRaises(usage.UsageError, self.parse,
3910                               ["--node-directory=there",
3911                                "start", "anywhere"])
3912         self.failUnlessRaises(usage.UsageError, self.parse,
3913                               ["--node-directory=there",
3914                                "start", "--basedir=here", "anywhere"])
3915
3916         self.failUnlessRaises(usage.UsageError, self.parse,
3917                               ["--node-directory=there", "start", "--nodaemon"])
3918         self.failUnlessRaises(usage.UsageError, self.parse,
3919                               ["start", "--basedir=here", "--nodaemon"])