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