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