/
test_web.py
4877 lines (4390 loc) · 217 KB
/
test_web.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Ported to Python 3.
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from future.utils import PY2
if PY2:
from future.builtins import filter, map, zip, ascii, chr, hex, input, next, oct, open, pow, round, super, bytes, dict, list, object, range, str, max, min # noqa: F401
from six import ensure_binary
import os.path, re, time
import treq
from urllib.parse import quote as urlquote, unquote as urlunquote
from bs4 import BeautifulSoup
from twisted.python.filepath import (
FilePath,
)
from twisted.application import service
from twisted.internet import defer
from twisted.internet.defer import inlineCallbacks, returnValue
from twisted.internet.task import Clock
from twisted.web import client, error, http
from twisted.python import failure, log
from allmydata import interfaces, uri, webish
from allmydata.storage_client import StorageFarmBroker, StubServer
from allmydata.immutable import upload
from allmydata.immutable.downloader.status import DownloadStatus
from allmydata.dirnode import DirectoryNode
from allmydata.nodemaker import NodeMaker
from allmydata.web.common import MultiFormatResource
from allmydata.util import fileutil, base32, hashutil, jsonbytes as json
from allmydata.util.consumer import download_to_data
from allmydata.util.encodingutil import to_bytes
from ...util.connection_status import ConnectionStatus
from ..common import (
EMPTY_CLIENT_CONFIG,
FakeCHKFileNode,
FakeMutableFileNode,
create_chk_filenode,
WebErrorMixin,
make_mutable_file_uri,
create_mutable_filenode,
TrialTestCase,
)
from .common import (
assert_soup_has_favicon,
assert_soup_has_text,
assert_soup_has_tag_with_attributes,
assert_soup_has_tag_with_content,
assert_soup_has_tag_with_attributes_and_content,
unknown_rwcap,
unknown_rocap,
unknown_immcap,
)
from allmydata.interfaces import (
IMutableFileNode, SDMF_VERSION, MDMF_VERSION,
FileTooLargeError,
MustBeReadonlyError,
)
from allmydata.mutable import servermap, publish, retrieve
from .. import common_util as testutil
from ..common_util import TimezoneMixin
from ..common_web import (
do_http,
Error,
render,
)
from ...web.common import (
humanize_exception,
)
from allmydata.client import _Client, SecretHolder
# create a fake uploader/downloader, and a couple of fake dirnodes, then
# create a webserver that works against them
class FakeStatsProvider(object):
def get_stats(self):
stats = {'stats': {}, 'counters': {}}
return stats
class FakeNodeMaker(NodeMaker):
encoding_params = {
'k': 3,
'n': 10,
'happy': 7,
'max_segment_size':128*1024 # 1024=KiB
}
def _create_lit(self, cap):
return FakeCHKFileNode(cap, self.all_contents)
def _create_immutable(self, cap):
return FakeCHKFileNode(cap, self.all_contents)
def _create_mutable(self, cap):
return FakeMutableFileNode(None, None,
self.encoding_params, None,
self.all_contents).init_from_cap(cap)
def create_mutable_file(self, contents=b"", keysize=None,
version=SDMF_VERSION):
n = FakeMutableFileNode(None, None, self.encoding_params, None,
self.all_contents)
return n.create(contents, version=version)
class FakeUploader(service.Service):
name = "uploader" # type: ignore # https://twistedmatrix.com/trac/ticket/10135
helper_furl = None
helper_connected = False
def upload(self, uploadable, **kw):
d = uploadable.get_size()
d.addCallback(lambda size: uploadable.read(size))
def _got_data(datav):
data = b"".join(datav)
n = create_chk_filenode(data, self.all_contents)
ur = upload.UploadResults(file_size=len(data),
ciphertext_fetched=0,
preexisting_shares=0,
pushed_shares=10,
sharemap={},
servermap={},
timings={},
uri_extension_data={},
uri_extension_hash=b"fake",
verifycapstr=b"fakevcap")
ur.set_uri(n.get_uri())
return ur
d.addCallback(_got_data)
return d
def get_helper_info(self):
return (self.helper_furl, self.helper_connected)
def build_one_ds():
ds = DownloadStatus(b"storage_index", 1234)
now = time.time()
serverA = StubServer(hashutil.tagged_hash(b"foo", b"serverid_a")[:20])
serverB = StubServer(hashutil.tagged_hash(b"foo", b"serverid_b")[:20])
storage_index = hashutil.storage_index_hash(b"SI")
e0 = ds.add_segment_request(0, now)
e0.activate(now+0.5)
e0.deliver(now+1, 0, 100, 0.5) # when, start,len, decodetime
e1 = ds.add_segment_request(1, now+2)
e1.error(now+3)
# two outstanding requests
e2 = ds.add_segment_request(2, now+4)
e3 = ds.add_segment_request(3, now+5)
del e2,e3 # hush pyflakes
# simulate a segment which gets delivered faster than a system clock tick (ticket #1166)
e = ds.add_segment_request(4, now)
e.activate(now)
e.deliver(now, 0, 140, 0.5)
e = ds.add_dyhb_request(serverA, now)
e.finished([1,2], now+1)
e = ds.add_dyhb_request(serverB, now+2) # left unfinished
e = ds.add_read_event(0, 120, now)
e.update(60, 0.5, 0.1) # bytes, decrypttime, pausetime
e.finished(now+1)
e = ds.add_read_event(120, 30, now+2) # left unfinished
e = ds.add_block_request(serverA, 1, 100, 20, now)
e.finished(20, now+1)
e = ds.add_block_request(serverB, 1, 120, 30, now+1) # left unfinished
# make sure that add_read_event() can come first too
ds1 = DownloadStatus(storage_index, 1234)
e = ds1.add_read_event(0, 120, now)
e.update(60, 0.5, 0.1) # bytes, decrypttime, pausetime
e.finished(now+1)
return ds
class FakeHistory(object):
_all_upload_status = [upload.UploadStatus()]
_all_download_status = [build_one_ds()]
_all_mapupdate_statuses = [servermap.UpdateStatus()]
_all_publish_statuses = [publish.PublishStatus()]
_all_retrieve_statuses = [retrieve.RetrieveStatus()]
def list_all_upload_statuses(self):
return self._all_upload_status
def list_all_download_statuses(self):
return self._all_download_status
def list_all_mapupdate_statuses(self):
return self._all_mapupdate_statuses
def list_all_publish_statuses(self):
return self._all_publish_statuses
def list_all_retrieve_statuses(self):
return self._all_retrieve_statuses
def list_all_helper_statuses(self):
return []
class FakeDisplayableServer(StubServer): # type: ignore # tahoe-lafs/ticket/3573
def __init__(self, serverid, nickname, connected,
last_connect_time, last_loss_time, last_rx_time):
StubServer.__init__(self, serverid)
self.announcement = {"my-version": "tahoe-lafs-fake",
"service-name": "storage",
"nickname": nickname}
self.connected = connected
self.last_loss_time = last_loss_time
self.last_rx_time = last_rx_time
self.last_connect_time = last_connect_time
def on_status_changed(self, cb): # TODO: try to remove me
cb(self)
def is_connected(self): # TODO: remove me
return self.connected
def get_version(self):
return {
b"application-version": b"1.0"
}
def get_permutation_seed(self):
return b""
def get_announcement(self):
return self.announcement
def get_nickname(self):
return self.announcement["nickname"]
def get_available_space(self):
return 123456
def get_connection_status(self):
return ConnectionStatus(self.connected, "summary", {},
self.last_connect_time, self.last_rx_time)
class FakeBucketCounter(object):
def get_state(self):
return {"last-complete-bucket-count": 0}
def get_progress(self):
return {"estimated-time-per-cycle": 0,
"cycle-in-progress": False,
"remaining-wait-time": 0}
class FakeLeaseChecker(object):
def __init__(self):
self.expiration_enabled = False
self.mode = "age"
self.override_lease_duration = None
self.sharetypes_to_expire = {}
def get_state(self):
return {"history": None}
def get_progress(self):
return {"estimated-time-per-cycle": 0,
"cycle-in-progress": False,
"remaining-wait-time": 0}
class FakeStorageServer(service.MultiService):
name = 'storage' # type: ignore # https://twistedmatrix.com/trac/ticket/10135
def __init__(self, nodeid, nickname):
service.MultiService.__init__(self)
self.my_nodeid = nodeid
self.nickname = nickname
self.bucket_counter = FakeBucketCounter()
self.lease_checker = FakeLeaseChecker()
def get_stats(self):
return {"storage_server.accepting_immutable_shares": False}
def on_status_changed(self, cb):
cb(self)
class FakeClient(_Client): # type: ignore # tahoe-lafs/ticket/3573
def __init__(self):
# don't upcall to Client.__init__, since we only want to initialize a
# minimal subset
service.MultiService.__init__(self)
self.all_contents = {}
self.nodeid = b"fake_nodeid"
self.nickname = u"fake_nickname \u263A"
self.introducer_furls = []
self.introducer_clients = []
self.stats_provider = FakeStatsProvider()
self._secret_holder = SecretHolder(b"lease secret", b"convergence secret")
self.helper = None
self.convergence = b"some random string"
self.storage_broker = StorageFarmBroker(
permute_peers=True,
tub_maker=None,
node_config=EMPTY_CLIENT_CONFIG,
)
# fake knowledge of another server
self.storage_broker.test_add_server(b"other_nodeid",
FakeDisplayableServer(
serverid=b"other_nodeid", nickname=u"other_nickname \u263B", connected = True,
last_connect_time = 10, last_loss_time = 20, last_rx_time = 30))
self.storage_broker.test_add_server(b"disconnected_nodeid",
FakeDisplayableServer(
serverid=b"disconnected_nodeid", nickname=u"disconnected_nickname \u263B", connected = False,
last_connect_time = None, last_loss_time = 25, last_rx_time = 35))
self.introducer_client = None
self.history = FakeHistory()
self.uploader = FakeUploader()
self.uploader.all_contents = self.all_contents
self.uploader.setServiceParent(self)
self.blacklist = None
self.nodemaker = FakeNodeMaker(None, self._secret_holder, None,
self.uploader, None,
None, None, None)
self.nodemaker.all_contents = self.all_contents
self.mutable_file_default = SDMF_VERSION
self.addService(FakeStorageServer(self.nodeid, self.nickname))
def get_long_nodeid(self):
return b"v0-nodeid"
def get_long_tubid(self):
return u"tubid"
def get_auth_token(self):
return b'a fake debug auth token'
def startService(self):
return service.MultiService.startService(self)
def stopService(self):
return service.MultiService.stopService(self)
MUTABLE_SIZELIMIT = FakeMutableFileNode.MUTABLE_SIZELIMIT
class WebMixin(TimezoneMixin):
def setUp(self):
self.setTimezone('UTC-13:00')
self.s = FakeClient()
self.s.startService()
self.staticdir = self.mktemp()
self.clock = Clock()
self.fakeTime = 86460 # 1d 0h 1m 0s
tempdir = FilePath(self.mktemp())
tempdir.makedirs()
self.ws = webish.WebishServer(
self.s,
"0",
tempdir=tempdir.path,
staticdir=self.staticdir,
clock=self.clock,
now_fn=lambda:self.fakeTime,
)
self.ws.setServiceParent(self.s)
self.webish_port = self.ws.getPortnum()
self.webish_url = self.ws.getURL()
assert self.webish_url.endswith("/")
self.webish_url = self.webish_url[:-1] # these tests add their own /
l = [ self.s.create_dirnode() for x in range(6) ]
d = defer.DeferredList(l)
def _then(res):
self.public_root = res[0][1]
assert interfaces.IDirectoryNode.providedBy(self.public_root), res
self.public_url = "/uri/" + str(self.public_root.get_uri(), "ascii")
self.private_root = res[1][1]
foo = res[2][1]
self._foo_node = foo
self._foo_uri = foo.get_uri()
self._foo_readonly_uri = foo.get_readonly_uri()
self._foo_verifycap = foo.get_verify_cap().to_string()
# NOTE: we ignore the deferred on all set_uri() calls, because we
# know the fake nodes do these synchronously
self.public_root.set_uri(u"foo", foo.get_uri(),
foo.get_readonly_uri())
self.BAR_CONTENTS, n, self._bar_txt_uri = self.makefile(0)
foo.set_uri(u"bar.txt", self._bar_txt_uri, self._bar_txt_uri)
self._bar_txt_verifycap = n.get_verify_cap().to_string()
# sdmf
# XXX: Do we ever use this?
self.BAZ_CONTENTS, n, self._baz_txt_uri, self._baz_txt_readonly_uri = self.makefile_mutable(0)
foo.set_uri(u"baz.txt", self._baz_txt_uri, self._baz_txt_readonly_uri)
# mdmf
self.QUUX_CONTENTS, n, self._quux_txt_uri, self._quux_txt_readonly_uri = self.makefile_mutable(0, mdmf=True)
assert self._quux_txt_uri.startswith(b"URI:MDMF")
foo.set_uri(u"quux.txt", self._quux_txt_uri, self._quux_txt_readonly_uri)
foo.set_uri(u"empty", res[3][1].get_uri(),
res[3][1].get_readonly_uri())
sub_uri = res[4][1].get_uri()
self._sub_uri = sub_uri
foo.set_uri(u"sub", sub_uri, sub_uri)
sub = self.s.create_node_from_uri(sub_uri)
self._sub_node = sub
_ign, n, blocking_uri = self.makefile(1)
foo.set_uri(u"blockingfile", blocking_uri, blocking_uri)
# filenode to test for html encoding issues
self._htmlname_unicode = u"<&weirdly'named\"file>>>_<iframe />.txt"
self._htmlname_raw = self._htmlname_unicode.encode('utf-8')
self._htmlname_urlencoded = urlquote(self._htmlname_raw, '')
self.HTMLNAME_CONTENTS, n, self._htmlname_txt_uri = self.makefile(0)
foo.set_uri(self._htmlname_unicode, self._htmlname_txt_uri, self._htmlname_txt_uri)
unicode_filename = u"n\u00fc.txt" # n u-umlaut . t x t
# ok, unicode calls it LATIN SMALL LETTER U WITH DIAERESIS but I
# still think of it as an umlaut
foo.set_uri(unicode_filename, self._bar_txt_uri, self._bar_txt_uri)
self.SUBBAZ_CONTENTS, n, baz_file = self.makefile(2)
self._baz_file_uri = baz_file
sub.set_uri(u"baz.txt", baz_file, baz_file)
_ign, n, self._bad_file_uri = self.makefile(3)
# this uri should not be downloadable
del self.s.all_contents[self._bad_file_uri]
rodir = res[5][1]
self.public_root.set_uri(u"reedownlee", rodir.get_readonly_uri(),
rodir.get_readonly_uri())
rodir.set_uri(u"nor", baz_file, baz_file)
# public/
# public/foo/
# public/foo/bar.txt
# public/foo/baz.txt
# public/foo/quux.txt
# public/foo/blockingfile
# public/foo/<&weirdly'named\"file>>>_<iframe />.txt
# public/foo/empty/
# public/foo/sub/
# public/foo/sub/baz.txt
# public/reedownlee/
# public/reedownlee/nor
self.NEWFILE_CONTENTS = b"newfile contents\n"
return foo.get_metadata_for(u"bar.txt")
d.addCallback(_then)
def _got_metadata(metadata):
self._bar_txt_metadata = metadata
d.addCallback(_got_metadata)
return d
def get_all_contents(self):
return self.s.all_contents
def makefile(self, number):
contents = b"contents of file %d\n" % number
n = create_chk_filenode(contents, self.get_all_contents())
return contents, n, n.get_uri()
def makefile_mutable(self, number, mdmf=False):
contents = b"contents of mutable file %d\n" % number
n = create_mutable_filenode(contents, mdmf, self.s.all_contents)
return contents, n, n.get_uri(), n.get_readonly_uri()
def tearDown(self):
return self.s.stopService()
def failUnlessIsBarDotTxt(self, res):
self.failUnlessReallyEqual(res, self.BAR_CONTENTS, res)
def failUnlessIsQuuxDotTxt(self, res):
self.failUnlessReallyEqual(res, self.QUUX_CONTENTS, res)
def failUnlessIsBazDotTxt(self, res):
self.failUnlessReallyEqual(res, self.BAZ_CONTENTS, res)
def failUnlessIsSubBazDotTxt(self, res):
self.failUnlessReallyEqual(res, self.SUBBAZ_CONTENTS, res)
def failUnlessIsBarJSON(self, res):
data = json.loads(res)
self.failUnless(isinstance(data, list))
self.failUnlessEqual(data[0], "filenode")
self.failUnless(isinstance(data[1], dict))
self.failIf(data[1]["mutable"])
self.failIfIn("rw_uri", data[1]) # immutable
self.failUnlessReallyEqual(to_bytes(data[1]["ro_uri"]), self._bar_txt_uri)
self.failUnlessReallyEqual(to_bytes(data[1]["verify_uri"]), self._bar_txt_verifycap)
self.failUnlessReallyEqual(data[1]["size"], len(self.BAR_CONTENTS))
def failUnlessIsQuuxJSON(self, res, readonly=False):
data = json.loads(res)
self.failUnless(isinstance(data, list))
self.failUnlessEqual(data[0], "filenode")
self.failUnless(isinstance(data[1], dict))
metadata = data[1]
return self.failUnlessIsQuuxDotTxtMetadata(metadata, readonly)
def failUnlessIsQuuxDotTxtMetadata(self, metadata, readonly):
self.failUnless(metadata['mutable'])
if readonly:
self.failIfIn("rw_uri", metadata)
else:
self.failUnlessIn("rw_uri", metadata)
self.failUnlessEqual(metadata['rw_uri'], str(self._quux_txt_uri, "ascii"))
self.failUnlessIn("ro_uri", metadata)
self.failUnlessEqual(metadata['ro_uri'], str(self._quux_txt_readonly_uri, "ascii"))
self.failUnlessReallyEqual(metadata['size'], len(self.QUUX_CONTENTS))
def failUnlessIsFooJSON(self, res):
data = json.loads(res)
self.failUnless(isinstance(data, list))
self.failUnlessEqual(data[0], "dirnode", res)
self.failUnless(isinstance(data[1], dict))
self.failUnless(data[1]["mutable"])
self.failUnlessIn("rw_uri", data[1]) # mutable
self.failUnlessReallyEqual(to_bytes(data[1]["rw_uri"]), self._foo_uri)
self.failUnlessReallyEqual(to_bytes(data[1]["ro_uri"]), self._foo_readonly_uri)
self.failUnlessReallyEqual(to_bytes(data[1]["verify_uri"]), self._foo_verifycap)
kidnames = sorted([str(n) for n in data[1]["children"]])
self.failUnlessEqual(kidnames,
[self._htmlname_unicode, u"bar.txt", u"baz.txt",
u"blockingfile", u"empty", u"n\u00fc.txt", u"quux.txt", u"sub"])
kids = dict( [(str(name),value)
for (name,value)
in list(data[1]["children"].items())] )
self.failUnlessEqual(kids[u"sub"][0], "dirnode")
self.failUnlessIn("metadata", kids[u"sub"][1])
self.failUnlessIn("tahoe", kids[u"sub"][1]["metadata"])
tahoe_md = kids[u"sub"][1]["metadata"]["tahoe"]
self.failUnlessIn("linkcrtime", tahoe_md)
self.failUnlessIn("linkmotime", tahoe_md)
self.failUnlessEqual(kids[u"bar.txt"][0], "filenode")
self.failUnlessReallyEqual(kids[u"bar.txt"][1]["size"], len(self.BAR_CONTENTS))
self.failUnlessReallyEqual(to_bytes(kids[u"bar.txt"][1]["ro_uri"]), self._bar_txt_uri)
self.failUnlessReallyEqual(to_bytes(kids[u"bar.txt"][1]["verify_uri"]),
self._bar_txt_verifycap)
self.failUnlessIn("metadata", kids[u"bar.txt"][1])
self.failUnlessIn("tahoe", kids[u"bar.txt"][1]["metadata"])
self.failUnlessReallyEqual(kids[u"bar.txt"][1]["metadata"]["tahoe"]["linkcrtime"],
self._bar_txt_metadata["tahoe"]["linkcrtime"])
self.failUnlessReallyEqual(to_bytes(kids[u"n\u00fc.txt"][1]["ro_uri"]),
self._bar_txt_uri)
self.failUnlessIn("quux.txt", kids)
self.failUnlessReallyEqual(to_bytes(kids[u"quux.txt"][1]["rw_uri"]),
self._quux_txt_uri)
self.failUnlessReallyEqual(to_bytes(kids[u"quux.txt"][1]["ro_uri"]),
self._quux_txt_readonly_uri)
@inlineCallbacks
def GET(self, urlpath, followRedirect=False, return_response=False,
**kwargs):
# if return_response=True, this fires with (data, statuscode,
# respheaders) instead of just data.
# treq can accept unicode URLs, unlike the old client.getPage
url = self.webish_url + urlpath
response = yield treq.request("get", url, persistent=False,
allow_redirects=followRedirect,
**kwargs)
data = yield response.content()
if return_response:
# we emulate the old HTTPClientGetFactory-based response, which
# wanted a tuple of (bytestring of data, bytestring of response
# code like "200" or "404", and a
# twisted.web.http_headers.Headers instance). Fortunately treq's
# response.headers has one.
returnValue( (data, str(response.code), response.headers) )
if 400 <= response.code < 600:
raise Error(response.code, response=data)
returnValue(data)
@inlineCallbacks
def HEAD(self, urlpath, return_response=False, headers={}):
url = self.webish_url + urlpath
response = yield treq.request("head", url, persistent=False,
headers=headers)
if 400 <= response.code < 600:
raise Error(response.code, response="")
returnValue( ("", response.code, response.headers) )
def PUT(self, urlpath, data, headers={}):
url = self.webish_url + urlpath
return do_http("put", url, data=data, headers=headers)
def DELETE(self, urlpath):
url = self.webish_url + urlpath
return do_http("delete", url)
def build_form(self, **fields):
sepbase = b"boogabooga"
sep = b"--" + sepbase
form = []
form.append(sep)
form.append(b'Content-Disposition: form-data; name="_charset"')
form.append(b'')
form.append(b'UTF-8')
form.append(sep)
for name, value in list(fields.items()):
if isinstance(name, str):
name = name.encode("utf-8")
if isinstance(value, tuple):
filename, value = value
if isinstance(filename, str):
filename = filename.encode("utf-8")
form.append(b'Content-Disposition: form-data; name="%s"; '
b'filename="%s"' % (name, filename))
else:
form.append(b'Content-Disposition: form-data; name="%s"' % name)
form.append(b'')
if isinstance(value, str):
value = value.encode("utf-8")
form.append(value)
form.append(sep)
form[-1] += b"--"
body = b""
headers = {}
if fields:
body = b"\r\n".join(form) + b"\r\n"
headers["content-type"] = "multipart/form-data; boundary=%s" % str(sepbase, "utf-8")
return (body, headers)
def POST(self, urlpath, **fields):
body, headers = self.build_form(**fields)
return self.POST2(urlpath, body, headers)
def POST2(self, urlpath, body="", headers={}, followRedirect=False):
url = self.webish_url + urlpath
if isinstance(body, str):
body = body.encode("utf-8")
return do_http("POST", url, allow_redirects=followRedirect,
headers=headers, data=body)
def shouldFail(self, res, expected_failure, which,
substring=None, response_substring=None):
if isinstance(res, failure.Failure):
res.trap(expected_failure)
if substring:
self.failUnlessIn(substring, str(res), which)
if response_substring:
self.failUnlessIn(response_substring, res.value.response, which)
else:
self.fail("%r was supposed to raise %s, not get %r" %
(which, expected_failure, res))
def shouldFail2(self, expected_failure, which, substring,
response_substring,
callable, *args, **kwargs):
assert substring is None or isinstance(substring, str)
assert response_substring is None or isinstance(response_substring, str)
d = defer.maybeDeferred(callable, *args, **kwargs)
def done(res):
if isinstance(res, failure.Failure):
res.trap(expected_failure)
if substring:
self.failUnlessIn(substring, str(res),
"%r not in %r (response is %r) for test %r" % \
(substring, str(res),
getattr(res.value, "response", ""),
which))
if response_substring:
response = res.value.response
if isinstance(response, bytes):
response = str(response, "utf-8")
self.failUnlessIn(response_substring, response,
"%r not in %r for test %r" % \
(response_substring, res.value.response,
which))
else:
self.fail("%r was supposed to raise %s, not get %r" %
(which, expected_failure, res))
d.addBoth(done)
return d
def should404(self, res, which):
if isinstance(res, failure.Failure):
res.trap(error.Error)
self.failUnlessReallyEqual(res.value.status, b"404")
else:
self.fail("%s was supposed to Error(404), not get '%s'" %
(which, res))
def should302(self, res, which):
if isinstance(res, failure.Failure):
res.trap(error.Error)
self.failUnlessReallyEqual(res.value.status, b"302")
else:
self.fail("%s was supposed to Error(302), not get '%s'" %
(which, res))
class MultiFormatResourceTests(TrialTestCase):
"""
Tests for ``MultiFormatResource``.
"""
def render(self, resource, **queryargs):
# Query arguments in real twisted.web requests have byte keys.
queryargs = {k.encode("utf-8"): v for (k, v) in list(queryargs.items())}
return self.successResultOf(render(resource, queryargs))
def resource(self):
"""
Create and return an instance of a ``MultiFormatResource`` subclass
with a default HTML format, and two custom formats: ``a`` and ``b``.
"""
class Content(MultiFormatResource):
def render_HTML(self, req):
return b"html"
def render_A(self, req):
return b"a"
def render_B(self, req):
return b"b"
return Content()
def test_select_format(self):
"""
The ``formatArgument`` attribute of a ``MultiFormatResource`` subclass
identifies the query argument which selects the result format.
"""
resource = self.resource()
resource.formatArgument = "foo"
self.assertEqual(b"a", self.render(resource, foo=[b"a"]))
def test_default_format_argument(self):
"""
If a ``MultiFormatResource`` subclass does not set ``formatArgument``
then the ``t`` argument is used.
"""
resource = self.resource()
self.assertEqual(b"a", self.render(resource, t=[b"a"]))
def test_no_format(self):
"""
If no value is given for the format argument and no default format has
been defined, the base rendering behavior is used (``render_HTML``).
"""
resource = self.resource()
self.assertEqual(b"html", self.render(resource))
def test_default_format(self):
"""
If no value is given for the format argument and the ``MultiFormatResource``
subclass defines a ``formatDefault``, that value is used as the format
to render.
"""
resource = self.resource()
resource.formatDefault = "b"
self.assertEqual(b"b", self.render(resource))
def test_explicit_none_format_renderer(self):
"""
If a format is selected which has a renderer set to ``None``, the base
rendering behavior is used (``render_HTML``).
"""
resource = self.resource()
resource.render_FOO = None
self.assertEqual(b"html", self.render(resource, t=[b"foo"]))
def test_unknown_format(self):
"""
If a format is selected for which there is no renderer, an error is
returned.
"""
resource = self.resource()
response_body = self.render(resource, t=[b"foo"])
self.assertIn(
b"<title>400 - Bad Format</title>", response_body,
)
self.assertIn(
b"Unknown t value:", response_body,
)
self.assertIn(
b"'foo'", response_body,
)
class Web(WebMixin, WebErrorMixin, testutil.StallMixin, testutil.ReallyEqualMixin, TrialTestCase):
maxDiff = None
def test_create(self):
pass
def _assertResponseHeaders(self, name, values):
"""
Assert that the resource at **/** is served with a response header named
``name`` and values ``values``.
:param bytes name: The name of the header item to check.
:param [bytes] values: The expected values.
:return Deferred: A Deferred that fires successfully if the expected
header item is found and which fails otherwise.
"""
d = self.GET("/", return_response=True)
def responded(result):
_, _, headers = result
self.assertEqual(
values,
headers.getRawHeaders(name),
)
d.addCallback(responded)
return d
def test_frame_options(self):
"""
Pages deny the ability to be loaded in frames.
"""
# It should be all pages but we only demonstrate it for / with this test.
return self._assertResponseHeaders(b"X-Frame-Options", [b"DENY"])
def test_referrer_policy(self):
"""
Pages set a **no-referrer** policy.
"""
# It should be all pages but we only demonstrate it for / with this test.
return self._assertResponseHeaders(b"Referrer-Policy", [b"no-referrer"])
def test_welcome_json(self):
"""
There is a JSON version of the welcome page which can be selected with the
``t`` query argument.
"""
d = self.GET("/?t=json")
def _check(res):
decoded = json.loads(res)
expected = {
u'introducers': {
u'statuses': [],
},
u'servers': sorted([
{u"nodeid": u'other_nodeid',
u'available_space': 123456,
u'connection_status': u'summary',
u'last_received_data': 30,
u'nickname': u'other_nickname \u263b',
u'version': u'1.0',
},
{u"nodeid": u'disconnected_nodeid',
u'available_space': 123456,
u'connection_status': u'summary',
u'last_received_data': 35,
u'nickname': u'disconnected_nickname \u263b',
u'version': u'1.0',
},
], key=lambda o: sorted(o.items())),
}
self.assertEqual(expected, decoded)
d.addCallback(_check)
return d
def test_introducer_status(self):
class MockIntroducerClient(object):
def __init__(self, connected):
self.connected = connected
def connection_status(self):
return ConnectionStatus(self.connected, "summary", {}, 0, 0)
d = defer.succeed(None)
# introducer not connected, unguessable furl
def _set_introducer_not_connected_unguessable(ign):
self.s.introducer_furls = [ "pb://someIntroducer/secret" ]
self.s.introducer_clients = [ MockIntroducerClient(False) ]
return self.GET("/")
d.addCallback(_set_introducer_not_connected_unguessable)
def _check_introducer_not_connected_unguessable(res):
soup = BeautifulSoup(res, 'html5lib')
self.failIfIn(b'pb://someIntroducer/secret', res)
assert_soup_has_tag_with_attributes(
self, soup, u"img",
{u"alt": u"Disconnected", u"src": u"img/connected-no.png"}
)
assert_soup_has_tag_with_content(
self, soup, u"div",
u"No introducers connected"
)
d.addCallback(_check_introducer_not_connected_unguessable)
# introducer connected, unguessable furl
def _set_introducer_connected_unguessable(ign):
self.s.introducer_furls = [ "pb://someIntroducer/secret" ]
self.s.introducer_clients = [ MockIntroducerClient(True) ]
return self.GET("/")
d.addCallback(_set_introducer_connected_unguessable)
def _check_introducer_connected_unguessable(res):
soup = BeautifulSoup(res, 'html5lib')
assert_soup_has_tag_with_attributes_and_content(
self, soup, u"div",
u"summary",
{ u"class": u"connection-status", u"title": u"(no other hints)" }
)
self.failIfIn(b'pb://someIntroducer/secret', res)
assert_soup_has_tag_with_attributes(
self, soup, u"img",
{ u"alt": u"Connected", u"src": u"img/connected-yes.png" }
)
assert_soup_has_tag_with_content(
self, soup, u"div",
u"1 introducer connected"
)
d.addCallback(_check_introducer_connected_unguessable)
# introducer connected, guessable furl
def _set_introducer_connected_guessable(ign):
self.s.introducer_furls = [ "pb://someIntroducer/introducer" ]
self.s.introducer_clients = [ MockIntroducerClient(True) ]
return self.GET("/")
d.addCallback(_set_introducer_connected_guessable)
def _check_introducer_connected_guessable(res):
soup = BeautifulSoup(res, 'html5lib')
assert_soup_has_tag_with_attributes_and_content(
self, soup, u"div",
u"summary",
{ u"class": u"connection-status", u"title": u"(no other hints)" }
)
assert_soup_has_tag_with_attributes(
self, soup, u"img",
{ u"src": u"img/connected-yes.png", u"alt": u"Connected" }
)
assert_soup_has_tag_with_content(
self, soup, u"div",
u"1 introducer connected"
)
d.addCallback(_check_introducer_connected_guessable)
return d
def test_helper_status(self):
d = defer.succeed(None)
# set helper furl to None
def _set_no_helper(ign):
self.s.uploader.helper_furl = None
return self.GET("/")
d.addCallback(_set_no_helper)
def _check_no_helper(res):
soup = BeautifulSoup(res, 'html5lib')
assert_soup_has_tag_with_attributes(
self, soup, u"img",
{ u"src": u"img/connected-not-configured.png", u"alt": u"Not Configured" }
)
d.addCallback(_check_no_helper)
# enable helper, not connected
def _set_helper_not_connected(ign):
self.s.uploader.helper_furl = "pb://someHelper/secret"
self.s.uploader.helper_connected = False
return self.GET("/")
d.addCallback(_set_helper_not_connected)
def _check_helper_not_connected(res):
soup = BeautifulSoup(res, 'html5lib')
assert_soup_has_tag_with_attributes_and_content(
self, soup, u"div",
u"pb://someHelper/[censored]",
{ u"class": u"furl" }
)
self.failIfIn(b'pb://someHelper/secret', res)
assert_soup_has_tag_with_attributes(
self, soup, u"img",
{ u"src": u"img/connected-no.png", u"alt": u"Disconnected" }
)
d.addCallback(_check_helper_not_connected)
# enable helper, connected
def _set_helper_connected(ign):
self.s.uploader.helper_furl = "pb://someHelper/secret"
self.s.uploader.helper_connected = True
return self.GET("/")
d.addCallback(_set_helper_connected)
def _check_helper_connected(res):
soup = BeautifulSoup(res, 'html5lib')
assert_soup_has_tag_with_attributes_and_content(
self, soup, u"div",
u"pb://someHelper/[censored]",
{ u"class": u"furl" }
)
self.failIfIn(b'pb://someHelper/secret', res)
assert_soup_has_tag_with_attributes(
self, soup, u"img",
{ u"src": u"img/connected-yes.png", "alt": u"Connected" }
)
d.addCallback(_check_helper_connected)
return d
def test_storage(self):
d = self.GET("/storage")
def _check(res):
soup = BeautifulSoup(res, 'html5lib')
assert_soup_has_text(self, soup, 'Storage Server Status')
assert_soup_has_favicon(self, soup)
res_u = res.decode('utf-8')
self.failUnlessIn(u'<li>Server Nickname: <span class="nickname mine">fake_nickname \u263A</span></li>', res_u)
d.addCallback(_check)
return d
def test_status(self):
h = self.s.get_history()
dl_num = h.list_all_download_statuses()[0].get_counter()
ul_num = h.list_all_upload_statuses()[0].get_counter()
mu_num = h.list_all_mapupdate_statuses()[0].get_counter()
pub_num = h.list_all_publish_statuses()[0].get_counter()
ret_num = h.list_all_retrieve_statuses()[0].get_counter()
d = self.GET("/status", followRedirect=True)