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