-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathtest_storage.py
More file actions
2334 lines (2041 loc) · 97.6 KB
/
test_storage.py
File metadata and controls
2334 lines (2041 loc) · 97.6 KB
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
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
"""Functional tests for the SyncStorage server protocol.
This file runs tests to ensure the correct operation of the server
as specified in:
http://docs.services.mozilla.com/storage/apis-1.5.html
If there's an aspect of that spec that's not covered by a test in this file,
consider it a bug.
"""
import pytest
import re
import json
import time
import random
import string
import urllib
import webtest
import contextlib
# import math
import simplejson # type: ignore[import-untyped]
from pyramid.interfaces import IAuthenticationPolicy
from webtest.app import AppError
from tools.integration_tests.test_support import StorageFunctionalTestCase
import tokenlib
class ConflictError(Exception):
"""Raised when a conflict (409) response is returned."""
pass
class BackendError(Exception):
"""Raised when a backend error (503) response is returned."""
pass
WEAVE_INVALID_WBO = 8 # Invalid Weave Basic Object
WEAVE_SIZE_LIMIT_EXCEEDED = 17 # Size limit exceeded
BATCH_MAX_IDS = 100
def get_limit_config(request, limit):
"""Get the configured value for the named size limit."""
return request.registry.settings["storage." + limit]
def json_dumps(value):
"""Decimal-aware version of json.dumps()."""
return simplejson.dumps(value, use_decimal=True)
def json_loads(value):
"""Decimal-aware version of json.loads()."""
return simplejson.loads(value, use_decimal=True)
_PLD = "*" * 500
_ASCII = string.ascii_letters + string.digits
def randtext(size=10):
"""Return a random ASCII string of the given size."""
return "".join([random.choice(_ASCII) for i in range(size)])
class TestStorage(StorageFunctionalTestCase):
"""Storage testcases that only use the web API.
These tests are suitable for running against both in-process and live
external web servers.
"""
def setUp(self):
"""Call setUp, set API path for current user, delete
old root path with user for a clean slate in each test.
"""
super(TestStorage, self).setUp()
self.root = "/1.5/%d" % (self.user_id,)
self.retry_delete(self.root)
@contextlib.contextmanager
def _switch_user(self):
"""Allow temporary switch of url to another user id.
Context manager yields for duration of test and then
returns to original user, regardless of test result.
If unsuccessful, root url is retained.
"""
orig_root = self.root
try:
with super(TestStorage, self)._switch_user():
self.root = "/1.5/%d" % (self.user_id,)
# Potentially slow: it's possible this is a user from
# a previous test w/ left over data. Clearing instead
# in a tearDown is more involved because at least one
# test calls _switch_user+writes many times
self.retry_delete(self.root)
yield
finally:
self.root = orig_root
def retry_post_json(self, *args, **kwargs):
"""Send a POST request with retry on transient errors."""
return self._retry_send(self.app.post_json, *args, **kwargs)
def retry_put_json(self, *args, **kwargs):
"""Send a PUT request with retry on transient errors."""
return self._retry_send(self.app.put_json, *args, **kwargs)
def retry_delete(self, *args, **kwargs):
"""Send a DELETE request with retry on transient errors."""
return self._retry_send(self.app.delete, *args, **kwargs)
def _retry_send(self, func, *args, **kwargs):
try:
# Try to call underlying webtest method with args.
return func(*args, **kwargs) # Generic callable
except webtest.AppError as ex:
# If non-200 resp, we want to retry as may be transient
# status. If 409 (conflict) or 503 (Service Unavailable)
# are not present, err non-transient and we re-raise,
# no retry.
if "409 " not in ex.args[0] and "503 " not in ex.args[0]:
raise ex
time.sleep(0.01)
return func(*args, **kwargs)
def test_get_info_collections(self):
"""Test get info collections."""
# xxx_col1 gets 3 items, xxx_col2 gets 5 items.
bsos = [{"id": str(i).zfill(2), "payload": "xxx"} for i in range(3)]
resp = self.retry_post_json(self.root + "/storage/xxx_col1", bsos)
ts1 = resp.json["modified"]
bsos = [{"id": str(i).zfill(2), "payload": "xxx"} for i in range(5)]
resp = self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
ts2 = resp.json["modified"]
# only those collections should appear in the query.
resp = self.app.get(self.root + "/info/collections")
res = resp.json
keys = sorted(list(res.keys()))
self.assertEqual(keys, ["xxx_col1", "xxx_col2"])
self.assertEqual(res["xxx_col1"], ts1)
self.assertEqual(res["xxx_col2"], ts2)
# Updating items in xxx_col2, check timestamps.
bsos = [{"id": str(i).zfill(2), "payload": "yyy"} for i in range(2)]
resp = self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
self.assertTrue(ts2 < resp.json["modified"])
ts2 = resp.json["modified"]
resp = self.app.get(self.root + "/info/collections")
res = resp.json
keys = sorted(list(res.keys()))
self.assertEqual(keys, ["xxx_col1", "xxx_col2"])
self.assertEqual(res["xxx_col1"], ts1)
self.assertEqual(res["xxx_col2"], ts2)
def test_get_collection_count(self):
"""Test get collection count."""
# xxx_col1 gets 3 items, xxx_col2 gets 5 items.
bsos = [{"id": str(i).zfill(2), "payload": "xxx"} for i in range(3)]
self.retry_post_json(self.root + "/storage/xxx_col1", bsos)
bsos = [{"id": str(i).zfill(2), "payload": "xxx"} for i in range(5)]
self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
# those counts should be reflected back in query.
resp = self.app.get(self.root + "/info/collection_counts")
res = resp.json
self.assertEqual(len(res), 2)
self.assertEqual(res["xxx_col1"], 3)
self.assertEqual(res["xxx_col2"], 5)
def test_bad_cache(self):
"""Test bad cache."""
# fixes #637332
# the collection name <-> id mapper is temporarely cached to
# save a few requests.
# but should get purged when new collections are added
# 1. get collection info
resp = self.app.get(self.root + "/info/collections")
numcols = len(resp.json)
# 2. add a new collection + stuff
bso = {"id": "125", "payload": _PLD}
self.retry_put_json(self.root + "/storage/xxxx/125", bso)
# 3. get collection info again, should find the new ones
resp = self.app.get(self.root + "/info/collections")
self.assertEqual(len(resp.json), numcols + 1)
def test_get_collection_only(self):
"""Test get collection only."""
bsos = [{"id": str(i).zfill(2), "payload": "xxx"} for i in range(5)]
self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
# non-existent collections appear as empty
resp = self.app.get(self.root + "/storage/nonexistent")
res = resp.json
self.assertEqual(res, [])
# try just getting all items at once.
resp = self.app.get(self.root + "/storage/xxx_col2")
res = resp.json
res.sort()
self.assertEqual(res, ["00", "01", "02", "03", "04"])
self.assertEqual(int(resp.headers["X-Weave-Records"]), 5)
# trying various filters
# "ids"
# Returns the ids for objects in the collection that are in the
# provided comma-separated list.
res = self.app.get(self.root + "/storage/xxx_col2?ids=01,03,17")
res = res.json
res.sort()
self.assertEqual(res, ["01", "03"])
# "newer"
# Returns only ids for objects in the collection that have been last
# modified after the timestamp given.
self.retry_delete(self.root + "/storage/xxx_col2")
bso = {"id": "128", "payload": "x"}
res = self.retry_put_json(self.root + "/storage/xxx_col2/128", bso)
ts1 = float(res.headers["X-Last-Modified"])
bso = {"id": "129", "payload": "x"}
res = self.retry_put_json(self.root + "/storage/xxx_col2/129", bso)
ts2 = float(res.headers["X-Last-Modified"])
self.assertTrue(ts1 < ts2)
res = self.app.get(self.root + "/storage/xxx_col2?newer=%s" % ts1)
self.assertEqual(res.json, ["129"])
res = self.app.get(self.root + "/storage/xxx_col2?newer=%s" % ts2)
self.assertEqual(res.json, [])
res = self.app.get(self.root + "/storage/xxx_col2?newer=%s" % (ts1 - 1))
self.assertEqual(sorted(res.json), ["128", "129"])
# "older"
# Returns only ids for objects in the collection that have been last
# modified before the timestamp given.
self.retry_delete(self.root + "/storage/xxx_col2")
bso = {"id": "128", "payload": "x"}
res = self.retry_put_json(self.root + "/storage/xxx_col2/128", bso)
ts1 = float(res.headers["X-Last-Modified"])
bso = {"id": "129", "payload": "x"}
res = self.retry_put_json(self.root + "/storage/xxx_col2/129", bso)
ts2 = float(res.headers["X-Last-Modified"])
self.assertTrue(ts1 < ts2)
res = self.app.get(self.root + "/storage/xxx_col2?older=%s" % ts1)
self.assertEqual(res.json, [])
res = self.app.get(self.root + "/storage/xxx_col2?older=%s" % ts2)
self.assertEqual(res.json, ["128"])
res = self.app.get(self.root + "/storage/xxx_col2?older=%s" % (ts2 + 1))
self.assertEqual(sorted(res.json), ["128", "129"])
qs = "?older=%s&newer=%s" % (ts2 + 1, ts1)
res = self.app.get(self.root + "/storage/xxx_col2" + qs)
self.assertEqual(sorted(res.json), ["129"])
# "full"
# If defined, returns the full BSO, rather than just the id.
res = self.app.get(self.root + "/storage/xxx_col2?full=1")
keys = list(res.json[0].keys())
keys.sort()
wanted = ["id", "modified", "payload"]
self.assertEqual(keys, wanted)
res = self.app.get(self.root + "/storage/xxx_col2")
self.assertTrue(isinstance(res.json, list))
# "limit"
# Sets the maximum number of ids that will be returned
self.retry_delete(self.root + "/storage/xxx_col2")
bsos = []
for i in range(10):
bso = {"id": str(i).zfill(2), "payload": "x", "sortindex": i}
bsos.append(bso)
self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
query_url = self.root + "/storage/xxx_col2?sort=index"
res = self.app.get(query_url)
all_items = res.json
self.assertEqual(len(all_items), 10)
res = self.app.get(query_url + "&limit=2")
self.assertEqual(res.json, all_items[:2])
# "offset"
# Skips over items that have already been returned.
next_offset = res.headers["X-Weave-Next-Offset"]
res = self.app.get(query_url + "&limit=3&offset=" + next_offset)
self.assertEqual(res.json, all_items[2:5])
next_offset = res.headers["X-Weave-Next-Offset"]
res = self.app.get(query_url + "&offset=" + next_offset)
self.assertEqual(res.json, all_items[5:])
self.assertTrue("X-Weave-Next-Offset" not in res.headers)
res = self.app.get(query_url + "&limit=10000&offset=" + next_offset)
self.assertEqual(res.json, all_items[5:])
self.assertTrue("X-Weave-Next-Offset" not in res.headers)
# "offset" again, this time ordering by descending timestamp.
query_url = self.root + "/storage/xxx_col2?sort=newest"
res = self.app.get(query_url)
all_items = res.json
self.assertEqual(len(all_items), 10)
res = self.app.get(query_url + "&limit=2")
self.assertEqual(res.json, all_items[:2])
next_offset = res.headers["X-Weave-Next-Offset"]
res = self.app.get(query_url + "&limit=3&offset=" + next_offset)
self.assertEqual(res.json, all_items[2:5])
next_offset = res.headers["X-Weave-Next-Offset"]
res = self.app.get(query_url + "&offset=" + next_offset)
self.assertEqual(res.json, all_items[5:])
self.assertTrue("X-Weave-Next-Offset" not in res.headers)
res = self.app.get(query_url + "&limit=10000&offset=" + next_offset)
self.assertEqual(res.json, all_items[5:])
# "offset" again, this time ordering by ascending timestamp.
query_url = self.root + "/storage/xxx_col2?sort=oldest"
res = self.app.get(query_url)
all_items = res.json
self.assertEqual(len(all_items), 10)
res = self.app.get(query_url + "&limit=2")
self.assertEqual(res.json, all_items[:2])
next_offset = res.headers["X-Weave-Next-Offset"]
res = self.app.get(query_url + "&limit=3&offset=" + next_offset)
self.assertEqual(res.json, all_items[2:5])
next_offset = res.headers["X-Weave-Next-Offset"]
res = self.app.get(query_url + "&offset=" + next_offset)
self.assertEqual(res.json, all_items[5:])
self.assertTrue("X-Weave-Next-Offset" not in res.headers)
res = self.app.get(query_url + "&limit=10000&offset=" + next_offset)
self.assertEqual(res.json, all_items[5:])
# "offset" once more, this time with no explicit ordering
query_url = self.root + "/storage/xxx_col2?"
res = self.app.get(query_url)
all_items = res.json
self.assertEqual(len(all_items), 10)
res = self.app.get(query_url + "&limit=2")
self.assertEqual(res.json, all_items[:2])
next_offset = res.headers["X-Weave-Next-Offset"]
res = self.app.get(query_url + "&limit=3&offset=" + next_offset)
self.assertEqual(res.json, all_items[2:5])
next_offset = res.headers["X-Weave-Next-Offset"]
res = self.app.get(query_url + "&offset=" + next_offset)
self.assertEqual(res.json, all_items[5:])
self.assertTrue("X-Weave-Next-Offset" not in res.headers)
res = self.app.get(query_url + "&limit=10000&offset=" + next_offset)
# "sort"
# 'newest': Orders by timestamp number (newest first)
# 'oldest': Orders by timestamp number (oldest first)
# 'index': Orders by the sortindex descending (highest weight first)
self.retry_delete(self.root + "/storage/xxx_col2")
for index, sortindex in (("00", -1), ("01", 34), ("02", 12)):
bso = {"id": index, "payload": "x", "sortindex": sortindex}
self.retry_post_json(self.root + "/storage/xxx_col2", [bso])
res = self.app.get(self.root + "/storage/xxx_col2?sort=newest")
res = res.json
self.assertEqual(res, ["02", "01", "00"])
res = self.app.get(self.root + "/storage/xxx_col2?sort=oldest")
res = res.json
self.assertEqual(res, ["00", "01", "02"])
res = self.app.get(self.root + "/storage/xxx_col2?sort=index")
res = res.json
self.assertEqual(res, ["01", "02", "00"])
def test_alternative_formats(self):
"""Test alternative formats."""
bsos = [{"id": str(i).zfill(2), "payload": "xxx"} for i in range(5)]
self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
# application/json
res = self.app.get(
self.root + "/storage/xxx_col2",
headers=[("Accept", "application/json")],
)
self.assertEqual(res.content_type.split(";")[0], "application/json")
res = res.json
res.sort()
self.assertEqual(res, ["00", "01", "02", "03", "04"])
# application/newlines
res = self.app.get(
self.root + "/storage/xxx_col2",
headers=[("Accept", "application/newlines")],
)
self.assertEqual(res.content_type, "application/newlines")
self.assertTrue(res.body.endswith(b"\n"))
res = [
json_loads(line) for line in res.body.decode("utf-8").strip().split("\n")
]
res.sort()
self.assertEqual(res, ["00", "01", "02", "03", "04"])
# unspecified format defaults to json
res = self.app.get(self.root + "/storage/xxx_col2")
self.assertEqual(res.content_type.split(";")[0], "application/json")
# unkown format gets a 406
self.app.get(
self.root + "/storage/xxx_col2",
headers=[("Accept", "x/yy")],
status=406,
)
def test_set_collection_with_if_modified_since(self):
"""Test set collection with if modified since."""
# Create five items with different timestamps.
for i in range(5):
bsos = [{"id": str(i).zfill(2), "payload": "xxx"}]
self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
# Get them all, along with their timestamps.
res = self.app.get(self.root + "/storage/xxx_col2?full=true").json
self.assertEqual(len(res), 5)
timestamps = sorted([r["modified"] for r in res])
# The timestamp of the collection should be the max of all those.
self.app.get(
self.root + "/storage/xxx_col2",
headers={"X-If-Modified-Since": str(timestamps[0])},
status=200,
)
res = self.app.get(
self.root + "/storage/xxx_col2",
headers={"X-If-Modified-Since": str(timestamps[-1])},
status=304,
)
self.assertTrue("X-Last-Modified" in res.headers)
def test_get_item(self):
"""Test get item."""
bsos = [{"id": str(i).zfill(2), "payload": "xxx"} for i in range(5)]
self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
# grabbing object 1 from xxx_col2
res = self.app.get(self.root + "/storage/xxx_col2/01")
res = res.json
keys = list(res.keys())
keys.sort()
self.assertEqual(keys, ["id", "modified", "payload"])
self.assertEqual(res["id"], "01")
# unexisting object
self.app.get(self.root + "/storage/xxx_col2/99", status=404)
# using x-if-modified-since header.
self.app.get(
self.root + "/storage/xxx_col2/01",
headers={"X-If-Modified-Since": str(res["modified"])},
status=304,
)
self.app.get(
self.root + "/storage/xxx_col2/01",
headers={"X-If-Modified-Since": str(res["modified"] + 1)},
status=304,
)
res = self.app.get(
self.root + "/storage/xxx_col2/01",
headers={"X-If-Modified-Since": str(res["modified"] - 1)},
)
self.assertEqual(res.json["id"], "01")
def test_set_item(self):
"""Test set item."""
# let's create an object
bso = {"payload": _PLD}
self.retry_put_json(self.root + "/storage/xxx_col2/12345", bso)
res = self.app.get(self.root + "/storage/xxx_col2/12345")
res = res.json
self.assertEqual(res["payload"], _PLD)
# now let's update it
bso = {"payload": "YYY"}
self.retry_put_json(self.root + "/storage/xxx_col2/12345", bso)
res = self.app.get(self.root + "/storage/xxx_col2/12345")
res = res.json
self.assertEqual(res["payload"], "YYY")
def test_set_collection(self):
"""Test set collection."""
# sending two bsos
bso1 = {"id": "12", "payload": _PLD}
bso2 = {"id": "13", "payload": _PLD}
bsos = [bso1, bso2]
self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
# checking what we did
res = self.app.get(self.root + "/storage/xxx_col2/12")
res = res.json
self.assertEqual(res["payload"], _PLD)
res = self.app.get(self.root + "/storage/xxx_col2/13")
res = res.json
self.assertEqual(res["payload"], _PLD)
# one more time, with changes
bso1 = {"id": "13", "payload": "XyX"}
bso2 = {"id": "14", "payload": _PLD}
bsos = [bso1, bso2]
self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
# checking what we did
res = self.app.get(self.root + "/storage/xxx_col2/14")
res = res.json
self.assertEqual(res["payload"], _PLD)
res = self.app.get(self.root + "/storage/xxx_col2/13")
res = res.json
self.assertEqual(res["payload"], "XyX")
# sending two bsos with one bad sortindex
bso1 = {"id": "one", "payload": _PLD}
bso2 = {"id": "two", "payload": _PLD, "sortindex": "FAIL"}
bsos = [bso1, bso2]
self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
self.app.get(self.root + "/storage/xxx_col2/two", status=404)
def test_set_collection_input_formats(self):
"""Test set collection input formats."""
# If we send with application/newlines it should work.
bso1 = {"id": "12", "payload": _PLD}
bso2 = {"id": "13", "payload": _PLD}
bsos = [bso1, bso2]
body = "\n".join(json_dumps(bso) for bso in bsos)
self.app.post(
self.root + "/storage/xxx_col2",
body,
headers={"Content-Type": "application/newlines"},
)
items = self.app.get(self.root + "/storage/xxx_col2").json
self.assertEqual(len(items), 2)
# If we send an unknown content type, we get an error.
self.retry_delete(self.root + "/storage/xxx_col2")
body = json_dumps(bsos)
self.app.post(
self.root + "/storage/xxx_col2",
body,
headers={"Content-Type": "application/octet-stream"},
status=415,
)
items = self.app.get(self.root + "/storage/xxx_col2").json
self.assertEqual(len(items), 0)
def test_set_item_input_formats(self):
"""Test set item input formats."""
# If we send with application/json it should work.
body = json_dumps({"payload": _PLD})
self.app.put(
self.root + "/storage/xxx_col2/TEST",
body,
headers={"Content-Type": "application/json"},
)
item = self.app.get(self.root + "/storage/xxx_col2/TEST").json
self.assertEqual(item["payload"], _PLD)
# If we send json with some other content type, it should fail
self.retry_delete(self.root + "/storage/xxx_col2")
self.app.put(
self.root + "/storage/xxx_col2/TEST",
body,
headers={"Content-Type": "application/octet-stream"},
status=415,
)
self.app.get(self.root + "/storage/xxx_col2/TEST", status=404)
# Unless we use text/plain, which is a special bw-compat case.
self.app.put(
self.root + "/storage/xxx_col2/TEST",
body,
headers={"Content-Type": "text/plain"},
)
item = self.app.get(self.root + "/storage/xxx_col2/TEST").json
self.assertEqual(item["payload"], _PLD)
def test_app_newlines_when_payloads_contain_newlines(self):
"""Test app newlines when payloads contain newlines."""
# Send some application/newlines with embedded newline chars.
bsos = [
{"id": "01", "payload": "hello\nworld"},
{"id": "02", "payload": "\nmarco\npolo\n"},
]
body = "\n".join(json_dumps(bso) for bso in bsos)
self.assertEqual(len(body.split("\n")), 2)
self.app.post(
self.root + "/storage/xxx_col2",
body,
headers={"Content-Type": "application/newlines"},
)
# Read them back as JSON list, check payloads.
items = self.app.get(self.root + "/storage/xxx_col2?full=1").json
self.assertEqual(len(items), 2)
items.sort(key=lambda bso: bso["id"])
self.assertEqual(items[0]["payload"], bsos[0]["payload"])
self.assertEqual(items[1]["payload"], bsos[1]["payload"])
# Read them back as application/newlines, check payloads.
res = self.app.get(
self.root + "/storage/xxx_col2?full=1",
headers={
"Accept": "application/newlines",
},
)
items = [
json_loads(line) for line in res.body.decode("utf-8").strip().split("\n")
]
self.assertEqual(len(items), 2)
items.sort(key=lambda bso: bso["id"])
self.assertEqual(items[0]["payload"], bsos[0]["payload"])
self.assertEqual(items[1]["payload"], bsos[1]["payload"])
def test_collection_usage(self):
"""Test collection usage."""
self.retry_delete(self.root + "/storage")
bso1 = {"id": "13", "payload": "XyX"}
bso2 = {"id": "14", "payload": _PLD}
bsos = [bso1, bso2]
self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
res = self.app.get(self.root + "/info/collection_usage")
usage = res.json
xxx_col2_size = usage["xxx_col2"]
wanted = (len(bso1["payload"]) + len(bso2["payload"])) / 1024.0
self.assertEqual(round(xxx_col2_size, 2), round(wanted, 2))
def test_delete_collection_items(self):
"""Test delete collection items."""
# creating a collection of three
bso1 = {"id": "12", "payload": _PLD}
bso2 = {"id": "13", "payload": _PLD}
bso3 = {"id": "14", "payload": _PLD}
bsos = [bso1, bso2, bso3]
self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
res = self.app.get(self.root + "/storage/xxx_col2")
self.assertEqual(len(res.json), 3)
# deleting all items
self.retry_delete(self.root + "/storage/xxx_col2")
items = self.app.get(self.root + "/storage/xxx_col2").json
self.assertEqual(len(items), 0)
# Deletes the ids for objects in the collection that are in the
# provided comma-separated list.
self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
res = self.app.get(self.root + "/storage/xxx_col2")
self.assertEqual(len(res.json), 3)
self.retry_delete(self.root + "/storage/xxx_col2?ids=12,14")
res = self.app.get(self.root + "/storage/xxx_col2")
self.assertEqual(len(res.json), 1)
self.retry_delete(self.root + "/storage/xxx_col2?ids=13")
res = self.app.get(self.root + "/storage/xxx_col2")
self.assertEqual(len(res.json), 0)
def test_delete_item(self):
"""Test delete item."""
# creating a collection of three
bso1 = {"id": "12", "payload": _PLD}
bso2 = {"id": "13", "payload": _PLD}
bso3 = {"id": "14", "payload": _PLD}
bsos = [bso1, bso2, bso3]
self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
res = self.app.get(self.root + "/storage/xxx_col2")
self.assertEqual(len(res.json), 3)
ts = float(res.headers["X-Last-Modified"])
# deleting item 13
self.retry_delete(self.root + "/storage/xxx_col2/13")
res = self.app.get(self.root + "/storage/xxx_col2")
self.assertEqual(len(res.json), 2)
# unexisting item should return a 404
self.retry_delete(self.root + "/storage/xxx_col2/12982", status=404)
# The collection should get an updated timestsamp.
res = self.app.get(self.root + "/info/collections")
self.assertTrue(ts < float(res.headers["X-Last-Modified"]))
def test_delete_storage(self):
"""Test delete storage."""
# creating a collection of three
bso1 = {"id": "12", "payload": _PLD}
bso2 = {"id": "13", "payload": _PLD}
bso3 = {"id": "14", "payload": _PLD}
bsos = [bso1, bso2, bso3]
self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
res = self.app.get(self.root + "/storage/xxx_col2")
self.assertEqual(len(res.json), 3)
# deleting all
self.retry_delete(self.root + "/storage")
items = self.app.get(self.root + "/storage/xxx_col2").json
self.assertEqual(len(items), 0)
self.retry_delete(self.root + "/storage/xxx_col2", status=200)
self.assertEqual(len(items), 0)
def test_x_timestamp_header(self):
"""Test x timestamp header."""
if self.distant:
pytest.skip("Test cannot be run against a live server.")
bsos = [{"id": str(i).zfill(2), "payload": "xxx"} for i in range(5)]
self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
now = round(time.time(), 2)
time.sleep(0.01)
res = self.app.get(self.root + "/storage/xxx_col2")
self.assertTrue(now <= float(res.headers["X-Weave-Timestamp"]))
# getting the timestamp with a PUT
now = round(time.time(), 2)
time.sleep(0.01)
bso = {"payload": _PLD}
res = self.retry_put_json(self.root + "/storage/xxx_col2/12345", bso)
self.assertTrue(now <= float(res.headers["X-Weave-Timestamp"]))
self.assertTrue(abs(now - float(res.headers["X-Weave-Timestamp"])) <= 200)
# getting the timestamp with a POST
now = round(time.time(), 2)
time.sleep(0.01)
bso1 = {"id": "12", "payload": _PLD}
bso2 = {"id": "13", "payload": _PLD}
bsos = [bso1, bso2]
res = self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
self.assertTrue(now <= float(res.headers["X-Weave-Timestamp"]))
def test_ifunmodifiedsince(self):
"""Test ifunmodifiedsince."""
bso = {"id": "12345", "payload": _PLD}
res = self.retry_put_json(self.root + "/storage/xxx_col2/12345", bso)
# Using an X-If-Unmodified-Since in the past should cause 412s.
ts = str(float(res.headers["X-Last-Modified"]) - 1)
bso = {"id": "12345", "payload": _PLD + "XXX"}
res = self.retry_put_json(
self.root + "/storage/xxx_col2/12345",
bso,
headers=[("X-If-Unmodified-Since", ts)],
status=412,
)
self.assertTrue("X-Last-Modified" in res.headers)
res = self.retry_delete(
self.root + "/storage/xxx_col2/12345",
headers=[("X-If-Unmodified-Since", ts)],
status=412,
)
self.assertTrue("X-Last-Modified" in res.headers)
self.retry_post_json(
self.root + "/storage/xxx_col2",
[bso],
headers=[("X-If-Unmodified-Since", ts)],
status=412,
)
self.retry_delete(
self.root + "/storage/xxx_col2?ids=12345",
headers=[("X-If-Unmodified-Since", ts)],
status=412,
)
self.app.get(
self.root + "/storage/xxx_col2/12345",
headers=[("X-If-Unmodified-Since", ts)],
status=412,
)
self.app.get(
self.root + "/storage/xxx_col2",
headers=[("X-If-Unmodified-Since", ts)],
status=412,
)
# Deleting items from a collection should give 412 even if some
# other, unrelated item in the collection has been modified.
ts = res.headers["X-Last-Modified"]
res2 = self.retry_put_json(
self.root + "/storage/xxx_col2/54321",
{
"payload": _PLD,
},
)
self.retry_delete(
self.root + "/storage/xxx_col2?ids=12345",
headers=[("X-If-Unmodified-Since", ts)],
status=412,
)
ts = res2.headers["X-Last-Modified"]
# All of those should have left the BSO unchanged
res2 = self.app.get(self.root + "/storage/xxx_col2/12345")
self.assertEqual(res2.json["payload"], _PLD)
self.assertEqual(
res2.headers["X-Last-Modified"], res.headers["X-Last-Modified"]
)
# Using an X-If-Unmodified-Since equal to
# X-Last-Modified should allow the request to succeed.
res = self.retry_post_json(
self.root + "/storage/xxx_col2",
[bso],
headers=[("X-If-Unmodified-Since", ts)],
status=200,
)
ts = res.headers["X-Last-Modified"]
self.app.get(
self.root + "/storage/xxx_col2/12345",
headers=[("X-If-Unmodified-Since", ts)],
status=200,
)
self.retry_delete(
self.root + "/storage/xxx_col2/12345",
headers=[("X-If-Unmodified-Since", ts)],
status=200,
)
res = self.retry_put_json(
self.root + "/storage/xxx_col2/12345",
bso,
headers=[("X-If-Unmodified-Since", "0")],
status=200,
)
ts = res.headers["X-Last-Modified"]
self.app.get(
self.root + "/storage/xxx_col2",
headers=[("X-If-Unmodified-Since", ts)],
status=200,
)
self.retry_delete(
self.root + "/storage/xxx_col2?ids=12345",
headers=[("X-If-Unmodified-Since", ts)],
status=200,
)
def test_quota(self):
"""Test quota."""
res = self.app.get(self.root + "/info/quota")
old_used = res.json[0]
bso = {"payload": _PLD}
self.retry_put_json(self.root + "/storage/xxx_col2/12345", bso)
res = self.app.get(self.root + "/info/quota")
used = res.json[0]
self.assertEqual(used - old_used, len(_PLD) / 1024.0)
def test_get_collection_ttl(self):
"""Test get collection ttl."""
bso = {"payload": _PLD, "ttl": 0}
res = self.retry_put_json(self.root + "/storage/xxx_col2/12345", bso)
time.sleep(1.1)
res = self.app.get(self.root + "/storage/xxx_col2")
self.assertEqual(res.json, [])
bso = {"payload": _PLD, "ttl": 2}
res = self.retry_put_json(self.root + "/storage/xxx_col2/123456", bso)
# it should exists now
res = self.app.get(self.root + "/storage/xxx_col2")
self.assertEqual(len(res.json), 1)
# trying a second put again
self.retry_put_json(self.root + "/storage/xxx_col2/123456", bso)
res = self.app.get(self.root + "/storage/xxx_col2")
self.assertEqual(len(res.json), 1)
time.sleep(2.1)
res = self.app.get(self.root + "/storage/xxx_col2")
self.assertEqual(len(res.json), 0)
def test_multi_item_post_limits(self):
"""Test multi item post limits."""
res = self.app.get(self.root + "/info/configuration")
try:
max_bytes = res.json["max_post_bytes"]
max_count = res.json["max_post_records"]
max_req_bytes = res.json["max_request_bytes"]
except KeyError:
# Can't run against live server if it doesn't
# report the right config options.
if self.distant:
pytest.skip("")
max_bytes = get_limit_config(self.config, "max_post_bytes")
max_count = get_limit_config(self.config, "max_post_records")
max_req_bytes = get_limit_config(self.config, "max_request_bytes")
# Uploading max_count-5 small objects should succeed.
bsos = [{"id": str(i).zfill(2), "payload": "X"} for i in range(max_count - 5)]
res = self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
res = res.json
self.assertEqual(len(res["success"]), max_count - 5)
self.assertEqual(len(res["failed"]), 0)
# Uploading max_count+5 items should produce five failures.
bsos = [{"id": str(i).zfill(2), "payload": "X"} for i in range(max_count + 5)]
res = self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
res = res.json
self.assertEqual(len(res["success"]), max_count)
self.assertEqual(len(res["failed"]), 5)
# Uploading items such that the last item puts us over the
# cumulative limit on payload size, should produce 1 failure.
# The item_size here is arbitrary, so I made it a prime in kB.
item_size = 227 * 1024
max_items, leftover = divmod(max_bytes, item_size)
bsos = [
{"id": str(i).zfill(2), "payload": "X" * item_size}
for i in range(max_items)
]
bsos.append({"id": str(max_items), "payload": "X" * (leftover + 1)})
# Check that we don't go over the limit on raw request bytes,
# which would get us rejected in production with a 413.
self.assertTrue(len(json.dumps(bsos)) < max_req_bytes)
res = self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
res = res.json
self.assertEqual(len(res["success"]), max_items)
self.assertEqual(len(res["failed"]), 1)
def test_weird_args(self):
"""Test weird args."""
# pushing some data in xxx_col2
bsos = [{"id": str(i).zfill(2), "payload": _PLD} for i in range(10)]
res = self.retry_post_json(self.root + "/storage/xxx_col2", bsos)
res = res.json
# trying weird args and make sure the server returns 400s
# Note: "Offset" is a string since the bsoid could be anything.
# skipping that for now.
args = ("newer", "older", "limit")
for arg in args:
value = randtext()
self.app.get(
self.root + "/storage/xxx_col2?%s=%s" % (arg, value),
status=400,
)
# what about a crazy ids= string ?
ids = ",".join([randtext(10) for i in range(100)])
res = self.app.get(self.root + "/storage/xxx_col2?ids=%s" % ids)
self.assertEqual(res.json, [])
# trying unexpected args - they should not break
self.app.get(self.root + "/storage/xxx_col2?blabla=1", status=200)
def test_guid_deletion(self):
"""Test guid deletion."""
# pushing some data in xxx_col2
bsos = [
{
"id": "6820f3ca-6e8a-4ff4-8af7-8b3625d7d65%d" % i,
"payload": _PLD,
}
for i in range(5)
]
res = self.retry_post_json(self.root + "/storage/passwords", bsos)
res = res.json
self.assertEqual(len(res["success"]), 5)
# now deleting some of them
ids = ",".join(["6820f3ca-6e8a-4ff4-8af7-8b3625d7d65%d" % i for i in range(2)])
self.retry_delete(self.root + "/storage/passwords?ids=%s" % ids)
res = self.app.get(self.root + "/storage/passwords?ids=%s" % ids)
self.assertEqual(len(res.json), 0)
res = self.app.get(self.root + "/storage/passwords")
self.assertEqual(len(res.json), 3)
def test_specifying_ids_with_percent_encoded_query_string(self):
"""Test specifying ids with percent encoded query string."""