/
test_furl.py
1915 lines (1607 loc) · 72.4 KB
/
test_furl.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
# -*- coding: utf-8 -*-
#
# furl - URL manipulation made simple.
#
# Arthur Grunseid
# grunseid.com
# grunseid@gmail.com
#
# License: Build Amazing Things (Unlicense)
import sys
import warnings
from abc import ABCMeta, abstractmethod
import six
from six.moves import urllib
import furl
from furl.omdict1D import omdict1D
from furl.compat import OrderedDict as odict
PYTHON_27PLUS = sys.version_info >= (2, 7)
if PYTHON_27PLUS:
import unittest
else:
import unittest2 as unittest
#
# TODO(grun): Add tests for furl objects with strict=True. Make sure
# UserWarnings are raised when improperly encoded path, query, and
# fragment strings are provided.
#
@six.add_metaclass(ABCMeta)
class itemcontainer(object):
"""
Utility list subclasses to expose allitems() and iterallitems()
methods on different kinds of item containers - lists, dictionaries,
multivalue dictionaries, and query strings. This provides a common
iteration interface for looping through their items (including items
with repeated keys). original() is also provided to get access to a
copy of the original container.
"""
@abstractmethod
def allitems(self):
pass
@abstractmethod
def iterallitems(self):
pass
@abstractmethod
def original(self):
"""
Returns: A copy of the original data type. For example, an
itemlist would return a list, itemdict a dict, etc.
"""
pass
class itemlist(list, itemcontainer):
def allitems(self):
return list(self.iterallitems())
def iterallitems(self):
return iter(self)
def original(self):
return list(self)
class itemdict(odict, itemcontainer):
def allitems(self):
return list(self.items())
def iterallitems(self):
return iter(self.items())
def original(self):
return dict(self)
class itemomdict1D(omdict1D, itemcontainer):
def original(self):
return omdict1D(self)
class itemstr(str, itemcontainer):
def allitems(self):
# Keys and values get unquoted. i.e. 'a=a%20a' -> ['a', 'a a']. Empty
# values without '=' have value None.
items = []
parsed = urllib.parse.parse_qsl(self, keep_blank_values=True)
pairstrs = [s2 for s1 in self.split('&')
for s2 in s1.split(';')]
for (key, value), pairstr in six.moves.zip(parsed, pairstrs):
if key == urllib.parse.quote_plus(pairstr):
value = None
items.append((key, value))
return items
def iterallitems(self):
return iter(self.allitems())
def original(self):
return str(self)
class TestPath(unittest.TestCase):
def test_isdir_isfile(self):
for path in ['', '/']:
p = furl.Path(path)
assert p.isdir
assert not p.isfile
paths = ['dir1/', 'd1/d2/', 'd/d/d/d/d/', '/', '/dir1/', '/d1/d2/d3/']
for path in paths:
p = furl.Path(path)
assert p.isdir
assert not p.isfile
for path in ['dir1', 'd1/d2', 'd/d/d/d/d', '/dir1', '/d1/d2/d3']:
p = furl.Path(path)
assert p.isfile
assert not p.isdir
def test_leading_slash(self):
p = furl.Path('')
assert not p.isabsolute
assert not p.segments
assert p.isdir and p.isdir != p.isfile
assert str(p) == ''
p = furl.Path('/')
assert p.isabsolute
assert p.segments == ['']
assert p.isdir and p.isdir != p.isfile
assert str(p) == '/'
p = furl.Path('sup')
assert not p.isabsolute
assert p.segments == ['sup']
assert p.isfile and p.isdir != p.isfile
assert str(p) == 'sup'
p = furl.Path('/sup')
assert p.isabsolute
assert p.segments == ['sup']
assert p.isfile and p.isdir != p.isfile
assert str(p) == '/sup'
p = furl.Path('a/b/c')
assert not p.isabsolute
assert p.segments == ['a', 'b', 'c']
assert p.isfile and p.isdir != p.isfile
assert str(p) == 'a/b/c'
p = furl.Path('/a/b/c')
assert p.isabsolute
assert p.segments == ['a', 'b', 'c']
assert p.isfile and p.isdir != p.isfile
assert str(p) == '/a/b/c'
p = furl.Path('a/b/c/')
assert not p.isabsolute
assert p.segments == ['a', 'b', 'c', '']
assert p.isdir and p.isdir != p.isfile
assert str(p) == 'a/b/c/'
p.isabsolute = True
assert p.isabsolute
assert str(p) == '/a/b/c/'
def test_encoding(self):
encoded = ['a%20a', '/%7haypepps/', 'a/:@/a', 'a%2Fb']
unencoded = ['a+a', '/~haypepps/', 'a/:@/a', 'a/b']
for path in encoded:
assert str(furl.Path(path)) == path
for path in unencoded:
assert str(furl.Path(path)) == urllib.parse.quote(
path, "/:@-._~!$&'()*+,;=")
# Valid path segment characters should not be encoded.
for char in ":@-._~!$&'()*+,;=":
f = furl.furl().set(path=char)
assert str(f.path) == f.url == char
assert f.path.segments == [char]
# Invalid path segment characters should be encoded.
for char in ' ^`<>[]"?':
f = furl.furl().set(path=char)
assert str(f.path) == f.url == urllib.parse.quote(char)
assert f.path.segments == [char]
# Encode '/' within a path segment.
segment = 'a/b' # One path segment that includes the '/' character.
f = furl.furl().set(path=[segment])
assert str(f.path) == 'a%2Fb'
assert f.path.segments == [segment]
assert f.url == 'a%2Fb'
def test_load(self):
self._test_set_load(furl.Path.load)
def test_set(self):
self._test_set_load(furl.Path.set)
def _test_set_load(self, path_set_or_load):
p = furl.Path('a/b/c/')
assert path_set_or_load(p, 'asdf/asdf/') == p
assert not p.isabsolute
assert str(p) == 'asdf/asdf/'
assert path_set_or_load(p, ['a', 'b', 'c', '']) == p
assert not p.isabsolute
assert str(p) == 'a/b/c/'
assert path_set_or_load(p, ['', 'a', 'b', 'c', '']) == p
assert p.isabsolute
assert str(p) == '/a/b/c/'
def test_add(self):
# URL paths.
p = furl.furl('a/b/c/').path
assert p.add('d') == p
assert not p.isabsolute
assert str(p) == 'a/b/c/d'
assert p.add('/') == p
assert not p.isabsolute
assert str(p) == 'a/b/c/d/'
assert p.add(['e', 'f', 'e e', '']) == p
assert not p.isabsolute
assert str(p) == 'a/b/c/d/e/f/e%20e/'
p = furl.furl().path
assert not p.isabsolute
assert p.add('/') == p
assert p.isabsolute
assert str(p) == '/'
assert p.add('pump') == p
assert p.isabsolute
assert str(p) == '/pump'
p = furl.furl().path
assert not p.isabsolute
assert p.add(['', '']) == p
assert p.isabsolute
assert str(p) == '/'
assert p.add(['pump', 'dump', '']) == p
assert p.isabsolute
assert str(p) == '/pump/dump/'
p = furl.furl('http://sprop.ru/a/b/c/').path
assert p.add('d') == p
assert p.isabsolute
assert str(p) == '/a/b/c/d'
assert p.add('/') == p
assert p.isabsolute
assert str(p) == '/a/b/c/d/'
assert p.add(['e', 'f', 'e e', '']) == p
assert p.isabsolute
assert str(p) == '/a/b/c/d/e/f/e%20e/'
f = furl.furl('http://sprop.ru')
assert not f.path.isabsolute
f.path.add('sup')
assert f.path.isabsolute and str(f.path) == '/sup'
f = furl.furl('/mrp').add(path='sup')
assert str(f.path) == '/mrp/sup'
f = furl.furl('/').add(path='/sup')
assert f.path.isabsolute and str(f.path) == '/sup'
f = furl.furl('/hi').add(path='sup')
assert f.path.isabsolute and str(f.path) == '/hi/sup'
f = furl.furl('/hi').add(path='/sup')
assert f.path.isabsolute and str(f.path) == '/hi/sup'
f = furl.furl('/hi/').add(path='/sup')
assert f.path.isabsolute and str(f.path) == '/hi//sup'
# Fragment paths.
f = furl.furl('http://sprop.ru#mrp')
assert not f.fragment.path.isabsolute
f.fragment.path.add('sup')
assert not f.fragment.path.isabsolute
assert str(f.fragment.path) == 'mrp/sup'
f = furl.furl('http://sprop.ru#/mrp')
assert f.fragment.path.isabsolute
f.fragment.path.add('sup')
assert f.fragment.path.isabsolute
assert str(f.fragment.path) == '/mrp/sup'
def test_remove(self):
# Remove lists of path segments.
p = furl.Path('a/b/s%20s/')
assert p.remove(['b', 's s']) == p
assert str(p) == 'a/b/s%20s/'
assert p.remove(['b', 's s', '']) == p
assert str(p) == 'a/'
assert p.remove(['', 'a']) == p
assert str(p) == 'a/'
assert p.remove(['a']) == p
assert str(p) == 'a/'
assert p.remove(['a', '']) == p
assert str(p) == ''
p = furl.Path('a/b/s%20s/')
assert p.remove(['', 'b', 's s']) == p
assert str(p) == 'a/b/s%20s/'
assert p.remove(['', 'b', 's s', '']) == p
assert str(p) == 'a'
assert p.remove(['', 'a']) == p
assert str(p) == 'a'
assert p.remove(['a', '']) == p
assert str(p) == 'a'
assert p.remove(['a']) == p
assert str(p) == ''
p = furl.Path('a/b/s%20s/')
assert p.remove(['a', 'b', 's%20s', '']) == p
assert str(p) == 'a/b/s%20s/'
assert p.remove(['a', 'b', 's s', '']) == p
assert str(p) == ''
# Remove a path string.
p = furl.Path('a/b/s%20s/')
assert p.remove('b/s s/') == p # Encoding Warning.
assert str(p) == 'a/'
p = furl.Path('a/b/s%20s/')
assert p.remove('b/s%20s/') == p
assert str(p) == 'a/'
assert p.remove('a') == p
assert str(p) == 'a/'
assert p.remove('/a') == p
assert str(p) == 'a/'
assert p.remove('a/') == p
assert str(p) == ''
p = furl.Path('a/b/s%20s/')
assert p.remove('b/s s') == p # Encoding Warning.
assert str(p) == 'a/b/s%20s/'
p = furl.Path('a/b/s%20s/')
assert p.remove('b/s%20s') == p
assert str(p) == 'a/b/s%20s/'
assert p.remove('s%20s') == p
assert str(p) == 'a/b/s%20s/'
assert p.remove('s s') == p # Encoding Warning.
assert str(p) == 'a/b/s%20s/'
assert p.remove('b/s%20s/') == p
assert str(p) == 'a/'
assert p.remove('/a') == p
assert str(p) == 'a/'
assert p.remove('a') == p
assert str(p) == 'a/'
assert p.remove('a/') == p
assert str(p) == ''
p = furl.Path('a/b/s%20s/')
assert p.remove('a/b/s s/') == p # Encoding Warning.
assert str(p) == ''
# Remove True.
p = furl.Path('a/b/s%20s/')
assert p.remove(True) == p
assert str(p) == ''
def test_isabsolute(self):
paths = ['', '/', 'pump', 'pump/dump', '/pump/dump', '/pump/dump']
for path in paths:
# A URL path's isabsolute attribute is mutable if there's no
# netloc.
mutable = [
{}, # No scheme or netloc -> isabsolute is mutable.
{'scheme': 'nonempty'}] # Scheme, no netloc -> isabs mutable.
for kwargs in mutable:
f = furl.furl().set(path=path, **kwargs)
if path and path.startswith('/'):
assert f.path.isabsolute
else:
assert not f.path.isabsolute
f.path.isabsolute = False # No exception.
assert not f.path.isabsolute and not str(
f.path).startswith('/')
f.path.isabsolute = True # No exception.
assert f.path.isabsolute and str(f.path).startswith('/')
# A URL path's isabsolute attribute is read-only if there's
# a netloc.
readonly = [
# Netloc, no scheme -> isabsolute is read-only if path
# is non-empty.
{'netloc': 'nonempty'},
# Netloc and scheme -> isabsolute is read-only if path
# is non-empty.
{'scheme': 'nonempty', 'netloc': 'nonempty'}]
for kwargs in readonly:
f = furl.furl().set(path=path, **kwargs)
if path: # Exception raised.
with self.assertRaises(AttributeError):
f.path.isabsolute = False
with self.assertRaises(AttributeError):
f.path.isabsolute = True
else: # No exception raised.
f.path.isabsolute = False
assert not f.path.isabsolute and not str(
f.path).startswith('/')
f.path.isabsolute = True
assert f.path.isabsolute and str(f.path).startswith('/')
# A Fragment path's isabsolute attribute is never read-only.
f = furl.furl().set(fragment_path=path)
if path and path.startswith('/'):
assert f.fragment.path.isabsolute
else:
assert not f.fragment.path.isabsolute
f.fragment.path.isabsolute = False # No exception.
assert (not f.fragment.path.isabsolute and
not str(f.fragment.path).startswith('/'))
f.fragment.path.isabsolute = True # No exception.
assert f.fragment.path.isabsolute and str(
f.fragment.path).startswith('/')
# Sanity checks.
f = furl.furl().set(scheme='mailto', path='dad@pumps.biz')
assert str(f) == 'mailto:dad@pumps.biz' and not f.path.isabsolute
f.path.isabsolute = True # No exception.
assert str(f) == 'mailto:/dad@pumps.biz' and f.path.isabsolute
f = furl.furl().set(scheme='sup', fragment_path='/dad@pumps.biz')
assert str(
f) == 'sup:#/dad@pumps.biz' and f.fragment.path.isabsolute
f.fragment.path.isabsolute = False # No exception.
assert str(
f) == 'sup:#dad@pumps.biz' and not f.fragment.path.isabsolute
def test_normalize(self):
# Path not modified.
for path in ['', 'a', '/a', '/a/', '/a/b%20b/c', '/a/b%20b/c/']:
p = furl.Path(path)
assert p.normalize() is p and str(p) == str(p.normalize()) == path
# Path modified.
tonormalize = [
('//', '/'), ('//a', '/a'), ('//a/', '/a/'), ('//a///', '/a/'),
('////a/..//b', '/b'), ('/a/..//b//./', '/b/')]
for path, normalized in tonormalize:
p = furl.Path(path)
assert p.normalize() is p and str(p.normalize()) == normalized
def test_equality(self):
assert furl.Path() == furl.Path()
p1 = furl.furl('http://sprop.ru/a/b/c/').path
p11 = furl.furl('http://spep.ru/a/b/c/').path
p2 = furl.furl('http://sprop.ru/a/b/c/d/').path
assert p1 == p11 and str(p1) == str(p11)
assert p1 != p2 and str(p1) != str(p2)
def test_nonzero(self):
p = furl.Path()
assert not p
p = furl.Path('')
assert not p
p = furl.Path('')
assert not p
p.segments = ['']
assert p
p = furl.Path('asdf')
assert p
p = furl.Path('/asdf')
assert p
def test_unicode(self):
paths = ['/wiki/Восход', u'/wiki/Восход']
path_encoded = '/wiki/%D0%92%D0%BE%D1%81%D1%85%D0%BE%D0%B4'
for path in paths:
p = furl.Path(path)
assert str(p) == path_encoded
class TestQuery(unittest.TestCase):
def setUp(self):
# All interaction with parameters is unquoted unless that
# interaction is through an already encoded query string. In the
# case of an already encoded query string, like 'a=a%20a&b=b',
# its keys and values will be unquoted.
self.itemlists = list(map(itemlist, [
[], [(1, 1)], [(1, 1), (2, 2)], [
(1, 1), (1, 11), (2, 2), (3, 3)], [('', '')],
[('a', 1), ('b', 2), ('a', 3)], [
('a', 1), ('b', 'b'), ('a', 0.23)],
[(0.1, -0.9), (-0.1231, 12312.3123)], [
(None, None), (None, 'pumps')],
[('', ''), ('', '')], [('', 'a'), ('', 'b'),
('b', ''), ('b', 'b')], [('<', '>')],
[('=', '><^%'), ('><^%', '=')], [
("/?:@-._~!$'()*+,", "/?:@-._~!$'()*+,=")],
[('+', '-')], [('a%20a', 'a%20a')], [('/^`<>[]"', '/^`<>[]"=')],
[("/?:@-._~!$'()*+,", "/?:@-._~!$'()*+,=")],
]))
self.itemdicts = list(map(itemdict, [
{}, {1: 1, 2: 2}, {'1': '1', '2': '2',
'3': '3'}, {None: None}, {5.4: 4.5},
{'': ''}, {'': 'a', 'b': ''}, {
'pue': 'pue', 'a': 'a&a'}, {'=': '====='},
{'pue': 'pue', 'a': 'a%26a'}, {'%': '`', '`': '%'}, {'+': '-'},
{"/?:@-._~!$'()*+,": "/?:@-._~!$'()*+,="}, {
'%25': '%25', '%60': '%60'},
]))
self.itemomdicts = list(map(itemomdict1D, self.itemlists))
self.itemstrs = list(map(itemstr, [
# Basics.
'', 'a=a', 'a=a&b=b', 'q=asdf&check_keywords=yes&area=default',
'=asdf',
# Various quoted and unquoted parameters and values that
# will be unquoted.
'space=a+a&=a%26a', 'a a=a a&no encoding=sup', 'a+a=a+a',
'a%20=a+a', 'a%20a=a%20a', 'a+a=a%20a', 'space=a a&=a^a',
'a=a&s=s#s', '+=+', "/?:@-._~!$&'()*+,=/?:@-._~!$'()*+,=",
'a=a&c=c%5Ec', '<=>&^="', '%3C=%3E&%5E=%22', '%=%;`=`',
'%25=%25&%60=%60',
# Only keys, no values.
'asdfasdf', '/asdf/asdf/sdf', '*******', '!@#(*&@!#(*@!#', 'a&b&',
'a;b',
# Repeated parameters.
'a=a&a=a', 'space=a+a&space=b+b',
# Empty keys and/or values.
'=', 'a=', 'a=a&a=', '=a&=b',
# Semicolon delimiter, like 'a=a;b=b'.
'a=a;a=a', 'space=a+a;space=b+b',
]))
self.items = (self.itemlists + self.itemdicts + self.itemomdicts +
self.itemstrs)
def test_various(self):
for items in self.items:
q = furl.Query(items.original())
assert q.params.allitems() == items.allitems()
pairs = ['%s=%s' % (i[0], i[1]) for i in self._quote_items(items)]
# encode() and __str__().
assert str(q) == q.encode() == q.encode('&')
# encode() accepts both 'delimiter' and 'delimeter'. The
# latter was incorrectly used until furl v0.4.6.
e = q.encode
assert e(';') == e(delimiter=';') == e(delimeter=';')
# __nonzero__().
if items.allitems():
assert q
else:
assert not q
def test_load(self):
for items in self.items:
q = furl.Query(items.original())
for update in self.items:
assert q.load(update) == q
assert q.params.allitems() == update.allitems()
def test_add(self):
for items in self.items:
q = furl.Query(items.original())
runningsum = list(items.allitems())
for itemupdate in self.items:
assert q.add(itemupdate.original()) == q
for item in itemupdate.iterallitems():
runningsum.append(item)
assert q.params.allitems() == runningsum
def test_set(self):
for items in self.items:
q = furl.Query(items.original())
items_omd = omdict1D(items.allitems())
for update in self.items:
q.set(update)
items_omd.updateall(update)
assert q.params.allitems() == items_omd.allitems()
# The examples.
q = furl.Query({1: 1}).set([(1, None), (2, 2)])
assert q.params.allitems() == [(1, None), (2, 2)]
q = furl.Query({1: None, 2: None}).set([(1, 1), (2, 2), (1, 11)])
assert q.params.allitems() == [(1, 1), (2, 2), (1, 11)]
q = furl.Query({1: None}).set([(1, [1, 11, 111])])
assert q.params.allitems() == [(1, 1), (1, 11), (1, 111)]
# Further manual tests.
q = furl.Query([(2, None), (3, None), (1, None)])
q.set([(1, [1, 11]), (2, 2), (3, [3, 33])])
assert q.params.allitems() == [
(2, 2), (3, 3), (1, 1), (1, 11), (3, 33)]
def test_remove(self):
for items in self.items:
# Remove one key at a time.
q = furl.Query(items.original())
for key in dict(items.iterallitems()):
assert key in q.params
assert q.remove(key) == q
assert key not in q.params
# Remove multiple keys at a time (in this case all of them).
q = furl.Query(items.original())
if items.allitems():
assert q.params
allkeys = [key for key, value in items.allitems()]
assert q.remove(allkeys) == q
assert len(q.params) == 0
# Remove the whole query string with True.
q = furl.Query(items.original())
if items.allitems():
assert q.params
assert q.remove(True) == q
assert len(q.params) == 0
# List of keys to remove.
q = furl.Query([('a', '1'), ('b', '2'), ('b', '3'), ('a', '4')])
q.remove(['a', 'b'])
assert not list(q.params.items())
# List of items to remove.
q = furl.Query([('a', '1'), ('b', '2'), ('b', '3'), ('a', '4')])
q.remove([('a', '1'), ('b', '3')])
assert list(q.params.allitems()) == [('b', '2'), ('a', '4')]
# Dictionary of items to remove.
q = furl.Query([('a', '1'), ('b', '2'), ('b', '3'), ('a', '4')])
q.remove({'b': '3', 'a': '1'})
assert q.params.allitems() == [('b', '2'), ('a', '4')]
# Multivalue dictionary of items to remove.
q = furl.Query([('a', '1'), ('b', '2'), ('b', '3'), ('a', '4')])
omd = omdict1D([('a', '4'), ('b', '3'), ('b', '2')])
q.remove(omd)
assert q.params.allitems() == [('a', '1')]
def test_params(self):
# Basics.
q = furl.Query('a=a&b=b')
assert q.params == {'a': 'a', 'b': 'b'}
q.params['sup'] = 'sup'
assert q.params == {'a': 'a', 'b': 'b', 'sup': 'sup'}
del q.params['a']
assert q.params == {'b': 'b', 'sup': 'sup'}
q.params['b'] = 'BLROP'
assert q.params == {'b': 'BLROP', 'sup': 'sup'}
# Blanks keys and values are kept.
q = furl.Query('=')
assert q.params == {'': ''} and str(q) == '='
q = furl.Query('=&=')
assert q.params.allitems() == [('', ''), ('', '')] and str(q) == '=&='
q = furl.Query('a=&=b')
assert q.params == {'a': '', '': 'b'} and str(q) == 'a=&=b'
# ';' is a valid query delimiter.
q = furl.Query('=;=')
assert q.params.allitems() == [('', ''), ('', '')] and str(q) == '=&='
q = furl.Query('a=a;b=b;c=')
assert q.params == {
'a': 'a', 'b': 'b', 'c': ''} and str(q) == 'a=a&b=b&c='
# Non-string parameters are coerced to strings in the final
# query string.
q.params.clear()
q.params[99] = 99
q.params[None] = -1
q.params['int'] = 1
q.params['float'] = 0.39393
assert str(q) == '99=99&None=-1&int=1&float=0.39393'
# Spaces are encoded as '+'s. '+'s are encoded as '%2B'.
q.params.clear()
q.params['s s'] = 's s'
q.params['p+p'] = 'p+p'
assert str(q) == 's+s=s+s&p%2Bp=p%2Bp'
# Params is an omdict (ordered multivalue dictionary).
q.params.clear()
q.params.add('1', '1').set('2', '4').add('1', '11').addlist(
3, [3, 3, '3'])
assert q.params.getlist('1') == ['1', '11'] and q.params['1'] == '1'
assert q.params.getlist(3) == [3, 3, '3']
# Assign various things to Query.params and make sure
# Query.params is reinitialized, not replaced.
for items in self.items:
q.params = items.original()
assert isinstance(q.params, omdict1D)
pairs = six.moves.zip(q.params.iterallitems(), items.iterallitems())
for item1, item2 in pairs:
assert item1 == item2
# Value of '' -> '?param='. Value of None -> '?param'.
q = furl.Query('slrp')
assert str(q) == 'slrp' and q.params['slrp'] is None
q = furl.Query('slrp=')
assert str(q) == 'slrp=' and q.params['slrp'] == ''
q = furl.Query('prp=&slrp')
assert q.params['prp'] == '' and q.params['slrp'] is None
q.params['slrp'] = ''
assert str(q) == 'prp=&slrp=' and q.params['slrp'] == ''
def test_unicode(self):
pairs = [('Восход', 'testä'), (u'Восход', u'testä')]
key_encoded = '%D0%92%D0%BE%D1%81%D1%85%D0%BE%D0%B4'
value_encoded = 'test%C3%A4'
for key, value in pairs:
q = furl.Query('%s=%s' % (key, value))
assert q.params[key] == value
assert str(q) == '%s=%s' % (key_encoded, value_encoded)
q = furl.Query()
q.params[key] = value
assert q.params[key] == value
assert str(q) == '%s=%s' % (key_encoded, value_encoded)
def test_equality(self):
assert furl.Query() == furl.Query()
q1 = furl.furl('http://sprop.ru/?a=1&b=2').query
q11 = furl.furl('http://spep.ru/path/?a=1&b=2').query
q2 = furl.furl('http://sprop.ru/?b=2&a=1').query
assert q1 == q11 and str(q1) == str(q11)
assert q1 != q2 and str(q1) != str(q2)
def _quote_items(self, items):
# Calculate the expected querystring with proper query encoding.
# Valid query key characters: "/?:@-._~!$'()*,;"
# Valid query value characters: "/?:@-._~!$'()*,;="
allitems_quoted = []
for key, value in items.iterallitems():
pair = (urllib.parse.quote_plus(str(key), "/?:@-._~!$'()*,;"),
urllib.parse.quote_plus(str(value), "/?:@-._~!$'()*,;="))
allitems_quoted.append(pair)
return allitems_quoted
class TestQueryCompositionInterface(unittest.TestCase):
def test_interface(self):
class tester(furl.QueryCompositionInterface):
def __init__(self):
furl.QueryCompositionInterface.__init__(self)
def __setattr__(self, attr, value):
fqci = furl.QueryCompositionInterface
if not fqci.__setattr__(self, attr, value):
object.__setattr__(self, attr, value)
t = tester()
assert isinstance(t.query, furl.Query)
assert str(t.query) == ''
t.query = 'a=a&s=s s'
assert isinstance(t.query, furl.Query)
assert str(t.query) == 'a=a&s=s+s'
assert t.args == t.query.params == {'a': 'a', 's': 's s'}
class TestFragment(unittest.TestCase):
def test_basics(self):
f = furl.Fragment()
assert str(f.path) == '' and str(f.query) == '' and str(f) == ''
f.args['sup'] = 'foo'
assert str(f) == 'sup=foo'
f.path = 'yasup'
assert str(f) == 'yasup?sup=foo'
f.path = '/yasup'
assert str(f) == '/yasup?sup=foo'
assert str(f.query) == 'sup=foo'
f.query.params['sup'] = 'kwlpumps'
assert str(f) == '/yasup?sup=kwlpumps'
f.query = ''
assert str(f) == '/yasup'
f.path = ''
assert str(f) == ''
f.args['no'] = 'dads'
f.query.params['hi'] = 'gr8job'
assert str(f) == 'no=dads&hi=gr8job'
def test_load(self):
comps = [('', '', {}),
('?', '%3F', {}),
('??a??', '%3F%3Fa%3F%3F', {}),
('??a??=', '', {'?a??': ''}),
('schtoot', 'schtoot', {}),
('sch/toot/YOEP', 'sch/toot/YOEP', {}),
('/sch/toot/YOEP', '/sch/toot/YOEP', {}),
('schtoot?', 'schtoot%3F', {}),
('schtoot?NOP', 'schtoot%3FNOP', {}),
('schtoot?NOP=', 'schtoot', {'NOP': ''}),
('schtoot?=PARNT', 'schtoot', {'': 'PARNT'}),
('schtoot?NOP=PARNT', 'schtoot', {'NOP': 'PARNT'}),
('dog?machine?yes', 'dog%3Fmachine%3Fyes', {}),
('dog?machine=?yes', 'dog', {'machine': '?yes'}),
('schtoot?a=a&hok%20sprm', 'schtoot',
{'a': 'a', 'hok sprm': ''}),
('schtoot?a=a&hok sprm', 'schtoot',
{'a': 'a', 'hok sprm': ''}),
('sch/toot?a=a&hok sprm', 'sch/toot',
{'a': 'a', 'hok sprm': ''}),
('/sch/toot?a=a&hok sprm', '/sch/toot',
{'a': 'a', 'hok sprm': ''}),
]
for fragment, path, query in comps:
f = furl.Fragment()
f.load(fragment)
assert str(f.path) == path
assert f.query.params == query
def test_add(self):
f = furl.Fragment('')
assert f is f.add(path='one two three', args=[('a', 'a'), ('s', 's s')])
assert str(f) == 'one%20two%20three?a=a&s=s+s'
f = furl.Fragment('break?legs=broken')
assert f is f.add(path='horse bones', args=[('a', 'a'), ('s', 's s')])
assert str(f) == 'break/horse%20bones?legs=broken&a=a&s=s+s'
def test_set(self):
f = furl.Fragment('asdf?lol=sup&foo=blorp')
assert f is f.set(path='one two three', args=[('a', 'a'), ('s', 's s')])
assert str(f) == 'one%20two%20three?a=a&s=s+s'
assert f is f.set(path='!', separator=False)
assert f.separator is False
assert str(f) == '!a=a&s=s+s'
def test_remove(self):
f = furl.Fragment('a/path/great/job?lol=sup&foo=blorp')
assert f is f.remove(path='job', args=['lol'])
assert str(f) == 'a/path/great/?foo=blorp'
assert f is f.remove(path=['path', 'great'], args=['foo'])
assert str(f) == 'a/path/great/'
assert f is f.remove(path=['path', 'great', ''])
assert str(f) == 'a/'
assert f is f.remove(fragment=True)
assert str(f) == ''
def test_encoding(self):
f = furl.Fragment()
f.path = "/?:@-._~!$&'()*+,;="
assert str(f) == "/?:@-._~!$&'()*+,;="
f.query = [('a', 'a'), ('b b', 'NOPE')]
assert str(f) == "/%3F:@-._~!$&'()*+,;=?a=a&b+b=NOPE"
f.separator = False
assert str(f) == "/?:@-._~!$&'()*+,;=a=a&b+b=NOPE"
f = furl.Fragment()
f.path = "/?:@-._~!$&'()*+,;= ^`<>[]"
assert str(f) == "/?:@-._~!$&'()*+,;=%20%5E%60%3C%3E%5B%5D"
f.query = [('a', 'a'), ('b b', 'NOPE')]
assert str(
f) == "/%3F:@-._~!$&'()*+,;=%20%5E%60%3C%3E%5B%5D?a=a&b+b=NOPE"
f.separator = False
assert str(f) == "/?:@-._~!$&'()*+,;=%20%5E%60%3C%3E%5B%5Da=a&b+b=NOPE"
f = furl.furl()
f.fragment = 'a?b?c?d?'
assert f.url == '#a?b?c?d?'
# TODO(grun): Once encoding has been fixed with URLPath and
# FragmentPath, the below line should be:
#
# assert str(f.fragment) == str(f.path) == 'a?b?c?d?'
#
assert str(f.fragment) == 'a?b?c?d?'
def test_equality(self):
assert furl.Fragment() == furl.Fragment()
f1 = furl.furl('http://sprop.ru/#ja').fragment
f11 = furl.furl('http://spep.ru/#ja').fragment
f2 = furl.furl('http://sprop.ru/#nein').fragment
assert f1 == f11 and str(f1) == str(f11)
assert f1 != f2 and str(f1) != str(f2)
def test_nonzero(self):
f = furl.Fragment()
assert not f
f = furl.Fragment('')
assert not f
f = furl.Fragment('asdf')
assert f
f = furl.Fragment()
f.path = 'sup'
assert f
f = furl.Fragment()
f.query = 'a=a'
assert f
f = furl.Fragment()
f.path = 'sup'
f.query = 'a=a'
assert f
f = furl.Fragment()
f.path = 'sup'
f.query = 'a=a'
f.separator = False
assert f
class TestFragmentCompositionInterface(unittest.TestCase):
def test_interface(self):
class tester(furl.FragmentCompositionInterface):
def __init__(self):
furl.FragmentCompositionInterface.__init__(self)
def __setattr__(self, attr, value):
ffci = furl.FragmentCompositionInterface
if not ffci.__setattr__(self, attr, value):
object.__setattr__(self, attr, value)
t = tester()
assert isinstance(t.fragment, furl.Fragment)
assert isinstance(t.fragment.path, furl.Path)
assert isinstance(t.fragment.query, furl.Query)
assert str(t.fragment) == ''
assert t.fragment.separator
assert str(t.fragment.path) == ''
assert str(t.fragment.query) == ''
t.fragment = 'animal meats'
assert isinstance(t.fragment, furl.Fragment)
t.fragment.path = 'pump/dump'
t.fragment.query = 'a=a&s=s+s'
assert isinstance(t.fragment.path, furl.Path)
assert isinstance(t.fragment.query, furl.Query)
assert str(t.fragment.path) == 'pump/dump'
assert t.fragment.path.segments == ['pump', 'dump']
assert not t.fragment.path.isabsolute
assert str(t.fragment.query) == 'a=a&s=s+s'
assert t.fragment.args == t.fragment.query.params == {
'a': 'a', 's': 's s'}
class TestFurl(unittest.TestCase):
def setUp(self):
# Don't hide duplicate Warnings. Test for all of them.
warnings.simplefilter("always")
def _param(self, url, key, val):
# Note: urlparse.urlsplit() doesn't separate the query from the
# path for all schemes, only those schemes in the list
# urlparse.uses_query. So, as a result of using
# urlparse.urlsplit(), this little helper function only works
# when provided URLs whos schemes are also in
# urlparse.uses_query.
items = urllib.parse.parse_qsl(urllib.parse.urlsplit(url).query, True)
return (key, val) in items
def test_unicode(self):
paths = ['Восход', u'Восход']
pairs = [('testö', 'testä'), (u'testö', u'testä')]
path_encoded = u'%D0%92%D0%BE%D1%81%D1%85%D0%BE%D0%B4'