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