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