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