]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/test/test_cli.py
Adds test_cli.Cp.test_cp_copies_dir
[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", fn3, self.dircap))
2036         def _test_for_wrong_indices((rc, out, err)):
2037             lines = err.split('\n')
2038             self.failUnlessIn('examining 1 of 1', lines)
2039             self.failUnlessIn('starting copy, 1 files, 1 directories', lines)
2040             self.failIfIn('examining 0 of', err)
2041         d.addCallback(_test_for_wrong_indices)
2042         return d
2043
2044     def test_cp_with_nonexistent_alias(self):
2045         # when invoked with an alias or aliases that don't exist, 'tahoe cp'
2046         # should output a sensible error message rather than a stack trace.
2047         self.basedir = "cli/Cp/cp_with_nonexistent_alias"
2048         self.set_up_grid()
2049         d = self.do_cli("cp", "fake:file1", "fake:file2")
2050         def _check((rc, out, err)):
2051             self.failUnlessReallyEqual(rc, 1)
2052             self.failUnlessIn("error:", err)
2053         d.addCallback(_check)
2054         # 'tahoe cp' actually processes the target argument first, so we need
2055         # to check to make sure that validation extends to the source
2056         # argument.
2057         d.addCallback(lambda ign: self.do_cli("create-alias", "tahoe"))
2058         d.addCallback(lambda ign: self.do_cli("cp", "fake:file1",
2059                                               "tahoe:file2"))
2060         d.addCallback(_check)
2061         return d
2062
2063     def test_unicode_dirnames(self):
2064         self.basedir = "cli/Cp/unicode_dirnames"
2065
2066         fn1 = os.path.join(unicode(self.basedir), u"\u00C4rtonwall")
2067         try:
2068             fn1_arg = fn1.encode(get_io_encoding())
2069             del fn1_arg # hush pyflakes
2070             artonwall_arg = u"\u00C4rtonwall".encode(get_io_encoding())
2071         except UnicodeEncodeError:
2072             raise unittest.SkipTest("A non-ASCII command argument could not be encoded on this platform.")
2073
2074         self.skip_if_cannot_represent_filename(fn1)
2075
2076         self.set_up_grid()
2077
2078         d = self.do_cli("create-alias", "tahoe")
2079         d.addCallback(lambda res: self.do_cli("mkdir", "tahoe:test/" + artonwall_arg))
2080         d.addCallback(lambda res: self.do_cli("cp", "-r", "tahoe:test", "tahoe:test2"))
2081         d.addCallback(lambda res: self.do_cli("ls", "tahoe:test2"))
2082         def _check((rc, out, err)):
2083             try:
2084                 unicode_to_output(u"\u00C4rtonwall")
2085             except UnicodeEncodeError:
2086                 self.failUnlessReallyEqual(rc, 1)
2087                 self.failUnlessReallyEqual(out, "")
2088                 self.failUnlessIn(quote_output(u"\u00C4rtonwall"), err)
2089                 self.failUnlessIn("files whose names could not be converted", err)
2090             else:
2091                 self.failUnlessReallyEqual(rc, 0)
2092                 self.failUnlessReallyEqual(out.decode(get_io_encoding()), u"\u00C4rtonwall\n")
2093                 self.failUnlessReallyEqual(err, "")
2094         d.addCallback(_check)
2095
2096         return d
2097
2098     def test_cp_replaces_mutable_file_contents(self):
2099         self.basedir = "cli/Cp/cp_replaces_mutable_file_contents"
2100         self.set_up_grid()
2101
2102         # Write a test file, which we'll copy to the grid.
2103         test_txt_path = os.path.join(self.basedir, "test.txt")
2104         test_txt_contents = "foo bar baz"
2105         f = open(test_txt_path, "w")
2106         f.write(test_txt_contents)
2107         f.close()
2108
2109         d = self.do_cli("create-alias", "tahoe")
2110         d.addCallback(lambda ignored:
2111             self.do_cli("mkdir", "tahoe:test"))
2112         # We have to use 'tahoe put' here because 'tahoe cp' doesn't
2113         # know how to make mutable files at the destination.
2114         d.addCallback(lambda ignored:
2115             self.do_cli("put", "--mutable", test_txt_path, "tahoe:test/test.txt"))
2116         d.addCallback(lambda ignored:
2117             self.do_cli("get", "tahoe:test/test.txt"))
2118         def _check((rc, out, err)):
2119             self.failUnlessEqual(rc, 0)
2120             self.failUnlessEqual(out, test_txt_contents)
2121         d.addCallback(_check)
2122
2123         # We'll do ls --json to get the read uri and write uri for the
2124         # file we've just uploaded.
2125         d.addCallback(lambda ignored:
2126             self.do_cli("ls", "--json", "tahoe:test/test.txt"))
2127         def _get_test_txt_uris((rc, out, err)):
2128             self.failUnlessEqual(rc, 0)
2129             filetype, data = simplejson.loads(out)
2130
2131             self.failUnlessEqual(filetype, "filenode")
2132             self.failUnless(data['mutable'])
2133
2134             self.failUnlessIn("rw_uri", data)
2135             self.rw_uri = to_str(data["rw_uri"])
2136             self.failUnlessIn("ro_uri", data)
2137             self.ro_uri = to_str(data["ro_uri"])
2138         d.addCallback(_get_test_txt_uris)
2139
2140         # Now make a new file to copy in place of test.txt.
2141         new_txt_path = os.path.join(self.basedir, "new.txt")
2142         new_txt_contents = "baz bar foo" * 100000
2143         f = open(new_txt_path, "w")
2144         f.write(new_txt_contents)
2145         f.close()
2146
2147         # Copy the new file on top of the old file.
2148         d.addCallback(lambda ignored:
2149             self.do_cli("cp", new_txt_path, "tahoe:test/test.txt"))
2150
2151         # If we get test.txt now, we should see the new data.
2152         d.addCallback(lambda ignored:
2153             self.do_cli("get", "tahoe:test/test.txt"))
2154         d.addCallback(lambda (rc, out, err):
2155             self.failUnlessEqual(out, new_txt_contents))
2156         # If we get the json of the new file, we should see that the old
2157         # uri is there
2158         d.addCallback(lambda ignored:
2159             self.do_cli("ls", "--json", "tahoe:test/test.txt"))
2160         def _check_json((rc, out, err)):
2161             self.failUnlessEqual(rc, 0)
2162             filetype, data = simplejson.loads(out)
2163
2164             self.failUnlessEqual(filetype, "filenode")
2165             self.failUnless(data['mutable'])
2166
2167             self.failUnlessIn("ro_uri", data)
2168             self.failUnlessEqual(to_str(data["ro_uri"]), self.ro_uri)
2169             self.failUnlessIn("rw_uri", data)
2170             self.failUnlessEqual(to_str(data["rw_uri"]), self.rw_uri)
2171         d.addCallback(_check_json)
2172
2173         # and, finally, doing a GET directly on one of the old uris
2174         # should give us the new contents.
2175         d.addCallback(lambda ignored:
2176             self.do_cli("get", self.rw_uri))
2177         d.addCallback(lambda (rc, out, err):
2178             self.failUnlessEqual(out, new_txt_contents))
2179         # Now copy the old test.txt without an explicit destination
2180         # file. tahoe cp will match it to the existing file and
2181         # overwrite it appropriately.
2182         d.addCallback(lambda ignored:
2183             self.do_cli("cp", test_txt_path, "tahoe:test"))
2184         d.addCallback(lambda ignored:
2185             self.do_cli("get", "tahoe:test/test.txt"))
2186         d.addCallback(lambda (rc, out, err):
2187             self.failUnlessEqual(out, test_txt_contents))
2188         d.addCallback(lambda ignored:
2189             self.do_cli("ls", "--json", "tahoe:test/test.txt"))
2190         d.addCallback(_check_json)
2191         d.addCallback(lambda ignored:
2192             self.do_cli("get", self.rw_uri))
2193         d.addCallback(lambda (rc, out, err):
2194             self.failUnlessEqual(out, test_txt_contents))
2195
2196         # Now we'll make a more complicated directory structure.
2197         # test2/
2198         # test2/mutable1
2199         # test2/mutable2
2200         # test2/imm1
2201         # test2/imm2
2202         imm_test_txt_path = os.path.join(self.basedir, "imm_test.txt")
2203         imm_test_txt_contents = test_txt_contents * 10000
2204         fileutil.write(imm_test_txt_path, imm_test_txt_contents)
2205         d.addCallback(lambda ignored:
2206             self.do_cli("mkdir", "tahoe:test2"))
2207         d.addCallback(lambda ignored:
2208             self.do_cli("put", "--mutable", new_txt_path,
2209                         "tahoe:test2/mutable1"))
2210         d.addCallback(lambda ignored:
2211             self.do_cli("put", "--mutable", new_txt_path,
2212                         "tahoe:test2/mutable2"))
2213         d.addCallback(lambda ignored:
2214             self.do_cli('put', new_txt_path, "tahoe:test2/imm1"))
2215         d.addCallback(lambda ignored:
2216             self.do_cli("put", imm_test_txt_path, "tahoe:test2/imm2"))
2217         d.addCallback(lambda ignored:
2218             self.do_cli("ls", "--json", "tahoe:test2"))
2219         def _process_directory_json((rc, out, err)):
2220             self.failUnlessEqual(rc, 0)
2221
2222             filetype, data = simplejson.loads(out)
2223             self.failUnlessEqual(filetype, "dirnode")
2224             self.failUnless(data['mutable'])
2225             self.failUnlessIn("children", data)
2226             children = data['children']
2227
2228             # Store the URIs for later use.
2229             self.childuris = {}
2230             for k in ["mutable1", "mutable2", "imm1", "imm2"]:
2231                 self.failUnlessIn(k, children)
2232                 childtype, childdata = children[k]
2233                 self.failUnlessEqual(childtype, "filenode")
2234                 if "mutable" in k:
2235                     self.failUnless(childdata['mutable'])
2236                     self.failUnlessIn("rw_uri", childdata)
2237                     uri_key = "rw_uri"
2238                 else:
2239                     self.failIf(childdata['mutable'])
2240                     self.failUnlessIn("ro_uri", childdata)
2241                     uri_key = "ro_uri"
2242                 self.childuris[k] = to_str(childdata[uri_key])
2243         d.addCallback(_process_directory_json)
2244         # Now build a local directory to copy into place, like the following:
2245         # source1/
2246         # source1/mutable1
2247         # source1/mutable2
2248         # source1/imm1
2249         # source1/imm3
2250         def _build_local_directory(ignored):
2251             source1_path = os.path.join(self.basedir, "source1")
2252             fileutil.make_dirs(source1_path)
2253             for fn in ("mutable1", "mutable2", "imm1", "imm3"):
2254                 fileutil.write(os.path.join(source1_path, fn), fn * 1000)
2255             self.source1_path = source1_path
2256         d.addCallback(_build_local_directory)
2257         d.addCallback(lambda ignored:
2258             self.do_cli("cp", "-r", self.source1_path, "tahoe:test2"))
2259
2260         # We expect that mutable1 and mutable2 are overwritten in-place,
2261         # so they'll retain their URIs but have different content.
2262         def _process_file_json((rc, out, err), fn):
2263             self.failUnlessEqual(rc, 0)
2264             filetype, data = simplejson.loads(out)
2265             self.failUnlessEqual(filetype, "filenode")
2266
2267             if "mutable" in fn:
2268                 self.failUnless(data['mutable'])
2269                 self.failUnlessIn("rw_uri", data)
2270                 self.failUnlessEqual(to_str(data["rw_uri"]), self.childuris[fn])
2271             else:
2272                 self.failIf(data['mutable'])
2273                 self.failUnlessIn("ro_uri", data)
2274                 self.failIfEqual(to_str(data["ro_uri"]), self.childuris[fn])
2275
2276         for fn in ("mutable1", "mutable2"):
2277             d.addCallback(lambda ignored, fn=fn:
2278                 self.do_cli("get", "tahoe:test2/%s" % fn))
2279             d.addCallback(lambda (rc, out, err), fn=fn:
2280                 self.failUnlessEqual(out, fn * 1000))
2281             d.addCallback(lambda ignored, fn=fn:
2282                 self.do_cli("ls", "--json", "tahoe:test2/%s" % fn))
2283             d.addCallback(_process_file_json, fn=fn)
2284
2285         # imm1 should have been replaced, so both its uri and content
2286         # should be different.
2287         d.addCallback(lambda ignored:
2288             self.do_cli("get", "tahoe:test2/imm1"))
2289         d.addCallback(lambda (rc, out, err):
2290             self.failUnlessEqual(out, "imm1" * 1000))
2291         d.addCallback(lambda ignored:
2292             self.do_cli("ls", "--json", "tahoe:test2/imm1"))
2293         d.addCallback(_process_file_json, fn="imm1")
2294
2295         # imm3 should have been created.
2296         d.addCallback(lambda ignored:
2297             self.do_cli("get", "tahoe:test2/imm3"))
2298         d.addCallback(lambda (rc, out, err):
2299             self.failUnlessEqual(out, "imm3" * 1000))
2300
2301         # imm2 should be exactly as we left it, since our newly-copied
2302         # directory didn't contain an imm2 entry.
2303         d.addCallback(lambda ignored:
2304             self.do_cli("get", "tahoe:test2/imm2"))
2305         d.addCallback(lambda (rc, out, err):
2306             self.failUnlessEqual(out, imm_test_txt_contents))
2307         d.addCallback(lambda ignored:
2308             self.do_cli("ls", "--json", "tahoe:test2/imm2"))
2309         def _process_imm2_json((rc, out, err)):
2310             self.failUnlessEqual(rc, 0)
2311             filetype, data = simplejson.loads(out)
2312             self.failUnlessEqual(filetype, "filenode")
2313             self.failIf(data['mutable'])
2314             self.failUnlessIn("ro_uri", data)
2315             self.failUnlessEqual(to_str(data["ro_uri"]), self.childuris["imm2"])
2316         d.addCallback(_process_imm2_json)
2317         return d
2318
2319     def test_cp_overwrite_readonly_mutable_file(self):
2320         # tahoe cp should print an error when asked to overwrite a
2321         # mutable file that it can't overwrite.
2322         self.basedir = "cli/Cp/overwrite_readonly_mutable_file"
2323         self.set_up_grid()
2324
2325         # This is our initial file. We'll link its readcap into the
2326         # tahoe: alias.
2327         test_file_path = os.path.join(self.basedir, "test_file.txt")
2328         test_file_contents = "This is a test file."
2329         fileutil.write(test_file_path, test_file_contents)
2330
2331         # This is our replacement file. We'll try and fail to upload it
2332         # over the readcap that we linked into the tahoe: alias.
2333         replacement_file_path = os.path.join(self.basedir, "replacement.txt")
2334         replacement_file_contents = "These are new contents."
2335         fileutil.write(replacement_file_path, replacement_file_contents)
2336
2337         d = self.do_cli("create-alias", "tahoe:")
2338         d.addCallback(lambda ignored:
2339             self.do_cli("put", "--mutable", test_file_path))
2340         def _get_test_uri((rc, out, err)):
2341             self.failUnlessEqual(rc, 0)
2342             # this should be a write uri
2343             self._test_write_uri = out
2344         d.addCallback(_get_test_uri)
2345         d.addCallback(lambda ignored:
2346             self.do_cli("ls", "--json", self._test_write_uri))
2347         def _process_test_json((rc, out, err)):
2348             self.failUnlessEqual(rc, 0)
2349             filetype, data = simplejson.loads(out)
2350
2351             self.failUnlessEqual(filetype, "filenode")
2352             self.failUnless(data['mutable'])
2353             self.failUnlessIn("ro_uri", data)
2354             self._test_read_uri = to_str(data["ro_uri"])
2355         d.addCallback(_process_test_json)
2356         # Now we'll link the readonly URI into the tahoe: alias.
2357         d.addCallback(lambda ignored:
2358             self.do_cli("ln", self._test_read_uri, "tahoe:test_file.txt"))
2359         d.addCallback(lambda (rc, out, err):
2360             self.failUnlessEqual(rc, 0))
2361         # Let's grab the json of that to make sure that we did it right.
2362         d.addCallback(lambda ignored:
2363             self.do_cli("ls", "--json", "tahoe:"))
2364         def _process_tahoe_json((rc, out, err)):
2365             self.failUnlessEqual(rc, 0)
2366
2367             filetype, data = simplejson.loads(out)
2368             self.failUnlessEqual(filetype, "dirnode")
2369             self.failUnlessIn("children", data)
2370             kiddata = data['children']
2371
2372             self.failUnlessIn("test_file.txt", kiddata)
2373             testtype, testdata = kiddata['test_file.txt']
2374             self.failUnlessEqual(testtype, "filenode")
2375             self.failUnless(testdata['mutable'])
2376             self.failUnlessIn("ro_uri", testdata)
2377             self.failUnlessEqual(to_str(testdata["ro_uri"]), self._test_read_uri)
2378             self.failIfIn("rw_uri", testdata)
2379         d.addCallback(_process_tahoe_json)
2380         # Okay, now we're going to try uploading another mutable file in
2381         # place of that one. We should get an error.
2382         d.addCallback(lambda ignored:
2383             self.do_cli("cp", replacement_file_path, "tahoe:test_file.txt"))
2384         def _check_error_message((rc, out, err)):
2385             self.failUnlessEqual(rc, 1)
2386             self.failUnlessIn("replace or update requested with read-only cap", err)
2387         d.addCallback(_check_error_message)
2388         # Make extra sure that that didn't work.
2389         d.addCallback(lambda ignored:
2390             self.do_cli("get", "tahoe:test_file.txt"))
2391         d.addCallback(lambda (rc, out, err):
2392             self.failUnlessEqual(out, test_file_contents))
2393         d.addCallback(lambda ignored:
2394             self.do_cli("get", self._test_read_uri))
2395         d.addCallback(lambda (rc, out, err):
2396             self.failUnlessEqual(out, test_file_contents))
2397         # Now we'll do it without an explicit destination.
2398         d.addCallback(lambda ignored:
2399             self.do_cli("cp", test_file_path, "tahoe:"))
2400         d.addCallback(_check_error_message)
2401         d.addCallback(lambda ignored:
2402             self.do_cli("get", "tahoe:test_file.txt"))
2403         d.addCallback(lambda (rc, out, err):
2404             self.failUnlessEqual(out, test_file_contents))
2405         d.addCallback(lambda ignored:
2406             self.do_cli("get", self._test_read_uri))
2407         d.addCallback(lambda (rc, out, err):
2408             self.failUnlessEqual(out, test_file_contents))
2409         # Now we'll link a readonly file into a subdirectory.
2410         d.addCallback(lambda ignored:
2411             self.do_cli("mkdir", "tahoe:testdir"))
2412         d.addCallback(lambda (rc, out, err):
2413             self.failUnlessEqual(rc, 0))
2414         d.addCallback(lambda ignored:
2415             self.do_cli("ln", self._test_read_uri, "tahoe:test/file2.txt"))
2416         d.addCallback(lambda (rc, out, err):
2417             self.failUnlessEqual(rc, 0))
2418
2419         test_dir_path = os.path.join(self.basedir, "test")
2420         fileutil.make_dirs(test_dir_path)
2421         for f in ("file1.txt", "file2.txt"):
2422             fileutil.write(os.path.join(test_dir_path, f), f * 10000)
2423
2424         d.addCallback(lambda ignored:
2425             self.do_cli("cp", "-r", test_dir_path, "tahoe:test"))
2426         d.addCallback(_check_error_message)
2427         d.addCallback(lambda ignored:
2428             self.do_cli("ls", "--json", "tahoe:test"))
2429         def _got_testdir_json((rc, out, err)):
2430             self.failUnlessEqual(rc, 0)
2431
2432             filetype, data = simplejson.loads(out)
2433             self.failUnlessEqual(filetype, "dirnode")
2434
2435             self.failUnlessIn("children", data)
2436             childdata = data['children']
2437
2438             self.failUnlessIn("file2.txt", childdata)
2439             file2type, file2data = childdata['file2.txt']
2440             self.failUnlessEqual(file2type, "filenode")
2441             self.failUnless(file2data['mutable'])
2442             self.failUnlessIn("ro_uri", file2data)
2443             self.failUnlessEqual(to_str(file2data["ro_uri"]), self._test_read_uri)
2444             self.failIfIn("rw_uri", file2data)
2445         d.addCallback(_got_testdir_json)
2446         return d
2447
2448     def test_cp_verbose(self):
2449         self.basedir = "cli/Cp/cp_verbose"
2450         self.set_up_grid()
2451
2452         # Write two test files, which we'll copy to the grid.
2453         test1_path = os.path.join(self.basedir, "test1")
2454         test2_path = os.path.join(self.basedir, "test2")
2455         fileutil.write(test1_path, "test1")
2456         fileutil.write(test2_path, "test2")
2457
2458         d = self.do_cli("create-alias", "tahoe")
2459         d.addCallback(lambda ign:
2460             self.do_cli("cp", "--verbose", test1_path, test2_path, "tahoe:"))
2461         def _check(res):
2462             (rc, out, err) = res
2463             self.failUnlessEqual(rc, 0, str(res))
2464             self.failUnlessIn("Success: files copied", out, str(res))
2465             self.failUnlessEqual(err, """\
2466 attaching sources to targets, 2 files / 0 dirs in root
2467 targets assigned, 1 dirs, 2 files
2468 starting copy, 2 files, 1 directories
2469 1/2 files, 0/1 directories
2470 2/2 files, 0/1 directories
2471 1/1 directories
2472 """, str(res))
2473         d.addCallback(_check)
2474         return d
2475
2476     def test_cp_copies_dir(self):
2477         # This test ensures that a directory is copied using
2478         # tahoe cp -r. Refer to ticket #712:
2479         # https://tahoe-lafs.org/trac/tahoe-lafs/ticket/712
2480
2481         self.basedir = "cli/Cp/cp_copies_dir"
2482         self.set_up_grid()
2483         subdir = os.path.join(self.basedir, "foo")
2484         os.mkdir(subdir)
2485         test1_path = os.path.join(subdir, "test1")
2486         fileutil.write(test1_path, "test1")
2487
2488         d = self.do_cli("create-alias", "tahoe")
2489         d.addCallback(lambda ign:
2490             self.do_cli("cp", "-r", subdir, "tahoe:"))
2491         d.addCallback(lambda ign:
2492             self.do_cli("ls", "tahoe:"))
2493         def _check(res, item):
2494             (rc, out, err) = res
2495             self.failUnlessEqual(rc, 0)
2496             self.failUnlessEqual(err, "")
2497             self.failUnlessIn(item, out, str(res))
2498         d.addCallback(_check, "foo")
2499         d.addCallback(lambda ign:
2500             self.do_cli("ls", "tahoe:foo/"))
2501         d.addCallback(_check, "test1")
2502
2503         d.addCallback(lambda ign: fileutil.rm_dir(subdir))
2504         d.addCallback(lambda ign: self.do_cli("cp", "-r", "tahoe:foo", self.basedir))
2505         def _check_local_fs(ign):
2506             self.failUnless(os.path.isdir(self.basedir))
2507             self.failUnless(os.path.isfile(test1_path))
2508         d.addCallback(_check_local_fs)
2509         return d
2510
2511 class Backup(GridTestMixin, CLITestMixin, StallMixin, unittest.TestCase):
2512
2513     def writeto(self, path, data):
2514         full_path = os.path.join(self.basedir, "home", path)
2515         fileutil.make_dirs(os.path.dirname(full_path))
2516         fileutil.write(full_path, data)
2517
2518     def count_output(self, out):
2519         mo = re.search(r"(\d)+ files uploaded \((\d+) reused\), "
2520                         "(\d)+ files skipped, "
2521                         "(\d+) directories created \((\d+) reused\), "
2522                         "(\d+) directories skipped", out)
2523         return [int(s) for s in mo.groups()]
2524
2525     def count_output2(self, out):
2526         mo = re.search(r"(\d)+ files checked, (\d+) directories checked", out)
2527         return [int(s) for s in mo.groups()]
2528
2529     def test_backup(self):
2530         self.basedir = "cli/Backup/backup"
2531         self.set_up_grid()
2532
2533         # is the backupdb available? If so, we test that a second backup does
2534         # not create new directories.
2535         hush = StringIO()
2536         bdb = backupdb.get_backupdb(os.path.join(self.basedir, "dbtest"),
2537                                     hush)
2538         self.failUnless(bdb)
2539
2540         # create a small local directory with a couple of files
2541         source = os.path.join(self.basedir, "home")
2542         fileutil.make_dirs(os.path.join(source, "empty"))
2543         self.writeto("parent/subdir/foo.txt", "foo")
2544         self.writeto("parent/subdir/bar.txt", "bar\n" * 1000)
2545         self.writeto("parent/blah.txt", "blah")
2546
2547         def do_backup(verbose=False):
2548             cmd = ["backup"]
2549             if verbose:
2550                 cmd.append("--verbose")
2551             cmd.append(source)
2552             cmd.append("tahoe:backups")
2553             return self.do_cli(*cmd)
2554
2555         d = self.do_cli("create-alias", "tahoe")
2556
2557         d.addCallback(lambda res: do_backup())
2558         def _check0((rc, out, err)):
2559             self.failUnlessReallyEqual(err, "")
2560             self.failUnlessReallyEqual(rc, 0)
2561             fu, fr, fs, dc, dr, ds = self.count_output(out)
2562             # foo.txt, bar.txt, blah.txt
2563             self.failUnlessReallyEqual(fu, 3)
2564             self.failUnlessReallyEqual(fr, 0)
2565             self.failUnlessReallyEqual(fs, 0)
2566             # empty, home, home/parent, home/parent/subdir
2567             self.failUnlessReallyEqual(dc, 4)
2568             self.failUnlessReallyEqual(dr, 0)
2569             self.failUnlessReallyEqual(ds, 0)
2570         d.addCallback(_check0)
2571
2572         d.addCallback(lambda res: self.do_cli("ls", "--uri", "tahoe:backups"))
2573         def _check1((rc, out, err)):
2574             self.failUnlessReallyEqual(err, "")
2575             self.failUnlessReallyEqual(rc, 0)
2576             lines = out.split("\n")
2577             children = dict([line.split() for line in lines if line])
2578             latest_uri = children["Latest"]
2579             self.failUnless(latest_uri.startswith("URI:DIR2-CHK:"), latest_uri)
2580             childnames = children.keys()
2581             self.failUnlessReallyEqual(sorted(childnames), ["Archives", "Latest"])
2582         d.addCallback(_check1)
2583         d.addCallback(lambda res: self.do_cli("ls", "tahoe:backups/Latest"))
2584         def _check2((rc, out, err)):
2585             self.failUnlessReallyEqual(err, "")
2586             self.failUnlessReallyEqual(rc, 0)
2587             self.failUnlessReallyEqual(sorted(out.split()), ["empty", "parent"])
2588         d.addCallback(_check2)
2589         d.addCallback(lambda res: self.do_cli("ls", "tahoe:backups/Latest/empty"))
2590         def _check2a((rc, out, err)):
2591             self.failUnlessReallyEqual(err, "")
2592             self.failUnlessReallyEqual(rc, 0)
2593             self.failUnlessReallyEqual(out.strip(), "")
2594         d.addCallback(_check2a)
2595         d.addCallback(lambda res: self.do_cli("get", "tahoe:backups/Latest/parent/subdir/foo.txt"))
2596         def _check3((rc, out, err)):
2597             self.failUnlessReallyEqual(err, "")
2598             self.failUnlessReallyEqual(rc, 0)
2599             self.failUnlessReallyEqual(out, "foo")
2600         d.addCallback(_check3)
2601         d.addCallback(lambda res: self.do_cli("ls", "tahoe:backups/Archives"))
2602         def _check4((rc, out, err)):
2603             self.failUnlessReallyEqual(err, "")
2604             self.failUnlessReallyEqual(rc, 0)
2605             self.old_archives = out.split()
2606             self.failUnlessReallyEqual(len(self.old_archives), 1)
2607         d.addCallback(_check4)
2608
2609
2610         d.addCallback(self.stall, 1.1)
2611         d.addCallback(lambda res: do_backup())
2612         def _check4a((rc, out, err)):
2613             # second backup should reuse everything, if the backupdb is
2614             # available
2615             self.failUnlessReallyEqual(err, "")
2616             self.failUnlessReallyEqual(rc, 0)
2617             fu, fr, fs, dc, dr, ds = self.count_output(out)
2618             # foo.txt, bar.txt, blah.txt
2619             self.failUnlessReallyEqual(fu, 0)
2620             self.failUnlessReallyEqual(fr, 3)
2621             self.failUnlessReallyEqual(fs, 0)
2622             # empty, home, home/parent, home/parent/subdir
2623             self.failUnlessReallyEqual(dc, 0)
2624             self.failUnlessReallyEqual(dr, 4)
2625             self.failUnlessReallyEqual(ds, 0)
2626         d.addCallback(_check4a)
2627
2628         # sneak into the backupdb, crank back the "last checked"
2629         # timestamp to force a check on all files
2630         def _reset_last_checked(res):
2631             dbfile = os.path.join(self.get_clientdir(),
2632                                   "private", "backupdb.sqlite")
2633             self.failUnless(os.path.exists(dbfile), dbfile)
2634             bdb = backupdb.get_backupdb(dbfile)
2635             bdb.cursor.execute("UPDATE last_upload SET last_checked=0")
2636             bdb.cursor.execute("UPDATE directories SET last_checked=0")
2637             bdb.connection.commit()
2638
2639         d.addCallback(_reset_last_checked)
2640
2641         d.addCallback(self.stall, 1.1)
2642         d.addCallback(lambda res: do_backup(verbose=True))
2643         def _check4b((rc, out, err)):
2644             # we should check all files, and re-use all of them. None of
2645             # the directories should have been changed, so we should
2646             # re-use all of them too.
2647             self.failUnlessReallyEqual(err, "")
2648             self.failUnlessReallyEqual(rc, 0)
2649             fu, fr, fs, dc, dr, ds = self.count_output(out)
2650             fchecked, dchecked = self.count_output2(out)
2651             self.failUnlessReallyEqual(fchecked, 3)
2652             self.failUnlessReallyEqual(fu, 0)
2653             self.failUnlessReallyEqual(fr, 3)
2654             self.failUnlessReallyEqual(fs, 0)
2655             self.failUnlessReallyEqual(dchecked, 4)
2656             self.failUnlessReallyEqual(dc, 0)
2657             self.failUnlessReallyEqual(dr, 4)
2658             self.failUnlessReallyEqual(ds, 0)
2659         d.addCallback(_check4b)
2660
2661         d.addCallback(lambda res: self.do_cli("ls", "tahoe:backups/Archives"))
2662         def _check5((rc, out, err)):
2663             self.failUnlessReallyEqual(err, "")
2664             self.failUnlessReallyEqual(rc, 0)
2665             self.new_archives = out.split()
2666             self.failUnlessReallyEqual(len(self.new_archives), 3, out)
2667             # the original backup should still be the oldest (i.e. sorts
2668             # alphabetically towards the beginning)
2669             self.failUnlessReallyEqual(sorted(self.new_archives)[0],
2670                                  self.old_archives[0])
2671         d.addCallback(_check5)
2672
2673         d.addCallback(self.stall, 1.1)
2674         def _modify(res):
2675             self.writeto("parent/subdir/foo.txt", "FOOF!")
2676             # and turn a file into a directory
2677             os.unlink(os.path.join(source, "parent/blah.txt"))
2678             os.mkdir(os.path.join(source, "parent/blah.txt"))
2679             self.writeto("parent/blah.txt/surprise file", "surprise")
2680             self.writeto("parent/blah.txt/surprisedir/subfile", "surprise")
2681             # turn a directory into a file
2682             os.rmdir(os.path.join(source, "empty"))
2683             self.writeto("empty", "imagine nothing being here")
2684             return do_backup()
2685         d.addCallback(_modify)
2686         def _check5a((rc, out, err)):
2687             # second backup should reuse bar.txt (if backupdb is available),
2688             # and upload the rest. None of the directories can be reused.
2689             self.failUnlessReallyEqual(err, "")
2690             self.failUnlessReallyEqual(rc, 0)
2691             fu, fr, fs, dc, dr, ds = self.count_output(out)
2692             # new foo.txt, surprise file, subfile, empty
2693             self.failUnlessReallyEqual(fu, 4)
2694             # old bar.txt
2695             self.failUnlessReallyEqual(fr, 1)
2696             self.failUnlessReallyEqual(fs, 0)
2697             # home, parent, subdir, blah.txt, surprisedir
2698             self.failUnlessReallyEqual(dc, 5)
2699             self.failUnlessReallyEqual(dr, 0)
2700             self.failUnlessReallyEqual(ds, 0)
2701         d.addCallback(_check5a)
2702         d.addCallback(lambda res: self.do_cli("ls", "tahoe:backups/Archives"))
2703         def _check6((rc, out, err)):
2704             self.failUnlessReallyEqual(err, "")
2705             self.failUnlessReallyEqual(rc, 0)
2706             self.new_archives = out.split()
2707             self.failUnlessReallyEqual(len(self.new_archives), 4)
2708             self.failUnlessReallyEqual(sorted(self.new_archives)[0],
2709                                  self.old_archives[0])
2710         d.addCallback(_check6)
2711         d.addCallback(lambda res: self.do_cli("get", "tahoe:backups/Latest/parent/subdir/foo.txt"))
2712         def _check7((rc, out, err)):
2713             self.failUnlessReallyEqual(err, "")
2714             self.failUnlessReallyEqual(rc, 0)
2715             self.failUnlessReallyEqual(out, "FOOF!")
2716             # the old snapshot should not be modified
2717             return self.do_cli("get", "tahoe:backups/Archives/%s/parent/subdir/foo.txt" % self.old_archives[0])
2718         d.addCallback(_check7)
2719         def _check8((rc, out, err)):
2720             self.failUnlessReallyEqual(err, "")
2721             self.failUnlessReallyEqual(rc, 0)
2722             self.failUnlessReallyEqual(out, "foo")
2723         d.addCallback(_check8)
2724
2725         return d
2726
2727     # on our old dapper buildslave, this test takes a long time (usually
2728     # 130s), so we have to bump up the default 120s timeout. The create-alias
2729     # and initial backup alone take 60s, probably because of the handful of
2730     # dirnodes being created (RSA key generation). The backup between check4
2731     # and check4a takes 6s, as does the backup before check4b.
2732     test_backup.timeout = 3000
2733
2734     def _check_filtering(self, filtered, all, included, excluded):
2735         filtered = set(filtered)
2736         all = set(all)
2737         included = set(included)
2738         excluded = set(excluded)
2739         self.failUnlessReallyEqual(filtered, included)
2740         self.failUnlessReallyEqual(all.difference(filtered), excluded)
2741
2742     def test_exclude_options(self):
2743         root_listdir = (u'lib.a', u'_darcs', u'subdir', u'nice_doc.lyx')
2744         subdir_listdir = (u'another_doc.lyx', u'run_snake_run.py', u'CVS', u'.svn', u'_darcs')
2745         basedir = "cli/Backup/exclude_options"
2746         fileutil.make_dirs(basedir)
2747         nodeurl_path = os.path.join(basedir, 'node.url')
2748         fileutil.write(nodeurl_path, 'http://example.net:2357/')
2749         def parse(args): return parse_options(basedir, "backup", args)
2750
2751         # test simple exclude
2752         backup_options = parse(['--exclude', '*lyx', 'from', 'to'])
2753         filtered = list(backup_options.filter_listdir(root_listdir))
2754         self._check_filtering(filtered, root_listdir, (u'lib.a', u'_darcs', u'subdir'),
2755                               (u'nice_doc.lyx',))
2756         # multiple exclude
2757         backup_options = parse(['--exclude', '*lyx', '--exclude', 'lib.?', 'from', 'to'])
2758         filtered = list(backup_options.filter_listdir(root_listdir))
2759         self._check_filtering(filtered, root_listdir, (u'_darcs', u'subdir'),
2760                               (u'nice_doc.lyx', u'lib.a'))
2761         # vcs metadata exclusion
2762         backup_options = parse(['--exclude-vcs', 'from', 'to'])
2763         filtered = list(backup_options.filter_listdir(subdir_listdir))
2764         self._check_filtering(filtered, subdir_listdir, (u'another_doc.lyx', u'run_snake_run.py',),
2765                               (u'CVS', u'.svn', u'_darcs'))
2766         # read exclude patterns from file
2767         exclusion_string = "_darcs\n*py\n.svn"
2768         excl_filepath = os.path.join(basedir, 'exclusion')
2769         fileutil.write(excl_filepath, exclusion_string)
2770         backup_options = parse(['--exclude-from', excl_filepath, 'from', 'to'])
2771         filtered = list(backup_options.filter_listdir(subdir_listdir))
2772         self._check_filtering(filtered, subdir_listdir, (u'another_doc.lyx', u'CVS'),
2773                               (u'.svn', u'_darcs', u'run_snake_run.py'))
2774         # test BackupConfigurationError
2775         self.failUnlessRaises(cli.BackupConfigurationError,
2776                               parse,
2777                               ['--exclude-from', excl_filepath + '.no', 'from', 'to'])
2778
2779         # test that an iterator works too
2780         backup_options = parse(['--exclude', '*lyx', 'from', 'to'])
2781         filtered = list(backup_options.filter_listdir(iter(root_listdir)))
2782         self._check_filtering(filtered, root_listdir, (u'lib.a', u'_darcs', u'subdir'),
2783                               (u'nice_doc.lyx',))
2784
2785     def test_exclude_options_unicode(self):
2786         nice_doc = u"nice_d\u00F8c.lyx"
2787         try:
2788             doc_pattern_arg = u"*d\u00F8c*".encode(get_io_encoding())
2789         except UnicodeEncodeError:
2790             raise unittest.SkipTest("A non-ASCII command argument could not be encoded on this platform.")
2791
2792         root_listdir = (u'lib.a', u'_darcs', u'subdir', nice_doc)
2793         basedir = "cli/Backup/exclude_options_unicode"
2794         fileutil.make_dirs(basedir)
2795         nodeurl_path = os.path.join(basedir, 'node.url')
2796         fileutil.write(nodeurl_path, 'http://example.net:2357/')
2797         def parse(args): return parse_options(basedir, "backup", args)
2798
2799         # test simple exclude
2800         backup_options = parse(['--exclude', doc_pattern_arg, 'from', 'to'])
2801         filtered = list(backup_options.filter_listdir(root_listdir))
2802         self._check_filtering(filtered, root_listdir, (u'lib.a', u'_darcs', u'subdir'),
2803                               (nice_doc,))
2804         # multiple exclude
2805         backup_options = parse(['--exclude', doc_pattern_arg, '--exclude', 'lib.?', 'from', 'to'])
2806         filtered = list(backup_options.filter_listdir(root_listdir))
2807         self._check_filtering(filtered, root_listdir, (u'_darcs', u'subdir'),
2808                              (nice_doc, u'lib.a'))
2809         # read exclude patterns from file
2810         exclusion_string = doc_pattern_arg + "\nlib.?"
2811         excl_filepath = os.path.join(basedir, 'exclusion')
2812         fileutil.write(excl_filepath, exclusion_string)
2813         backup_options = parse(['--exclude-from', excl_filepath, 'from', 'to'])
2814         filtered = list(backup_options.filter_listdir(root_listdir))
2815         self._check_filtering(filtered, root_listdir, (u'_darcs', u'subdir'),
2816                              (nice_doc, u'lib.a'))
2817
2818         # test that an iterator works too
2819         backup_options = parse(['--exclude', doc_pattern_arg, 'from', 'to'])
2820         filtered = list(backup_options.filter_listdir(iter(root_listdir)))
2821         self._check_filtering(filtered, root_listdir, (u'lib.a', u'_darcs', u'subdir'),
2822                               (nice_doc,))
2823
2824     @patch('__builtin__.file')
2825     def test_exclude_from_tilde_expansion(self, mock):
2826         basedir = "cli/Backup/exclude_from_tilde_expansion"
2827         fileutil.make_dirs(basedir)
2828         nodeurl_path = os.path.join(basedir, 'node.url')
2829         fileutil.write(nodeurl_path, 'http://example.net:2357/')
2830         def parse(args): return parse_options(basedir, "backup", args)
2831
2832         # ensure that tilde expansion is performed on exclude-from argument
2833         exclude_file = u'~/.tahoe/excludes.dummy'
2834
2835         mock.return_value = StringIO()
2836         parse(['--exclude-from', unicode_to_argv(exclude_file), 'from', 'to'])
2837         self.failUnlessIn(((abspath_expanduser_unicode(exclude_file),), {}), mock.call_args_list)
2838
2839     def test_ignore_symlinks(self):
2840         if not hasattr(os, 'symlink'):
2841             raise unittest.SkipTest("Symlinks are not supported by Python on this platform.")
2842
2843         self.basedir = os.path.dirname(self.mktemp())
2844         self.set_up_grid()
2845
2846         source = os.path.join(self.basedir, "home")
2847         self.writeto("foo.txt", "foo")
2848         os.symlink(os.path.join(source, "foo.txt"), os.path.join(source, "foo2.txt"))
2849
2850         d = self.do_cli("create-alias", "tahoe")
2851         d.addCallback(lambda res: self.do_cli("backup", "--verbose", source, "tahoe:test"))
2852
2853         def _check((rc, out, err)):
2854             self.failUnlessReallyEqual(rc, 2)
2855             foo2 = os.path.join(source, "foo2.txt")
2856             self.failUnlessReallyEqual(err, "WARNING: cannot backup symlink '%s'\n" % foo2)
2857
2858             fu, fr, fs, dc, dr, ds = self.count_output(out)
2859             # foo.txt
2860             self.failUnlessReallyEqual(fu, 1)
2861             self.failUnlessReallyEqual(fr, 0)
2862             # foo2.txt
2863             self.failUnlessReallyEqual(fs, 1)
2864             # home
2865             self.failUnlessReallyEqual(dc, 1)
2866             self.failUnlessReallyEqual(dr, 0)
2867             self.failUnlessReallyEqual(ds, 0)
2868
2869         d.addCallback(_check)
2870         return d
2871
2872     def test_ignore_unreadable_file(self):
2873         self.basedir = os.path.dirname(self.mktemp())
2874         self.set_up_grid()
2875
2876         source = os.path.join(self.basedir, "home")
2877         self.writeto("foo.txt", "foo")
2878         os.chmod(os.path.join(source, "foo.txt"), 0000)
2879
2880         d = self.do_cli("create-alias", "tahoe")
2881         d.addCallback(lambda res: self.do_cli("backup", source, "tahoe:test"))
2882
2883         def _check((rc, out, err)):
2884             self.failUnlessReallyEqual(rc, 2)
2885             self.failUnlessReallyEqual(err, "WARNING: permission denied on file %s\n" % os.path.join(source, "foo.txt"))
2886
2887             fu, fr, fs, dc, dr, ds = self.count_output(out)
2888             self.failUnlessReallyEqual(fu, 0)
2889             self.failUnlessReallyEqual(fr, 0)
2890             # foo.txt
2891             self.failUnlessReallyEqual(fs, 1)
2892             # home
2893             self.failUnlessReallyEqual(dc, 1)
2894             self.failUnlessReallyEqual(dr, 0)
2895             self.failUnlessReallyEqual(ds, 0)
2896         d.addCallback(_check)
2897
2898         # This is necessary for the temp files to be correctly removed
2899         def _cleanup(self):
2900             os.chmod(os.path.join(source, "foo.txt"), 0644)
2901         d.addCallback(_cleanup)
2902         d.addErrback(_cleanup)
2903
2904         return d
2905
2906     def test_ignore_unreadable_directory(self):
2907         self.basedir = os.path.dirname(self.mktemp())
2908         self.set_up_grid()
2909
2910         source = os.path.join(self.basedir, "home")
2911         os.mkdir(source)
2912         os.mkdir(os.path.join(source, "test"))
2913         os.chmod(os.path.join(source, "test"), 0000)
2914
2915         d = self.do_cli("create-alias", "tahoe")
2916         d.addCallback(lambda res: self.do_cli("backup", source, "tahoe:test"))
2917
2918         def _check((rc, out, err)):
2919             self.failUnlessReallyEqual(rc, 2)
2920             self.failUnlessReallyEqual(err, "WARNING: permission denied on directory %s\n" % os.path.join(source, "test"))
2921
2922             fu, fr, fs, dc, dr, ds = self.count_output(out)
2923             self.failUnlessReallyEqual(fu, 0)
2924             self.failUnlessReallyEqual(fr, 0)
2925             self.failUnlessReallyEqual(fs, 0)
2926             # home, test
2927             self.failUnlessReallyEqual(dc, 2)
2928             self.failUnlessReallyEqual(dr, 0)
2929             # test
2930             self.failUnlessReallyEqual(ds, 1)
2931         d.addCallback(_check)
2932
2933         # This is necessary for the temp files to be correctly removed
2934         def _cleanup(self):
2935             os.chmod(os.path.join(source, "test"), 0655)
2936         d.addCallback(_cleanup)
2937         d.addErrback(_cleanup)
2938         return d
2939
2940     def test_backup_without_alias(self):
2941         # 'tahoe backup' should output a sensible error message when invoked
2942         # without an alias instead of a stack trace.
2943         self.basedir = os.path.dirname(self.mktemp())
2944         self.set_up_grid()
2945         source = os.path.join(self.basedir, "file1")
2946         d = self.do_cli('backup', source, source)
2947         def _check((rc, out, err)):
2948             self.failUnlessReallyEqual(rc, 1)
2949             self.failUnlessIn("error:", err)
2950             self.failUnlessReallyEqual(out, "")
2951         d.addCallback(_check)
2952         return d
2953
2954     def test_backup_with_nonexistent_alias(self):
2955         # 'tahoe backup' should output a sensible error message when invoked
2956         # with a nonexistent alias.
2957         self.basedir = os.path.dirname(self.mktemp())
2958         self.set_up_grid()
2959         source = os.path.join(self.basedir, "file1")
2960         d = self.do_cli("backup", source, "nonexistent:" + source)
2961         def _check((rc, out, err)):
2962             self.failUnlessReallyEqual(rc, 1)
2963             self.failUnlessIn("error:", err)
2964             self.failUnlessIn("nonexistent", err)
2965             self.failUnlessReallyEqual(out, "")
2966         d.addCallback(_check)
2967         return d
2968
2969
2970 class Check(GridTestMixin, CLITestMixin, unittest.TestCase):
2971
2972     def test_check(self):
2973         self.basedir = "cli/Check/check"
2974         self.set_up_grid()
2975         c0 = self.g.clients[0]
2976         DATA = "data" * 100
2977         DATA_uploadable = MutableData(DATA)
2978         d = c0.create_mutable_file(DATA_uploadable)
2979         def _stash_uri(n):
2980             self.uri = n.get_uri()
2981         d.addCallback(_stash_uri)
2982
2983         d.addCallback(lambda ign: self.do_cli("check", self.uri))
2984         def _check1((rc, out, err)):
2985             self.failUnlessReallyEqual(err, "")
2986             self.failUnlessReallyEqual(rc, 0)
2987             lines = out.splitlines()
2988             self.failUnless("Summary: Healthy" in lines, out)
2989             self.failUnless(" good-shares: 10 (encoding is 3-of-10)" in lines, out)
2990         d.addCallback(_check1)
2991
2992         d.addCallback(lambda ign: self.do_cli("check", "--raw", self.uri))
2993         def _check2((rc, out, err)):
2994             self.failUnlessReallyEqual(err, "")
2995             self.failUnlessReallyEqual(rc, 0)
2996             data = simplejson.loads(out)
2997             self.failUnlessReallyEqual(to_str(data["summary"]), "Healthy")
2998             self.failUnlessReallyEqual(data["results"]["healthy"], True)
2999         d.addCallback(_check2)
3000
3001         d.addCallback(lambda ign: c0.upload(upload.Data("literal", convergence="")))
3002         def _stash_lit_uri(n):
3003             self.lit_uri = n.get_uri()
3004         d.addCallback(_stash_lit_uri)
3005
3006         d.addCallback(lambda ign: self.do_cli("check", self.lit_uri))
3007         def _check_lit((rc, out, err)):
3008             self.failUnlessReallyEqual(err, "")
3009             self.failUnlessReallyEqual(rc, 0)
3010             lines = out.splitlines()
3011             self.failUnless("Summary: Healthy (LIT)" in lines, out)
3012         d.addCallback(_check_lit)
3013
3014         d.addCallback(lambda ign: self.do_cli("check", "--raw", self.lit_uri))
3015         def _check_lit_raw((rc, out, err)):
3016             self.failUnlessReallyEqual(err, "")
3017             self.failUnlessReallyEqual(rc, 0)
3018             data = simplejson.loads(out)
3019             self.failUnlessReallyEqual(data["results"]["healthy"], True)
3020         d.addCallback(_check_lit_raw)
3021
3022         d.addCallback(lambda ign: c0.create_immutable_dirnode({}, convergence=""))
3023         def _stash_lit_dir_uri(n):
3024             self.lit_dir_uri = n.get_uri()
3025         d.addCallback(_stash_lit_dir_uri)
3026
3027         d.addCallback(lambda ign: self.do_cli("check", self.lit_dir_uri))
3028         d.addCallback(_check_lit)
3029
3030         d.addCallback(lambda ign: self.do_cli("check", "--raw", self.lit_uri))
3031         d.addCallback(_check_lit_raw)
3032
3033         def _clobber_shares(ignored):
3034             # delete one, corrupt a second
3035             shares = self.find_uri_shares(self.uri)
3036             self.failUnlessReallyEqual(len(shares), 10)
3037             os.unlink(shares[0][2])
3038             cso = debug.CorruptShareOptions()
3039             cso.stdout = StringIO()
3040             cso.parseOptions([shares[1][2]])
3041             storage_index = uri.from_string(self.uri).get_storage_index()
3042             self._corrupt_share_line = "  server %s, SI %s, shnum %d" % \
3043                                        (base32.b2a(shares[1][1]),
3044                                         base32.b2a(storage_index),
3045                                         shares[1][0])
3046             debug.corrupt_share(cso)
3047         d.addCallback(_clobber_shares)
3048
3049         d.addCallback(lambda ign: self.do_cli("check", "--verify", self.uri))
3050         def _check3((rc, out, err)):
3051             self.failUnlessReallyEqual(err, "")
3052             self.failUnlessReallyEqual(rc, 0)
3053             lines = out.splitlines()
3054             summary = [l for l in lines if l.startswith("Summary")][0]
3055             self.failUnless("Summary: Unhealthy: 8 shares (enc 3-of-10)"
3056                             in summary, summary)
3057             self.failUnless(" good-shares: 8 (encoding is 3-of-10)" in lines, out)
3058             self.failUnless(" corrupt shares:" in lines, out)
3059             self.failUnless(self._corrupt_share_line in lines, out)
3060         d.addCallback(_check3)
3061
3062         d.addCallback(lambda ign: self.do_cli("check", "--verify", "--raw", self.uri))
3063         def _check3_raw((rc, out, err)):
3064             self.failUnlessReallyEqual(err, "")
3065             self.failUnlessReallyEqual(rc, 0)
3066             data = simplejson.loads(out)
3067             self.failUnlessReallyEqual(data["results"]["healthy"], False)
3068             self.failUnlessIn("Unhealthy: 8 shares (enc 3-of-10)", data["summary"])
3069             self.failUnlessReallyEqual(data["results"]["count-shares-good"], 8)
3070             self.failUnlessReallyEqual(data["results"]["count-corrupt-shares"], 1)
3071             self.failUnlessIn("list-corrupt-shares", data["results"])
3072         d.addCallback(_check3_raw)
3073
3074         d.addCallback(lambda ign:
3075                       self.do_cli("check", "--verify", "--repair", self.uri))
3076         def _check4((rc, out, err)):
3077             self.failUnlessReallyEqual(err, "")
3078             self.failUnlessReallyEqual(rc, 0)
3079             lines = out.splitlines()
3080             self.failUnless("Summary: not healthy" in lines, out)
3081             self.failUnless(" good-shares: 8 (encoding is 3-of-10)" in lines, out)
3082             self.failUnless(" corrupt shares:" in lines, out)
3083             self.failUnless(self._corrupt_share_line in lines, out)
3084             self.failUnless(" repair successful" in lines, out)
3085         d.addCallback(_check4)
3086
3087         d.addCallback(lambda ign:
3088                       self.do_cli("check", "--verify", "--repair", self.uri))
3089         def _check5((rc, out, err)):
3090             self.failUnlessReallyEqual(err, "")
3091             self.failUnlessReallyEqual(rc, 0)
3092             lines = out.splitlines()
3093             self.failUnless("Summary: healthy" in lines, out)
3094             self.failUnless(" good-shares: 10 (encoding is 3-of-10)" in lines, out)
3095             self.failIf(" corrupt shares:" in lines, out)
3096         d.addCallback(_check5)
3097
3098         return d
3099
3100     def test_deep_check(self):
3101         self.basedir = "cli/Check/deep_check"
3102         self.set_up_grid()
3103         c0 = self.g.clients[0]
3104         self.uris = {}
3105         self.fileurls = {}
3106         DATA = "data" * 100
3107         quoted_good = quote_output(u"g\u00F6\u00F6d")
3108
3109         d = c0.create_dirnode()
3110         def _stash_root_and_create_file(n):
3111             self.rootnode = n
3112             self.rooturi = n.get_uri()
3113             return n.add_file(u"g\u00F6\u00F6d", upload.Data(DATA, convergence=""))
3114         d.addCallback(_stash_root_and_create_file)
3115         def _stash_uri(fn, which):
3116             self.uris[which] = fn.get_uri()
3117             return fn
3118         d.addCallback(_stash_uri, u"g\u00F6\u00F6d")
3119         d.addCallback(lambda ign:
3120                       self.rootnode.add_file(u"small",
3121                                            upload.Data("literal",
3122                                                         convergence="")))
3123         d.addCallback(_stash_uri, "small")
3124         d.addCallback(lambda ign:
3125             c0.create_mutable_file(MutableData(DATA+"1")))
3126         d.addCallback(lambda fn: self.rootnode.set_node(u"mutable", fn))
3127         d.addCallback(_stash_uri, "mutable")
3128
3129         d.addCallback(lambda ign: self.do_cli("deep-check", self.rooturi))
3130         def _check1((rc, out, err)):
3131             self.failUnlessReallyEqual(err, "")
3132             self.failUnlessReallyEqual(rc, 0)
3133             lines = out.splitlines()
3134             self.failUnless("done: 4 objects checked, 4 healthy, 0 unhealthy"
3135                             in lines, out)
3136         d.addCallback(_check1)
3137
3138         # root
3139         # root/g\u00F6\u00F6d
3140         # root/small
3141         # root/mutable
3142
3143         d.addCallback(lambda ign: self.do_cli("deep-check", "--verbose",
3144                                               self.rooturi))
3145         def _check2((rc, out, err)):
3146             self.failUnlessReallyEqual(err, "")
3147             self.failUnlessReallyEqual(rc, 0)
3148             lines = out.splitlines()
3149             self.failUnless("'<root>': Healthy" in lines, out)
3150             self.failUnless("'small': Healthy (LIT)" in lines, out)
3151             self.failUnless((quoted_good + ": Healthy") in lines, out)
3152             self.failUnless("'mutable': Healthy" in lines, out)
3153             self.failUnless("done: 4 objects checked, 4 healthy, 0 unhealthy"
3154                             in lines, out)
3155         d.addCallback(_check2)
3156
3157         d.addCallback(lambda ign: self.do_cli("stats", self.rooturi))
3158         def _check_stats((rc, out, err)):
3159             self.failUnlessReallyEqual(err, "")
3160             self.failUnlessReallyEqual(rc, 0)
3161             lines = out.splitlines()
3162             self.failUnlessIn(" count-immutable-files: 1", lines)
3163             self.failUnlessIn("   count-mutable-files: 1", lines)
3164             self.failUnlessIn("   count-literal-files: 1", lines)
3165             self.failUnlessIn("     count-directories: 1", lines)
3166             self.failUnlessIn("  size-immutable-files: 400", lines)
3167             self.failUnlessIn("Size Histogram:", lines)
3168             self.failUnlessIn("   4-10   : 1    (10 B, 10 B)", lines)
3169             self.failUnlessIn(" 317-1000 : 1    (1000 B, 1000 B)", lines)
3170         d.addCallback(_check_stats)
3171
3172         def _clobber_shares(ignored):
3173             shares = self.find_uri_shares(self.uris[u"g\u00F6\u00F6d"])
3174             self.failUnlessReallyEqual(len(shares), 10)
3175             os.unlink(shares[0][2])
3176
3177             shares = self.find_uri_shares(self.uris["mutable"])
3178             cso = debug.CorruptShareOptions()
3179             cso.stdout = StringIO()
3180             cso.parseOptions([shares[1][2]])
3181             storage_index = uri.from_string(self.uris["mutable"]).get_storage_index()
3182             self._corrupt_share_line = " corrupt: server %s, SI %s, shnum %d" % \
3183                                        (base32.b2a(shares[1][1]),
3184                                         base32.b2a(storage_index),
3185                                         shares[1][0])
3186             debug.corrupt_share(cso)
3187         d.addCallback(_clobber_shares)
3188
3189         # root
3190         # root/g\u00F6\u00F6d  [9 shares]
3191         # root/small
3192         # root/mutable [1 corrupt share]
3193
3194         d.addCallback(lambda ign:
3195                       self.do_cli("deep-check", "--verbose", self.rooturi))
3196         def _check3((rc, out, err)):
3197             self.failUnlessReallyEqual(err, "")
3198             self.failUnlessReallyEqual(rc, 0)
3199             lines = out.splitlines()
3200             self.failUnless("'<root>': Healthy" in lines, out)
3201             self.failUnless("'small': Healthy (LIT)" in lines, out)
3202             self.failUnless("'mutable': Healthy" in lines, out) # needs verifier
3203             self.failUnless((quoted_good + ": Not Healthy: 9 shares (enc 3-of-10)") in lines, out)
3204             self.failIf(self._corrupt_share_line in lines, out)
3205             self.failUnless("done: 4 objects checked, 3 healthy, 1 unhealthy"
3206                             in lines, out)
3207         d.addCallback(_check3)
3208
3209         d.addCallback(lambda ign:
3210                       self.do_cli("deep-check", "--verbose", "--verify",
3211                                   self.rooturi))
3212         def _check4((rc, out, err)):
3213             self.failUnlessReallyEqual(err, "")
3214             self.failUnlessReallyEqual(rc, 0)
3215             lines = out.splitlines()
3216             self.failUnless("'<root>': Healthy" in lines, out)
3217             self.failUnless("'small': Healthy (LIT)" in lines, out)
3218             mutable = [l for l in lines if l.startswith("'mutable'")][0]
3219             self.failUnless(mutable.startswith("'mutable': Unhealthy: 9 shares (enc 3-of-10)"),
3220                             mutable)
3221             self.failUnless(self._corrupt_share_line in lines, out)
3222             self.failUnless((quoted_good + ": Not Healthy: 9 shares (enc 3-of-10)") in lines, out)
3223             self.failUnless("done: 4 objects checked, 2 healthy, 2 unhealthy"
3224                             in lines, out)
3225         d.addCallback(_check4)
3226
3227         d.addCallback(lambda ign:
3228                       self.do_cli("deep-check", "--raw",
3229                                   self.rooturi))
3230         def _check5((rc, out, err)):
3231             self.failUnlessReallyEqual(err, "")
3232             self.failUnlessReallyEqual(rc, 0)
3233             lines = out.splitlines()
3234             units = [simplejson.loads(line) for line in lines]
3235             # root, small, g\u00F6\u00F6d, mutable,  stats
3236             self.failUnlessReallyEqual(len(units), 4+1)
3237         d.addCallback(_check5)
3238
3239         d.addCallback(lambda ign:
3240                       self.do_cli("deep-check",
3241                                   "--verbose", "--verify", "--repair",
3242                                   self.rooturi))
3243         def _check6((rc, out, err)):
3244             self.failUnlessReallyEqual(err, "")
3245             self.failUnlessReallyEqual(rc, 0)
3246             lines = out.splitlines()
3247             self.failUnless("'<root>': healthy" in lines, out)
3248             self.failUnless("'small': healthy" in lines, out)
3249             self.failUnless("'mutable': not healthy" in lines, out)
3250             self.failUnless(self._corrupt_share_line in lines, out)
3251             self.failUnless((quoted_good + ": not healthy") in lines, out)
3252             self.failUnless("done: 4 objects checked" in lines, out)
3253             self.failUnless(" pre-repair: 2 healthy, 2 unhealthy" in lines, out)
3254             self.failUnless(" 2 repairs attempted, 2 successful, 0 failed"
3255                             in lines, out)
3256             self.failUnless(" post-repair: 4 healthy, 0 unhealthy" in lines,out)
3257         d.addCallback(_check6)
3258
3259         # now add a subdir, and a file below that, then make the subdir
3260         # unrecoverable
3261
3262         d.addCallback(lambda ign: self.rootnode.create_subdirectory(u"subdir"))
3263         d.addCallback(_stash_uri, "subdir")
3264         d.addCallback(lambda fn:
3265                       fn.add_file(u"subfile", upload.Data(DATA+"2", "")))
3266         d.addCallback(lambda ign:
3267                       self.delete_shares_numbered(self.uris["subdir"],
3268                                                   range(10)))
3269
3270         # root
3271         # rootg\u00F6\u00F6d/
3272         # root/small
3273         # root/mutable
3274         # root/subdir [unrecoverable: 0 shares]
3275         # root/subfile
3276
3277         d.addCallback(lambda ign: self.do_cli("manifest", self.rooturi))
3278         def _manifest_failed((rc, out, err)):
3279             self.failIfEqual(rc, 0)
3280             self.failUnlessIn("ERROR: UnrecoverableFileError", err)
3281             # the fatal directory should still show up, as the last line
3282             self.failUnlessIn(" subdir\n", out)
3283         d.addCallback(_manifest_failed)
3284
3285         d.addCallback(lambda ign: self.do_cli("deep-check", self.rooturi))
3286         def _deep_check_failed((rc, out, err)):
3287             self.failIfEqual(rc, 0)
3288             self.failUnlessIn("ERROR: UnrecoverableFileError", err)
3289             # we want to make sure that the error indication is the last
3290             # thing that gets emitted
3291             self.failIf("done:" in out, out)
3292         d.addCallback(_deep_check_failed)
3293
3294         # this test is disabled until the deep-repair response to an
3295         # unrepairable directory is fixed. The failure-to-repair should not
3296         # throw an exception, but the failure-to-traverse that follows
3297         # should throw UnrecoverableFileError.
3298
3299         #d.addCallback(lambda ign:
3300         #              self.do_cli("deep-check", "--repair", self.rooturi))
3301         #def _deep_check_repair_failed((rc, out, err)):
3302         #    self.failIfEqual(rc, 0)
3303         #    print err
3304         #    self.failUnlessIn("ERROR: UnrecoverableFileError", err)
3305         #    self.failIf("done:" in out, out)
3306         #d.addCallback(_deep_check_repair_failed)
3307
3308         return d
3309
3310     def test_check_without_alias(self):
3311         # 'tahoe check' should output a sensible error message if it needs to
3312         # find the default alias and can't
3313         self.basedir = "cli/Check/check_without_alias"
3314         self.set_up_grid()
3315         d = self.do_cli("check")
3316         def _check((rc, out, err)):
3317             self.failUnlessReallyEqual(rc, 1)
3318             self.failUnlessIn("error:", err)
3319             self.failUnlessReallyEqual(out, "")
3320         d.addCallback(_check)
3321         d.addCallback(lambda ign: self.do_cli("deep-check"))
3322         d.addCallback(_check)
3323         return d
3324
3325     def test_check_with_nonexistent_alias(self):
3326         # 'tahoe check' should output a sensible error message if it needs to
3327         # find an alias and can't.
3328         self.basedir = "cli/Check/check_with_nonexistent_alias"
3329         self.set_up_grid()
3330         d = self.do_cli("check", "nonexistent:")
3331         def _check((rc, out, err)):
3332             self.failUnlessReallyEqual(rc, 1)
3333             self.failUnlessIn("error:", err)
3334             self.failUnlessIn("nonexistent", err)
3335             self.failUnlessReallyEqual(out, "")
3336         d.addCallback(_check)
3337         return d
3338
3339     def test_check_with_multiple_aliases(self):
3340         self.basedir = "cli/Check/check_with_multiple_aliases"
3341         self.set_up_grid()
3342         self.uriList = []
3343         c0 = self.g.clients[0]
3344         d = c0.create_dirnode()
3345         def _stash_uri(n):
3346             self.uriList.append(n.get_uri()) 
3347         d.addCallback(_stash_uri)
3348         d = c0.create_dirnode()
3349         d.addCallback(_stash_uri)
3350         
3351         d.addCallback(lambda ign: self.do_cli("check", self.uriList[0], self.uriList[1]))
3352         def _check((rc, out, err)):
3353             self.failUnlessReallyEqual(rc, 0)
3354             self.failUnlessReallyEqual(err, "")
3355             #Ensure healthy appears for each uri
3356             self.failUnlessIn("Healthy", out[:len(out)/2])
3357             self.failUnlessIn("Healthy", out[len(out)/2:])
3358         d.addCallback(_check)
3359         
3360         d.addCallback(lambda ign: self.do_cli("check", self.uriList[0], "nonexistent:"))
3361         def _check2((rc, out, err)):
3362             self.failUnlessReallyEqual(rc, 1)
3363             self.failUnlessIn("Healthy", out)
3364             self.failUnlessIn("error:", err)
3365             self.failUnlessIn("nonexistent", err)
3366         d.addCallback(_check2)
3367         
3368         return d
3369
3370
3371 class Errors(GridTestMixin, CLITestMixin, unittest.TestCase):
3372     def test_get(self):
3373         self.basedir = "cli/Errors/get"
3374         self.set_up_grid()
3375         c0 = self.g.clients[0]
3376         self.fileurls = {}
3377         DATA = "data" * 100
3378         d = c0.upload(upload.Data(DATA, convergence=""))
3379         def _stash_bad(ur):
3380             self.uri_1share = ur.get_uri()
3381             self.delete_shares_numbered(ur.get_uri(), range(1,10))
3382         d.addCallback(_stash_bad)
3383
3384         # the download is abandoned as soon as it's clear that we won't get
3385         # enough shares. The one remaining share might be in either the
3386         # COMPLETE or the PENDING state.
3387         in_complete_msg = "ran out of shares: complete=sh0 pending= overdue= unused= need 3"
3388         in_pending_msg = "ran out of shares: complete= pending=Share(sh0-on-fob7vqgd) overdue= unused= need 3"
3389
3390         d.addCallback(lambda ign: self.do_cli("get", self.uri_1share))
3391         def _check1((rc, out, err)):
3392             self.failIfEqual(rc, 0)
3393             self.failUnless("410 Gone" in err, err)
3394             self.failUnlessIn("NotEnoughSharesError: ", err)
3395             self.failUnless(in_complete_msg in err or in_pending_msg in err,
3396                             err)
3397         d.addCallback(_check1)
3398
3399         targetf = os.path.join(self.basedir, "output")
3400         d.addCallback(lambda ign: self.do_cli("get", self.uri_1share, targetf))
3401         def _check2((rc, out, err)):
3402             self.failIfEqual(rc, 0)
3403             self.failUnless("410 Gone" in err, err)
3404             self.failUnlessIn("NotEnoughSharesError: ", err)
3405             self.failUnless(in_complete_msg in err or in_pending_msg in err,
3406                             err)
3407             self.failIf(os.path.exists(targetf))
3408         d.addCallback(_check2)
3409
3410         return d
3411
3412     def test_broken_socket(self):
3413         # When the http connection breaks (such as when node.url is overwritten
3414         # by a confused user), a user friendly error message should be printed.
3415         self.basedir = "cli/Errors/test_broken_socket"
3416         self.set_up_grid()
3417
3418         # Simulate a connection error
3419         def _socket_error(*args, **kwargs):
3420             raise socket_error('test error')
3421         self.patch(allmydata.scripts.common_http.httplib.HTTPConnection,
3422                    "endheaders", _socket_error)
3423
3424         d = self.do_cli("mkdir")
3425         def _check_invalid((rc,stdout,stderr)):
3426             self.failIfEqual(rc, 0)
3427             self.failUnlessIn("Error trying to connect to http://127.0.0.1", stderr)
3428         d.addCallback(_check_invalid)
3429         return d
3430
3431
3432 class Get(GridTestMixin, CLITestMixin, unittest.TestCase):
3433     def test_get_without_alias(self):
3434         # 'tahoe get' should output a useful error message when invoked
3435         # without an explicit alias and when the default 'tahoe' alias
3436         # hasn't been created yet.
3437         self.basedir = "cli/Get/get_without_alias"
3438         self.set_up_grid()
3439         d = self.do_cli('get', 'file')
3440         def _check((rc, out, err)):
3441             self.failUnlessReallyEqual(rc, 1)
3442             self.failUnlessIn("error:", err)
3443             self.failUnlessReallyEqual(out, "")
3444         d.addCallback(_check)
3445         return d
3446
3447     def test_get_with_nonexistent_alias(self):
3448         # 'tahoe get' should output a useful error message when invoked with
3449         # an explicit alias that doesn't exist.
3450         self.basedir = "cli/Get/get_with_nonexistent_alias"
3451         self.set_up_grid()
3452         d = self.do_cli("get", "nonexistent:file")
3453         def _check((rc, out, err)):
3454             self.failUnlessReallyEqual(rc, 1)
3455             self.failUnlessIn("error:", err)
3456             self.failUnlessIn("nonexistent", err)
3457             self.failUnlessReallyEqual(out, "")
3458         d.addCallback(_check)
3459         return d
3460
3461
3462 class Manifest(GridTestMixin, CLITestMixin, unittest.TestCase):
3463     def test_manifest_without_alias(self):
3464         # 'tahoe manifest' should output a useful error message when invoked
3465         # without an explicit alias when the default 'tahoe' alias is
3466         # missing.
3467         self.basedir = "cli/Manifest/manifest_without_alias"
3468         self.set_up_grid()
3469         d = self.do_cli("manifest")
3470         def _check((rc, out, err)):
3471             self.failUnlessReallyEqual(rc, 1)
3472             self.failUnlessIn("error:", err)
3473             self.failUnlessReallyEqual(out, "")
3474         d.addCallback(_check)
3475         return d
3476
3477     def test_manifest_with_nonexistent_alias(self):
3478         # 'tahoe manifest' should output a useful error message when invoked
3479         # with an explicit alias that doesn't exist.
3480         self.basedir = "cli/Manifest/manifest_with_nonexistent_alias"
3481         self.set_up_grid()
3482         d = self.do_cli("manifest", "nonexistent:")
3483         def _check((rc, out, err)):
3484             self.failUnlessReallyEqual(rc, 1)
3485             self.failUnlessIn("error:", err)
3486             self.failUnlessIn("nonexistent", err)
3487             self.failUnlessReallyEqual(out, "")
3488         d.addCallback(_check)
3489         return d
3490
3491
3492 class Mkdir(GridTestMixin, CLITestMixin, unittest.TestCase):
3493     def test_mkdir(self):
3494         self.basedir = os.path.dirname(self.mktemp())
3495         self.set_up_grid()
3496
3497         d = self.do_cli("create-alias", "tahoe")
3498         d.addCallback(lambda res: self.do_cli("mkdir", "test"))
3499         def _check((rc, out, err)):
3500             self.failUnlessReallyEqual(rc, 0)
3501             self.failUnlessReallyEqual(err, "")
3502             self.failUnlessIn("URI:", out)
3503         d.addCallback(_check)
3504
3505         return d
3506
3507     def test_mkdir_mutable_type(self):
3508         self.basedir = os.path.dirname(self.mktemp())
3509         self.set_up_grid()
3510         d = self.do_cli("create-alias", "tahoe")
3511         def _check((rc, out, err), st):
3512             self.failUnlessReallyEqual(rc, 0)
3513             self.failUnlessReallyEqual(err, "")
3514             self.failUnlessIn(st, out)
3515             return out
3516         def _mkdir(ign, mutable_type, uri_prefix, dirname):
3517             d2 = self.do_cli("mkdir", "--format="+mutable_type, dirname)
3518             d2.addCallback(_check, uri_prefix)
3519             def _stash_filecap(cap):
3520                 u = uri.from_string(cap)
3521                 fn_uri = u.get_filenode_cap()
3522                 self._filecap = fn_uri.to_string()
3523             d2.addCallback(_stash_filecap)
3524             d2.addCallback(lambda ign: self.do_cli("ls", "--json", dirname))
3525             d2.addCallback(_check, uri_prefix)
3526             d2.addCallback(lambda ign: self.do_cli("ls", "--json", self._filecap))
3527             d2.addCallback(_check, '"format": "%s"' % (mutable_type.upper(),))
3528             return d2
3529
3530         d.addCallback(_mkdir, "sdmf", "URI:DIR2", "tahoe:foo")
3531         d.addCallback(_mkdir, "SDMF", "URI:DIR2", "tahoe:foo2")
3532         d.addCallback(_mkdir, "mdmf", "URI:DIR2-MDMF", "tahoe:bar")
3533         d.addCallback(_mkdir, "MDMF", "URI:DIR2-MDMF", "tahoe:bar2")
3534         return d
3535
3536     def test_mkdir_mutable_type_unlinked(self):
3537         self.basedir = os.path.dirname(self.mktemp())
3538         self.set_up_grid()
3539         d = self.do_cli("mkdir", "--format=SDMF")
3540         def _check((rc, out, err), st):
3541             self.failUnlessReallyEqual(rc, 0)
3542             self.failUnlessReallyEqual(err, "")
3543             self.failUnlessIn(st, out)
3544             return out
3545         d.addCallback(_check, "URI:DIR2")
3546         def _stash_dircap(cap):
3547             self._dircap = cap
3548             # Now we're going to feed the cap into uri.from_string...
3549             u = uri.from_string(cap)
3550             # ...grab the underlying filenode uri.
3551             fn_uri = u.get_filenode_cap()
3552             # ...and stash that.
3553             self._filecap = fn_uri.to_string()
3554         d.addCallback(_stash_dircap)
3555         d.addCallback(lambda res: self.do_cli("ls", "--json",
3556                                               self._filecap))
3557         d.addCallback(_check, '"format": "SDMF"')
3558         d.addCallback(lambda res: self.do_cli("mkdir", "--format=MDMF"))
3559         d.addCallback(_check, "URI:DIR2-MDMF")
3560         d.addCallback(_stash_dircap)
3561         d.addCallback(lambda res: self.do_cli("ls", "--json",
3562                                               self._filecap))
3563         d.addCallback(_check, '"format": "MDMF"')
3564         return d
3565
3566     def test_mkdir_bad_mutable_type(self):
3567         o = cli.MakeDirectoryOptions()
3568         self.failUnlessRaises(usage.UsageError,
3569                               o.parseOptions,
3570                               ["--format=LDMF"])
3571
3572     def test_mkdir_unicode(self):
3573         self.basedir = os.path.dirname(self.mktemp())
3574         self.set_up_grid()
3575
3576         try:
3577             motorhead_arg = u"tahoe:Mot\u00F6rhead".encode(get_io_encoding())
3578         except UnicodeEncodeError:
3579             raise unittest.SkipTest("A non-ASCII command argument could not be encoded on this platform.")
3580
3581         d = self.do_cli("create-alias", "tahoe")
3582         d.addCallback(lambda res: self.do_cli("mkdir", motorhead_arg))
3583         def _check((rc, out, err)):
3584             self.failUnlessReallyEqual(rc, 0)
3585             self.failUnlessReallyEqual(err, "")
3586             self.failUnlessIn("URI:", out)
3587         d.addCallback(_check)
3588
3589         return d
3590
3591     def test_mkdir_with_nonexistent_alias(self):
3592         # when invoked with an alias that doesn't exist, 'tahoe mkdir' should
3593         # output a sensible error message rather than a stack trace.
3594         self.basedir = "cli/Mkdir/mkdir_with_nonexistent_alias"
3595         self.set_up_grid()
3596         d = self.do_cli("mkdir", "havasu:")
3597         def _check((rc, out, err)):
3598             self.failUnlessReallyEqual(rc, 1)
3599             self.failUnlessIn("error:", err)
3600             self.failUnlessReallyEqual(out, "")
3601         d.addCallback(_check)
3602         return d
3603
3604
3605 class Unlink(GridTestMixin, CLITestMixin, unittest.TestCase):
3606     command = "unlink"
3607
3608     def _create_test_file(self):
3609         data = "puppies" * 1000
3610         path = os.path.join(self.basedir, "datafile")
3611         fileutil.write(path, data)
3612         self.datafile = path
3613
3614     def test_unlink_without_alias(self):
3615         # 'tahoe unlink' should behave sensibly when invoked without an explicit
3616         # alias before the default 'tahoe' alias has been created.
3617         self.basedir = "cli/Unlink/%s_without_alias" % (self.command,)
3618         self.set_up_grid()
3619         d = self.do_cli(self.command, "afile")
3620         def _check((rc, out, err)):
3621             self.failUnlessReallyEqual(rc, 1)
3622             self.failUnlessIn("error:", err)
3623             self.failUnlessReallyEqual(out, "")
3624         d.addCallback(_check)
3625
3626         d.addCallback(lambda ign: self.do_cli(self.command, "afile"))
3627         d.addCallback(_check)
3628         return d
3629
3630     def test_unlink_with_nonexistent_alias(self):
3631         # 'tahoe unlink' should behave sensibly when invoked with an explicit
3632         # alias that doesn't exist.
3633         self.basedir = "cli/Unlink/%s_with_nonexistent_alias" % (self.command,)
3634         self.set_up_grid()
3635         d = self.do_cli(self.command, "nonexistent:afile")
3636         def _check((rc, out, err)):
3637             self.failUnlessReallyEqual(rc, 1)
3638             self.failUnlessIn("error:", err)
3639             self.failUnlessIn("nonexistent", err)
3640             self.failUnlessReallyEqual(out, "")
3641         d.addCallback(_check)
3642
3643         d.addCallback(lambda ign: self.do_cli(self.command, "nonexistent:afile"))
3644         d.addCallback(_check)
3645         return d
3646
3647     def test_unlink_without_path(self):
3648         # 'tahoe unlink' should give a sensible error message when invoked without a path.
3649         self.basedir = "cli/Unlink/%s_without_path" % (self.command,)
3650         self.set_up_grid()
3651         self._create_test_file()
3652         d = self.do_cli("create-alias", "tahoe")
3653         d.addCallback(lambda ign: self.do_cli("put", self.datafile, "tahoe:test"))
3654         def _do_unlink((rc, out, err)):
3655             self.failUnlessReallyEqual(rc, 0)
3656             self.failUnless(out.startswith("URI:"), out)
3657             return self.do_cli(self.command, out.strip('\n'))
3658         d.addCallback(_do_unlink)
3659
3660         def _check((rc, out, err)):
3661             self.failUnlessReallyEqual(rc, 1)
3662             self.failUnlessIn("'tahoe %s'" % (self.command,), err)
3663             self.failUnlessIn("path must be given", err)
3664             self.failUnlessReallyEqual(out, "")
3665         d.addCallback(_check)
3666         return d
3667
3668
3669 class Rm(Unlink):
3670     """Test that 'tahoe rm' behaves in the same way as 'tahoe unlink'."""
3671     command = "rm"
3672
3673
3674 class Stats(GridTestMixin, CLITestMixin, unittest.TestCase):
3675     def test_empty_directory(self):
3676         self.basedir = "cli/Stats/empty_directory"
3677         self.set_up_grid()
3678         c0 = self.g.clients[0]
3679         self.fileurls = {}
3680         d = c0.create_dirnode()
3681         def _stash_root(n):
3682             self.rootnode = n
3683             self.rooturi = n.get_uri()
3684         d.addCallback(_stash_root)
3685
3686         # make sure we can get stats on an empty directory too
3687         d.addCallback(lambda ign: self.do_cli("stats", self.rooturi))
3688         def _check_stats((rc, out, err)):
3689             self.failUnlessReallyEqual(err, "")
3690             self.failUnlessReallyEqual(rc, 0)
3691             lines = out.splitlines()
3692             self.failUnlessIn(" count-immutable-files: 0", lines)
3693             self.failUnlessIn("   count-mutable-files: 0", lines)
3694             self.failUnlessIn("   count-literal-files: 0", lines)
3695             self.failUnlessIn("     count-directories: 1", lines)
3696             self.failUnlessIn("  size-immutable-files: 0", lines)
3697             self.failIfIn("Size Histogram:", lines)
3698         d.addCallback(_check_stats)
3699
3700         return d
3701
3702     def test_stats_without_alias(self):
3703         # when invoked with no explicit alias and before the default 'tahoe'
3704         # alias is created, 'tahoe stats' should output an informative error
3705         # message, not a stack trace.
3706         self.basedir = "cli/Stats/stats_without_alias"
3707         self.set_up_grid()
3708         d = self.do_cli("stats")
3709         def _check((rc, out, err)):
3710             self.failUnlessReallyEqual(rc, 1)
3711             self.failUnlessIn("error:", err)
3712             self.failUnlessReallyEqual(out, "")
3713         d.addCallback(_check)
3714         return d
3715
3716     def test_stats_with_nonexistent_alias(self):
3717         # when invoked with an explicit alias that doesn't exist,
3718         # 'tahoe stats' should output a useful error message.
3719         self.basedir = "cli/Stats/stats_with_nonexistent_alias"
3720         self.set_up_grid()
3721         d = self.do_cli("stats", "havasu:")
3722         def _check((rc, out, err)):
3723             self.failUnlessReallyEqual(rc, 1)
3724             self.failUnlessIn("error:", err)
3725             self.failUnlessReallyEqual(out, "")
3726         d.addCallback(_check)
3727         return d
3728
3729
3730 class Webopen(GridTestMixin, CLITestMixin, unittest.TestCase):
3731     def test_webopen_with_nonexistent_alias(self):
3732         # when invoked with an alias that doesn't exist, 'tahoe webopen'
3733         # should output an informative error message instead of a stack
3734         # trace.
3735         self.basedir = "cli/Webopen/webopen_with_nonexistent_alias"
3736         self.set_up_grid()
3737         d = self.do_cli("webopen", "fake:")
3738         def _check((rc, out, err)):
3739             self.failUnlessReallyEqual(rc, 1)
3740             self.failUnlessIn("error:", err)
3741             self.failUnlessReallyEqual(out, "")
3742         d.addCallback(_check)
3743         return d
3744
3745     def test_webopen(self):
3746         # TODO: replace with @patch that supports Deferreds.
3747         import webbrowser
3748         def call_webbrowser_open(url):
3749             self.failUnlessIn(self.alias_uri.replace(':', '%3A'), url)
3750             self.webbrowser_open_called = True
3751         def _cleanup(res):
3752             webbrowser.open = self.old_webbrowser_open
3753             return res
3754
3755         self.old_webbrowser_open = webbrowser.open
3756         try:
3757             webbrowser.open = call_webbrowser_open
3758
3759             self.basedir = "cli/Webopen/webopen"
3760             self.set_up_grid()
3761             d = self.do_cli("create-alias", "alias:")
3762             def _check_alias((rc, out, err)):
3763                 self.failUnlessReallyEqual(rc, 0, repr((rc, out, err)))
3764                 self.failUnlessIn("Alias 'alias' created", out)
3765                 self.failUnlessReallyEqual(err, "")
3766                 self.alias_uri = get_aliases(self.get_clientdir())["alias"]
3767             d.addCallback(_check_alias)
3768             d.addCallback(lambda res: self.do_cli("webopen", "alias:"))
3769             def _check_webopen((rc, out, err)):
3770                 self.failUnlessReallyEqual(rc, 0, repr((rc, out, err)))
3771                 self.failUnlessReallyEqual(out, "")
3772                 self.failUnlessReallyEqual(err, "")
3773                 self.failUnless(self.webbrowser_open_called)
3774             d.addCallback(_check_webopen)
3775             d.addBoth(_cleanup)
3776         except:
3777             _cleanup(None)
3778             raise
3779         return d
3780
3781 class Options(unittest.TestCase):
3782     # this test case only looks at argument-processing and simple stuff.
3783
3784     def parse(self, args, stdout=None):
3785         o = runner.Options()
3786         if stdout is not None:
3787             o.stdout = stdout
3788         o.parseOptions(args)
3789         while hasattr(o, "subOptions"):
3790             o = o.subOptions
3791         return o
3792
3793     def test_list(self):
3794         fileutil.rm_dir("cli/test_options")
3795         fileutil.make_dirs("cli/test_options")
3796         fileutil.make_dirs("cli/test_options/private")
3797         fileutil.write("cli/test_options/node.url", "http://localhost:8080/\n")
3798         filenode_uri = uri.WriteableSSKFileURI(writekey="\x00"*16,
3799                                                fingerprint="\x00"*32)
3800         private_uri = uri.DirectoryURI(filenode_uri).to_string()
3801         fileutil.write("cli/test_options/private/root_dir.cap", private_uri + "\n")
3802         def parse2(args): return parse_options("cli/test_options", "ls", args)
3803         o = parse2([])
3804         self.failUnlessEqual(o['node-url'], "http://localhost:8080/")
3805         self.failUnlessEqual(o.aliases[DEFAULT_ALIAS], private_uri)
3806         self.failUnlessEqual(o.where, u"")
3807
3808         o = parse2(["--node-url", "http://example.org:8111/"])
3809         self.failUnlessEqual(o['node-url'], "http://example.org:8111/")
3810         self.failUnlessEqual(o.aliases[DEFAULT_ALIAS], private_uri)
3811         self.failUnlessEqual(o.where, u"")
3812
3813         o = parse2(["--dir-cap", "root"])
3814         self.failUnlessEqual(o['node-url'], "http://localhost:8080/")
3815         self.failUnlessEqual(o.aliases[DEFAULT_ALIAS], "root")
3816         self.failUnlessEqual(o.where, u"")
3817
3818         other_filenode_uri = uri.WriteableSSKFileURI(writekey="\x11"*16,
3819                                                      fingerprint="\x11"*32)
3820         other_uri = uri.DirectoryURI(other_filenode_uri).to_string()
3821         o = parse2(["--dir-cap", other_uri])
3822         self.failUnlessEqual(o['node-url'], "http://localhost:8080/")
3823         self.failUnlessEqual(o.aliases[DEFAULT_ALIAS], other_uri)
3824         self.failUnlessEqual(o.where, u"")
3825
3826         o = parse2(["--dir-cap", other_uri, "subdir"])
3827         self.failUnlessEqual(o['node-url'], "http://localhost:8080/")
3828         self.failUnlessEqual(o.aliases[DEFAULT_ALIAS], other_uri)
3829         self.failUnlessEqual(o.where, u"subdir")
3830
3831         self.failUnlessRaises(usage.UsageError, parse2,
3832                               ["--node-url", "NOT-A-URL"])
3833
3834         o = parse2(["--node-url", "http://localhost:8080"])
3835         self.failUnlessEqual(o["node-url"], "http://localhost:8080/")
3836
3837         o = parse2(["--node-url", "https://localhost/"])
3838         self.failUnlessEqual(o["node-url"], "https://localhost/")
3839
3840     def test_version(self):
3841         # "tahoe --version" dumps text to stdout and exits
3842         stdout = StringIO()
3843         self.failUnlessRaises(SystemExit, self.parse, ["--version"], stdout)
3844         self.failUnlessIn("allmydata-tahoe", stdout.getvalue())
3845         # but "tahoe SUBCOMMAND --version" should be rejected
3846         self.failUnlessRaises(usage.UsageError, self.parse,
3847                               ["start", "--version"])
3848         self.failUnlessRaises(usage.UsageError, self.parse,
3849                               ["start", "--version-and-path"])
3850
3851     def test_quiet(self):
3852         # accepted as an overall option, but not on subcommands
3853         o = self.parse(["--quiet", "start"])
3854         self.failUnless(o.parent["quiet"])
3855         self.failUnlessRaises(usage.UsageError, self.parse,
3856                               ["start", "--quiet"])
3857
3858     def test_basedir(self):
3859         # accept a --node-directory option before the verb, or a --basedir
3860         # option after, or a basedir argument after, but none in the wrong
3861         # place, and not more than one of the three.
3862         o = self.parse(["start"])
3863         self.failUnlessEqual(o["basedir"], os.path.join(os.path.expanduser("~"),
3864                                                         ".tahoe"))
3865         o = self.parse(["start", "here"])
3866         self.failUnlessEqual(o["basedir"], os.path.abspath("here"))
3867         o = self.parse(["start", "--basedir", "there"])
3868         self.failUnlessEqual(o["basedir"], os.path.abspath("there"))
3869         o = self.parse(["--node-directory", "there", "start"])
3870         self.failUnlessEqual(o["basedir"], os.path.abspath("there"))
3871
3872         self.failUnlessRaises(usage.UsageError, self.parse,
3873                               ["--basedir", "there", "start"])
3874         self.failUnlessRaises(usage.UsageError, self.parse,
3875                               ["start", "--node-directory", "there"])
3876
3877         self.failUnlessRaises(usage.UsageError, self.parse,
3878                               ["--node-directory=there",
3879                                "start", "--basedir=here"])
3880         self.failUnlessRaises(usage.UsageError, self.parse,
3881                               ["start", "--basedir=here", "anywhere"])
3882         self.failUnlessRaises(usage.UsageError, self.parse,
3883                               ["--node-directory=there",
3884                                "start", "anywhere"])
3885         self.failUnlessRaises(usage.UsageError, self.parse,
3886                               ["--node-directory=there",
3887                                "start", "--basedir=here", "anywhere"])
3888