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