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