forked from sashahart/cookies
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_cookies.py
2447 lines (2215 loc) · 94.5 KB
/
test_cookies.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for code in cookies.py.
"""
from __future__ import unicode_literals
import re
import sys
import logging
if sys.version_info < (3, 0, 0):
from urllib import quote, unquote
else:
from urllib.parse import quote, unquote
unichr = chr
basestring = str
from datetime import datetime, tzinfo, timedelta
from pytest import raises
from cookies import (
InvalidCookieError, InvalidCookieAttributeError,
Definitions,
Cookie, Cookies,
render_date, parse_date,
parse_string, parse_value, parse_domain, parse_path,
parse_one_response,
encode_cookie_value, encode_extension_av,
valid_value, valid_date, valid_domain, valid_path,
strip_spaces_and_quotes, _total_seconds,
)
class RFC1034:
"""Definitions from RFC 1034: 'DOMAIN NAMES - CONCEPTS AND FACILITIES'
section 3.5, as cited in RFC 6265 4.1.1.
"""
digit = "[0-9]"
letter = "[A-Za-z]"
let_dig = "[0-9A-Za-z]"
let_dig_hyp = "[0-9A-Za-z\-]"
assert "\\" in let_dig_hyp
ldh_str = "%s+" % let_dig_hyp
label = "(?:%s|%s|%s)" % (
letter,
letter + let_dig,
letter + ldh_str + let_dig)
subdomain = "(?:%s\.)*(?:%s)" % (label, label)
domain = "( |%s)" % (subdomain)
def test_sanity(self):
"Basic smoke tests that definitions transcribed OK"
match = re.compile("^%s\Z" % self.domain).match
assert match("A.ISI.EDU")
assert match("XX.LCS.MIT.EDU")
assert match("SRI-NIC.ARPA")
assert not match("foo+bar")
assert match("foo.com")
assert match("foo9.com")
assert not match("9foo.com")
assert not match("26.0.0.73.COM")
assert not match(".woo.com")
assert not match("blop.foo.")
assert match("foo-bar.com")
assert not match("-foo.com")
assert not match("foo.com-")
class RFC1123:
"""Definitions from RFC 1123: "Requirements for Internet Hosts --
Application and Support" section 2.1, cited in RFC 6265 section
4.1.1 as an update to RFC 1034.
Here this is really just used for testing Domain attribute values.
"""
# Changed per 2.1 (similar to some changes in RFC 1101)
# this implementation is a bit simpler...
# n.b.: there are length limits in the real thing
label = "{let_dig}(?:(?:{let_dig_hyp}+)?{let_dig})?".format(
let_dig=RFC1034.let_dig, let_dig_hyp=RFC1034.let_dig_hyp)
subdomain = "(?:%s\.)*(?:%s)" % (label, label)
domain = "( |%s)" % (subdomain)
def test_sanity(self):
"Basic smoke tests that definitions transcribed OK"
match = re.compile("^%s\Z" % self.domain).match
assert match("A.ISI.EDU")
assert match("XX.LCS.MIT.EDU")
assert match("SRI-NIC.ARPA")
assert not match("foo+bar")
assert match("foo.com")
assert match("9foo.com")
assert match("3Com.COM")
assert match("3M.COM")
class RFC2616:
"""Definitions from RFC 2616 section 2.2, as cited in RFC 6265 4.1.1
"""
SEPARATORS = '()<>@,;:\\"/[]?={} \t'
class RFC5234:
"""Basic definitions per RFC 5234: 'Augmented BNF for Syntax
Specifications'
"""
CHAR = "".join([chr(i) for i in range(0, 127 + 1)])
CTL = "".join([chr(i) for i in range(0, 31 + 1)]) + "\x7f"
# this isn't in the RFC but it can be handy
NONCTL = "".join([chr(i) for i in range(32, 127)])
# this is what the RFC says about a token more or less verbatim
TOKEN = "".join(sorted(set(NONCTL) - set(RFC2616.SEPARATORS)))
class FixedOffsetTz(tzinfo):
"""A tzinfo subclass for attaching to datetime objects.
Used for various tests involving date parsing, since Python stdlib does not
obviously provide tzinfo subclasses and testing this module only requires
a very simple one.
"""
def __init__(self, offset):
# tzinfo.utcoffset() throws an error for sub-minute amounts,
# so round
minutes = round(offset / 60.0, 0)
self.__offset = timedelta(minutes=minutes)
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return "FixedOffsetTz" + str(self.__offset.seconds)
def dst(self, dt):
return timedelta(0)
class TestInvalidCookieError(object):
"""Exercise the trivial behavior of the InvalidCookieError exception.
"""
def test_simple(self):
"This be the test"
def exception(data):
"Gather an InvalidCookieError exception"
try:
raise InvalidCookieError(data)
except InvalidCookieError as exception:
return exception
# other exceptions will pass through
return None
assert exception("no donut").data == "no donut"
# Spot check for obvious junk in loggable representations.
e = exception("yay\x00whee")
assert "\x00" not in repr(e)
assert "\x00" not in str(e)
assert "yaywhee" not in repr(e)
assert "yaywhee" not in str(e)
assert "\n" not in repr(exception("foo\nbar"))
class TestInvalidCookieAttributeError(object):
"""Exercise the trivial behavior of InvalidCookieAttributeError.
"""
def exception(self, *args, **kwargs):
"Generate an InvalidCookieAttributeError exception naturally"
try:
raise InvalidCookieAttributeError(*args, **kwargs)
except InvalidCookieAttributeError as exception:
return exception
return None
def test_simple(self):
e = self.exception("foo", "bar")
assert e.name == "foo"
assert e.value == "bar"
def test_junk_in_loggables(self):
# Spot check for obvious junk in loggable representations.
# This isn't completely idle: for example, nulls are ignored in
# %-formatted text, and this could be very misleading
e = self.exception("ya\x00y", "whee")
assert "\x00" not in repr(e)
assert "\x00" not in str(e)
assert "yay" not in repr(e)
assert "yay" not in str(e)
e = self.exception("whee", "ya\x00y")
assert "\x00" not in repr(e)
assert "\x00" not in str(e)
assert "yay" not in repr(e)
assert "yay" not in str(e)
assert "\n" not in repr(self.exception("yay", "foo\nbar"))
assert "\n" not in repr(self.exception("foo\nbar", "yay"))
def test_no_name(self):
# not recommended to do this, but we want to handle it if people do
e = self.exception(None, "stuff")
assert e.name == None
assert e.value == "stuff"
assert e.reason == None
assert 'stuff' in str(e)
class TestDefinitions(object):
"""Test the patterns in cookies.Definitions against specs.
"""
def test_cookie_name(self, check_unicode=False):
"""Check COOKIE_NAME against the token definition in RFC 2616 2.2 (as
cited in RFC 6265):
token = 1*<any CHAR except CTLs or separators>
separators = "(" | ")" | "<" | ">" | "@"
| "," | ";" | ":" | "\" | <">
| "/" | "[" | "]" | "?" | "="
| "{" | "}" | SP | HT
(Definitions.COOKIE_NAME is regex-ready while RFC5234.TOKEN is more
clearly related to the RFC; they should be functionally the same)
"""
regex = Definitions.COOKIE_NAME_RE
assert regex.match(RFC5234.TOKEN)
assert not regex.match(RFC5234.NONCTL)
for c in RFC5234.CTL:
assert not regex.match(c)
for c in RFC2616.SEPARATORS:
# Skip special case - some number of Java and PHP apps have used
# colon in names, while this is dumb we want to not choke on this
# by default since it may be the single biggest cause of bugs filed
# against Python's cookie libraries
if c == ':':
continue
assert not regex.match(c)
# Unicode over 7 bit ASCII shouldn't match, but this takes a while
if check_unicode:
for i in range(127, 0x10FFFF + 1):
assert not regex.match(unichr(i))
def test_cookie_octet(self):
"""Check COOKIE_OCTET against the definition in RFC 6265:
cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
; US-ASCII characters excluding CTLs,
; whitespace DQUOTE, comma, semicolon,
; and backslash
"""
match = re.compile("^[%s]+\Z" % Definitions.COOKIE_OCTET).match
for c in RFC5234.CTL:
assert not match(c)
assert not match("a%sb" % c)
# suspect RFC typoed 'whitespace, DQUOTE' as 'whitespace DQUOTE'
assert not match(' ')
assert not match('"')
assert not match(',')
assert not match(';')
assert not match('\\')
# the spec above DOES include =.-
assert match("=")
assert match(".")
assert match("-")
# Check that everything else in CHAR works.
safe_cookie_octet = "".join(sorted(
set(RFC5234.NONCTL) - set(' ",;\\')))
assert match(safe_cookie_octet)
def test_set_cookie_header(self):
"""Smoke test SET_COOKIE_HEADER (used to compile SET_COOKIE_HEADER_RE)
against HEADER_CASES.
"""
# should match if expectation is not an error, shouldn't match if it is
# an error. set-cookie-header is for responses not requests, so use
# response expectation rather than request expectation
match = re.compile(Definitions.SET_COOKIE_HEADER).match
for case in HEADER_CASES:
arg, kwargs, request_result, expected = case
this_match = match(arg)
if expected and not isinstance(expected, type):
assert this_match, "should match as response: " + repr(arg)
else:
if not request_result:
assert not this_match, \
"should not match as response: " + repr(arg)
def test_cookie_cases(self):
"""Smoke test COOKIE_HEADER (used to compile COOKIE_HEADER_RE) against
HEADER_CASES.
"""
# should match if expectation is not an error, shouldn't match if it is
# an error. cookie-header is for requests not responses, so use request
# expectation rather than response expectation
match = re.compile(Definitions.COOKIE).match
for case in HEADER_CASES:
arg, kwargs, expected, response_result = case
this_match = match(arg)
if expected and not isinstance(expected, type):
assert this_match, "should match as request: " + repr(arg)
else:
if not response_result:
assert not this_match, \
"should not match as request: " + repr(arg)
def test_cookie_pattern(self):
"""Smoke test Definitions.COOKIE (used to compile COOKIE_RE) against
the grammar for cookie-header as in RFC 6265.
cookie-header = "Cookie:" OWS cookie-string OWS
cookie-string = cookie-pair *( ";" SP cookie-pair )
cookie-pair = cookie-name "=" cookie-value
cookie-name = token
cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
cookie-name and cookie-value are not broken apart for separate
testing, as the former is essentially just token and the latter
essentially just cookie-octet.
"""
match = re.compile(Definitions.COOKIE).match
# cookie-pair behavior around =
assert match("foo").group('invalid')
assert match("foo=bar")
# Looks dumb, but this is legal because "=" is valid for cookie-octet.
assert match("a=b=c")
# DQUOTE *cookie-octet DQUOTE - allowed
assert match('foo="bar"')
# for testing on the contents of cookie name and cookie value,
# see test_cookie_name and test_cookie_octet.
regex = re.compile(Definitions.COOKIE)
correct = [
('foo', 'yar', ''),
('bar', 'eeg', ''),
('baz', 'wog', ''),
('frob', 'laz', '')]
def assert_correct(s):
#naive = re.findall(" *([^;]+)=([^;]+) *(?:;|\Z)", s)
result = regex.findall(s)
assert result == correct
# normal-looking case should work normally
assert_correct("foo=yar; bar=eeg; baz=wog; frob=laz")
# forgive lack of whitespace as long as semicolons are explicit
assert_correct("foo=yar;bar=eeg;baz=wog;frob=laz")
# forgive too much whitespace AROUND values
assert_correct(" foo=yar; bar=eeg; baz=wog; frob=laz ")
# Actually literal spaces are NOT allowed in cookie values per RFC 6265
# and it is UNWISE to put them in without escaping. But we want the
# flexibility to let this pass with a warning, because this is the kind
# of bad idea which is very common and results in loud complaining on
# issue trackers on the grounds that PHP does it or something. So the
# regex is weakened, but the presence of a space should still be at
# least noted, and an exception must be raised if = is also used
# - because that would often indicate the loss of cookies due to
# forgotten separator, as in "foo=yar bar=eeg baz=wog frob=laz".
assert regex.findall("foo=yar; bar=eeg; baz=wog; frob=l az") == [
('foo', 'yar', ''),
('bar', 'eeg', ''),
('baz', 'wog', ''),
# handle invalid internal whitespace.
('frob', 'l az', '')
]
# Without semicolons or inside semicolon-delimited blocks, the part
# before the first = should be interpreted as a name, and the rest as
# a value (since = is not forbidden for cookie values). Thus:
result = regex.findall("foo=yarbar=eegbaz=wogfrob=laz")
assert result[0][0] == 'foo'
assert result[0][1] == 'yarbar=eegbaz=wogfrob=laz'
assert result[0][2] == ''
# Make some bad values and see that it's handled reasonably.
# (related to http://bugs.python.org/issue2988)
# don't test on semicolon because the regexp stops there, reasonably.
for c in '\x00",\\':
nasty = "foo=yar" + c + "bar"
result = regex.findall(nasty + "; baz=bam")
# whole bad pair reported in the 'invalid' group (the third one)
assert result[0][2] == nasty
# kept on truckin' and got the other one just fine.
assert result[1] == ('baz', 'bam', '')
# same thing if the good one is first and the bad one second
result = regex.findall("baz=bam; " + nasty)
assert result[0] == ('baz', 'bam', '')
assert result[1][2] == ' ' + nasty
def test_extension_av(self, check_unicode=False):
"""Test Definitions.EXTENSION_AV against extension-av per RFC 6265.
extension-av = <any CHAR except CTLs or ";">
"""
# This is how it's defined in RFC 6265, just about verbatim.
extension_av_explicit = "".join(sorted(
set(RFC5234.CHAR) - set(RFC5234.CTL + ";")))
# ... that should turn out to be the same as Definitions.EXTENSION_AV
match = re.compile("^([%s]+)\Z" % Definitions.EXTENSION_AV).match
# Verify I didn't mess up on escaping here first
assert match(r']')
assert match(r'[')
assert match(r"'")
assert match(r'"')
assert match("\\")
assert match(extension_av_explicit)
# There should be some CHAR not matched
assert not match(RFC5234.CHAR)
# Every single CTL should not match
for c in RFC5234.CTL + ";":
assert not match(c)
# Unicode over 7 bit ASCII shouldn't match, but this takes a while
if check_unicode:
for i in range(127, 0x10FFFF + 1):
assert not match(unichr(i))
def test_max_age_av(self):
"Smoke test Definitions.MAX_AGE_AV"
# Not a lot to this, it's just digits
match = re.compile("^%s\Z" % Definitions.MAX_AGE_AV).match
assert not match("")
assert not match("Whiskers")
assert not match("Max-Headroom=992")
for c in "123456789":
assert not match(c)
assert match("Max-Age=%s" % c)
assert not match("Max-Age=0")
assert not match("Max-Age=029")
for c in RFC5234.CHAR:
assert not match(c)
def test_label(self, check_unicode=False):
"Test label, as used in Domain attribute"
match = re.compile("^(%s)\Z" % Definitions.LABEL).match
for i in range(0, 10):
assert match(str(i))
assert not match(".")
assert not match(",")
for c in RFC5234.CTL:
assert not match("a%sb" % c)
assert not match("%sb" % c)
assert not match("a%s" % c)
# Unicode over 7 bit ASCII shouldn't match, but this takes a while
if check_unicode:
for i in range(127, 0x10FFFF + 1):
assert not match(unichr(i))
def test_domain_av(self):
"Smoke test Definitions.DOMAIN_AV"
# This is basically just RFC1123.subdomain, which has its own
# assertions in the class definition
bad_domains = [
""
]
good_domains = [
"foobar.com",
"foo-bar.com",
"3Com.COM"
]
# First test DOMAIN via DOMAIN_RE
match = Definitions.DOMAIN_RE.match
for domain in bad_domains:
assert not match(domain)
for domain in good_domains:
assert match(domain)
# Now same tests through DOMAIN_AV
match = re.compile("^%s\Z" % Definitions.DOMAIN_AV).match
for domain in bad_domains:
assert not match("Domain=%s" % domain)
for domain in good_domains:
assert not match(domain)
assert match("Domain=%s" % domain)
# This is NOT valid and shouldn't be tolerated in cookies we create,
# but it should be tolerated in existing cookies since people do it;
# interpreted by stripping the initial .
assert match("Domain=.foo.net")
def test_path_av(self):
"Smoke test PATH and PATH_AV"
# This is basically just EXTENSION_AV, see test_extension_av
bad_paths = [
""
]
good_paths = [
"/",
"/foo",
"/foo/bar"
]
match = Definitions.PATH_RE.match
for path in bad_paths:
assert not match(path)
for path in good_paths:
assert match(path)
match = re.compile("^%s\Z" % Definitions.PATH_AV).match
for path in bad_paths:
assert not match("Path=%s" % path)
for path in good_paths:
assert not match(path)
assert match("Path=%s" % path)
def test_months(self):
"""Sanity checks on MONTH_SHORT and MONTH_LONG month name recognizers.
The RFCs set these in stone, they aren't locale-dependent.
"""
match = re.compile(Definitions.MONTH_SHORT).match
assert match("Jan")
assert match("Feb")
assert match("Mar")
assert match("Apr")
assert match("May")
assert match("Jun")
assert match("Jul")
assert match("Aug")
assert match("Sep")
assert match("Oct")
assert match("Nov")
assert match("Dec")
match = re.compile(Definitions.MONTH_LONG).match
assert match("January")
assert match("February")
assert match("March")
assert match("April")
assert match("May")
assert match("June")
assert match("July")
assert match("August")
assert match("September")
assert match("October")
assert match("November")
assert match("December")
def test_weekdays(self):
"""Sanity check on WEEKDAY_SHORT and WEEKDAY_LONG weekday
recognizers.
The RFCs set these in stone, they aren't locale-dependent.
"""
match = re.compile(Definitions.WEEKDAY_SHORT).match
assert match("Mon")
assert match("Tue")
assert match("Wed")
assert match("Thu")
assert match("Fri")
assert match("Sat")
assert match("Sun")
match = re.compile(Definitions.WEEKDAY_LONG).match
assert match("Monday")
assert match("Tuesday")
assert match("Wednesday")
assert match("Thursday")
assert match("Friday")
assert match("Saturday")
assert match("Sunday")
def test_day_of_month(self):
"""Check that the DAY_OF_MONTH regex allows all actual days, but
excludes obviously wrong ones (so they are tossed in the first pass).
"""
match = re.compile(Definitions.DAY_OF_MONTH).match
for day in ['01', '02', '03', '04', '05', '06', '07', '08', '09', ' 1',
' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9', '1', '2', '3',
'4', '5', '6', '7', '8', '9'] \
+ [str(i) for i in range(10, 32)]:
assert match(day)
assert not match("0")
assert not match("00")
assert not match("000")
assert not match("111")
assert not match("99")
assert not match("41")
def test_expires_av(self):
"Smoke test the EXPIRES_AV regex pattern"
# Definitions.EXPIRES_AV is actually pretty bad because it's a disaster
# to test three different date formats with lots of definition
# dependencies, and odds are good that other implementations are loose.
# so this parser is also loose. "liberal in what you accept,
# conservative in what you produce"
match = re.compile("^%s\Z" % Definitions.EXPIRES_AV).match
assert not match("")
assert not match("Expires=")
assert match("Expires=Tue, 15-Jan-2013 21:47:38 GMT")
assert match("Expires=Sun, 06 Nov 1994 08:49:37 GMT")
assert match("Expires=Sunday, 06-Nov-94 08:49:37 GMT")
assert match("Expires=Sun Nov 6 08:49:37 1994")
# attributed to Netscape in RFC 2109 10.1.2
assert match("Expires=Mon, 13-Jun-93 10:00:00 GMT")
assert not match("Expires=S9n, 06 Nov 1994 08:49:37 GMT")
assert not match("Expires=Sun3ay, 06-Nov-94 08:49:37 GMT")
assert not match("Expires=S9n Nov 6 08:49:37 1994")
assert not match("Expires=Sun, A6 Nov 1994 08:49:37 GMT")
assert not match("Expires=Sunday, 0B-Nov-94 08:49:37 GMT")
assert not match("Expires=Sun No8 6 08:49:37 1994")
assert not match("Expires=Sun, 06 N3v 1994 08:49:37 GMT")
assert not match("Expires=Sunday, 06-N8v-94 08:49:37 GMT")
assert not match("Expires=Sun Nov A 08:49:37 1994")
assert not match("Expires=Sun, 06 Nov 1B94 08:49:37 GMT")
assert not match("Expires=Sunday, 06-Nov-C4 08:49:37 GMT")
assert not match("Expires=Sun Nov 6 08:49:37 1Z94")
def test_no_obvious_need_for_disjunctive_attr_pattern(self):
"""Smoke test the assumption that extension-av is a reasonable set of
chars for all attrs (and thus that there is no reason to use a fancy
disjunctive pattern in the findall that splits out the attrs, freeing
us to use EXTENSION_AV instead).
If this works, then ATTR should work
"""
match = re.compile("^[%s]+\Z" % Definitions.EXTENSION_AV).match
assert match("Expires=Sun, 06 Nov 1994 08:49:37 GMT")
assert match("Expires=Sunday, 06-Nov-94 08:49:37 GMT")
assert match("Expires=Sun Nov 6 08:49:37 1994")
assert match("Max-Age=14658240962")
assert match("Domain=FoO.b9ar.baz")
assert match("Path=/flakes")
assert match("Secure")
assert match("HttpOnly")
def test_attr(self):
"""Smoke test ATTR, used to compile ATTR_RE.
"""
match = re.compile(Definitions.ATTR).match
def recognized(pattern):
"macro for seeing if ATTR recognized something"
this_match = match(pattern)
if not this_match:
return False
groupdict = this_match.groupdict()
if groupdict['unrecognized']:
return False
return True
# Quickly test that a batch of attributes matching the explicitly
# recognized patterns make it through without anything in the
# 'unrecognized' catchall capture group.
for pattern in [
"Secure",
"HttpOnly",
"Max-Age=9523052",
"Domain=frobble.com",
"Domain=3Com.COM",
"Path=/",
"Expires=Wed, 09 Jun 2021 10:18:14 GMT",
]:
assert recognized(pattern)
# Anything else is in extension-av and that's very broad;
# see test_extension_av for that test.
# This is only about the recognized ones.
assert not recognized("Frob=mugmannary")
assert not recognized("Fqjewp@1j5j510923")
assert not recognized(";aqjwe")
assert not recognized("ETJpqw;fjw")
assert not recognized("fjq;")
assert not recognized("Expires=\x00")
# Verify interface from regexp for extracting values isn't changed;
# a little rigidity here is a good idea
expires = "Wed, 09 Jun 2021 10:18:14 GMT"
m = match("Expires=%s" % expires)
assert m.group("expires") == expires
max_age = "233951698"
m = match("Max-Age=%s" % max_age)
assert m.group("max_age") == max_age
domain = "flarp"
m = match("Domain=%s" % domain)
assert m.group("domain") == domain
path = "2903"
m = match("Path=%s" % path)
assert m.group("path") == path
m = match("Secure")
assert m.group("secure")
assert not m.group("httponly")
m = match("HttpOnly")
assert not m.group("secure")
assert m.group("httponly")
def test_date_accepts_formats(self):
"""Check that DATE matches most formats used in Expires: headers,
and explain what the different formats are about.
The value extraction of this regexp is more comprehensively exercised
by test_date_parsing().
"""
# Date formats vary widely in the wild. Even the standards vary widely.
# This series of tests does spot-checks with instances of formats that
# it makes sense to support. In the following comments, each format is
# discussed and the rationale for the overall regexp is developed.
match = re.compile(Definitions.DATE).match
# The most common formats, related to the old Netscape cookie spec
# (NCSP), are supposed to follow this template:
#
# Wdy, DD-Mon-YYYY HH:MM:SS GMT
#
# (where 'Wdy' is a short weekday, and 'Mon' is a named month).
assert match("Mon, 20-Jan-1994 00:00:00 GMT")
# Similarly, RFC 850 proposes this format:
#
# Weekday, DD-Mon-YY HH:MM:SS GMT
#
# (with a long-form weekday and a 2-digit year).
assert match("Tuesday, 12-Feb-92 23:25:42 GMT")
# RFC 1036 obsoleted the RFC 850 format:
#
# Wdy, DD Mon YY HH:MM:SS GMT
#
# (shortening the weekday format and changing dashes to spaces).
assert match("Wed, 30 Mar 92 13:16:12 GMT")
# RFC 6265 cites a definition from RFC 2616, which uses the RFC 1123
# definition but limits it to GMT (consonant with NCSP). RFC 1123
# expanded RFC 822 with 2-4 digit years (more permissive than NCSP);
# RFC 822 left weekday and seconds as optional, and a day of 1-2 digits
# (all more permissive than NCSP). Giving something like this:
#
# [Wdy, ][D]D Mon [YY]YY HH:MM[:SS] GMT
#
assert match("Thu, 3 Apr 91 12:46 GMT")
# No weekday, two digit year.
assert match("13 Apr 91 12:46 GMT")
# Similarly, there is RFC 2822:
#
# [Wdy, ][D]D Mon YYYY HH:MM[:SS] GMT
# (which only differs in requiring a 4-digit year, where RFC 1123
# permits 2 or 3 digit years).
assert match("13 Apr 1991 12:46 GMT")
assert match("Wed, 13 Apr 1991 12:46 GMT")
# The generalized format given above encompasses RFC 1036 and RFC 2822
# and would encompass NCSP except for the dashes; allowing long-form
# weekdays also encompasses the format proposed in RFC 850. Taken
# together, this should cover something like 99% of Expires values
# (see, e.g., https://bugzilla.mozilla.org/show_bug.cgi?id=610218)
# Finally, we also want to support asctime format, as mentioned in RFC
# 850 and RFC 2616 and occasionally seen in the wild:
# Wdy Mon DD HH:MM:SS YYYY
# e.g.: Sun Nov 6 08:49:37 1994
assert match("Sun Nov 6 08:49:37 1994")
assert match("Sun Nov 26 08:49:37 1994")
# Reportedly someone has tacked 'GMT' on to the end of an asctime -
# although this is not RFC valid, it is pretty harmless
assert match("Sun Nov 26 08:49:37 1994 GMT")
# This test is not passed until it is shown that it wasn't trivially
# because DATE was matching .* or similar. This isn't intended to be
# a thorough test, just rule out the obvious reason. See test_date()
# for a more thorough workout of the whole parse and render mechanisms
assert not match("")
assert not match(" ")
assert not match("wobbly")
assert not match("Mon")
assert not match("Mon, 20")
assert not match("Mon, 20 Jan")
assert not match("Mon, 20,Jan,1994 00:00:00 GMT")
assert not match("Tuesday, 12-Feb-992 23:25:42 GMT")
assert not match("Wed, 30 Mar 92 13:16:1210 GMT")
assert not match("Wed, 30 Mar 92 13:16:12:10 GMT")
assert not match("Thu, 3 Apr 91 12:461 GMT")
def test_eol(self):
"""Test that the simple EOL regex works basically as expected.
"""
split = Definitions.EOL.split
assert split("foo\nbar") == ["foo", "bar"]
assert split("foo\r\nbar") == ["foo", "bar"]
letters = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
assert split("\n".join(letters)) == letters
assert split("\r\n".join(letters)) == letters
def test_compiled(self):
"""Check that certain patterns are present as compiled regexps
"""
re_type = type(re.compile(''))
def present(name):
"Macro for testing existence of an re in Definitions"
item = getattr(Definitions, name)
return item and isinstance(item, re_type)
assert present("COOKIE_NAME_RE")
assert present("COOKIE_RE")
assert present("SET_COOKIE_HEADER_RE")
assert present("ATTR_RE")
assert present("DATE_RE")
assert present("EOL")
def _test_init(cls, args, kwargs, expected):
"Core instance test function for test_init"
print("test_init", cls, args, kwargs)
try:
instance = cls(*args, **kwargs)
except Exception as exception:
if type(exception) == expected:
return
logging.error("expected %s, got %s", expected, repr(exception))
raise
if isinstance(expected, type) and issubclass(expected, Exception):
raise AssertionError("No exception raised; "
"expected %s for %s/%s" % (
expected.__name__,
repr(args),
repr(kwargs)))
for attr_name, attr_value in expected.items():
assert getattr(instance, attr_name) == attr_value
class TestCookie(object):
"""Tests for the Cookie class.
"""
# Test cases exercising different constructor calls to make a new Cookie
# from scratch. Each case is tuple:
# args, kwargs, exception or dict of expected attribute values
# this exercises the default validators as well.
creation_cases = [
# bad call gives TypeError
(("foo",), {}, TypeError),
(("a", "b", "c"), {}, TypeError),
# give un-ascii-able name - raises error due to likely
# compatibility problems (cookie ignored, etc.)
# in value it's fine, it'll be encoded and not inspected anyway.
(("ăŊĻ", "b"), {}, InvalidCookieError),
(("b", "ăŊĻ"), {}, {'name': 'b', 'value': "ăŊĻ"}),
# normal simple construction gives name and value
(("foo", "bar"), {}, {'name': 'foo', 'value': 'bar'}),
# add a valid attribute and get it set
(("baz", "bam"), {'max_age': 9},
{'name': 'baz', 'value': 'bam', 'max_age': 9}),
# multiple valid attributes
(("x", "y"), {'max_age': 9, 'comment': 'fruity'},
{'name': 'x', 'value': 'y',
'max_age': 9, 'comment': 'fruity'}),
# invalid max-age
(("w", "m"), {'max_age': 'loopy'}, InvalidCookieAttributeError),
(("w", "m"), {'max_age': -1}, InvalidCookieAttributeError),
(("w", "m"), {'max_age': 1.2}, InvalidCookieAttributeError),
# invalid expires
(("w", "m"), {'expires': 0}, InvalidCookieAttributeError),
(("w", "m"), {'expires':
datetime(2010, 1, 1, tzinfo=FixedOffsetTz(600))},
InvalidCookieAttributeError),
# control: valid expires
(("w", "m"),
{'expires': datetime(2010, 1, 1)},
{'expires': datetime(2010, 1, 1)}),
# invalid domain
(("w", "m"), {'domain': ''}, InvalidCookieAttributeError),
(("w", "m"), {'domain': '@'}, InvalidCookieAttributeError),
(("w", "m"), {'domain': '.foo.net'},
InvalidCookieAttributeError),
# control: valid domain
(("w", "m"),
{'domain': 'foo.net'},
{'domain': 'foo.net'},),
# invalid path
(("w", "m"), {'path': ''}, InvalidCookieAttributeError),
(("w", "m"), {'path': '""'}, InvalidCookieAttributeError),
(("w", "m"), {'path': 'foo'}, InvalidCookieAttributeError),
(("w", "m"), {'path': '"/foo"'}, InvalidCookieAttributeError),
(("w", "m"), {'path': ' /foo '}, InvalidCookieAttributeError),
# control: valid path
(("w", "m"), {'path': '/'},
{'path': '/'}),
(("w", "m"), {'path': '/axes'},
{'path': '/axes'}),
# invalid version per RFC 2109/RFC 2965
(("w", "m"), {'version': ''}, InvalidCookieAttributeError),
(("w", "m"), {'version': 'baa'}, InvalidCookieAttributeError),
(("w", "m"), {'version': -2}, InvalidCookieAttributeError),
(("w", "m"), {'version': 2.3}, InvalidCookieAttributeError),
# control: valid version
(("w", "m"), {'version': 0}, {'version': 0}),
(("w", "m"), {'version': 1}, {'version': 1}),
(("w", "m"), {'version': 3042}, {'version': 3042}),
# invalid secure, httponly
(("w", "m"), {'secure': ''}, InvalidCookieAttributeError),
(("w", "m"), {'secure': 0}, InvalidCookieAttributeError),
(("w", "m"), {'secure': 1}, InvalidCookieAttributeError),
(("w", "m"), {'secure': 'a'}, InvalidCookieAttributeError),
(("w", "m"), {'httponly': ''}, InvalidCookieAttributeError),
(("w", "m"), {'httponly': 0}, InvalidCookieAttributeError),
(("w", "m"), {'httponly': 1}, InvalidCookieAttributeError),
(("w", "m"), {'httponly': 'a'}, InvalidCookieAttributeError),
# valid comment
(("w", "m"), {'comment': 'a'}, {'comment': 'a'}),
# invalid names
# (unicode cases are done last because they mess with pytest print)
((None, "m"), {}, InvalidCookieError),
(("", "m"), {}, InvalidCookieError),
(("ü", "m"), {}, InvalidCookieError),
# invalid values
(("w", None), {}, {'name': 'w'}),
# a control - unicode is valid value, just gets encoded on way out
(("w", "üm"), {}, {'value': "üm"}),
# comma
(('a', ','), {}, {'value': ','}),
# semicolons
(('a', ';'), {}, {'value': ';'}),
# spaces
(('a', ' '), {}, {'value': ' '}),
]
def test_init(self):
"""Exercise __init__ and validators.
This is important both because it is a user-facing API, and also
because the parse/render tests depend heavily on it.
"""
creation_cases = self.creation_cases + [
(("a", "b"), {'frob': 10}, InvalidCookieAttributeError)
]
counter = 0
for args, kwargs, expected in creation_cases:
counter += 1
logging.error("counter %d, %s, %s, %s", counter, args, kwargs,
expected)
_test_init(Cookie, args, kwargs, expected)
def test_set_attributes(self):
"""Exercise setting, validation and getting of attributes without
much involving __init__. Also sets value and name.
"""
for args, kwargs, expected in self.creation_cases:
if not kwargs:
continue
try:
cookie = Cookie("yarp", "flam")
for attr, value in kwargs.items():
setattr(cookie, attr, value)
if args:
cookie.name = args[0]
cookie.value = args[1]
except Exception as e:
if type(e) == expected:
continue
raise
if isinstance(expected, type) and issubclass(expected, Exception):
raise AssertionError("No exception raised; "
"expected %s for %s" % (
expected.__name__,
repr(kwargs)))
for attr_name, attr_value in expected.items():
assert getattr(cookie, attr_name) == attr_value
def test_get_defaults(self):
"Test that defaults are right for cookie attrs"
cookie = Cookie("foo", "bar")
for attr in (
"expires",
"max_age",
"domain",
"path",
"comment",
"version",
"secure",
"httponly"):
assert hasattr(cookie, attr)
assert getattr(cookie, attr) == None
# Verify that not every name is getting something
for attr in ("foo", "bar", "baz"):
assert not hasattr(cookie, attr)
with raises(AttributeError):
getattr(cookie, attr)
names_values = [
("a", "b"),
("foo", "bar"),
("baz", "1234567890"),
("!!#po99!", "blah"),
("^_~`*", "foo"),
("%s+|-.&$", "snah"),
("lub", "!@#$%^&*()[]{}|/:'<>~.?`"),
("woah", "====+-_"),
]
def test_render_response(self):
"Test rendering Cookie object for Set-Cookie: header"
for name, value in self.names_values:
cookie = Cookie(name, value)
expected = "{name}={value}".format(
name=name, value=value)
assert cookie.render_response() == expected
for data, result in [