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