• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Simple test suite for Cookie.py
2
3from test.test_support import run_unittest, run_doctest, check_warnings
4import unittest
5import Cookie
6import pickle
7
8
9class CookieTests(unittest.TestCase):
10    # Currently this only tests SimpleCookie
11    def test_basic(self):
12        cases = [
13            { 'data': 'chips=ahoy; vienna=finger',
14              'dict': {'chips':'ahoy', 'vienna':'finger'},
15              'repr': "<SimpleCookie: chips='ahoy' vienna='finger'>",
16              'output': 'Set-Cookie: chips=ahoy\nSet-Cookie: vienna=finger',
17            },
18
19            { 'data': 'keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"',
20              'dict': {'keebler' : 'E=mc2; L="Loves"; fudge=\012;'},
21              'repr': '''<SimpleCookie: keebler='E=mc2; L="Loves"; fudge=\\n;'>''',
22              'output': 'Set-Cookie: keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"',
23            },
24
25            # Check illegal cookies that have an '=' char in an unquoted value
26            { 'data': 'keebler=E=mc2',
27              'dict': {'keebler' : 'E=mc2'},
28              'repr': "<SimpleCookie: keebler='E=mc2'>",
29              'output': 'Set-Cookie: keebler=E=mc2',
30            },
31
32            # issue22931 - Adding '[' and ']' as valid characters in cookie
33            # values as defined in RFC 6265
34            {
35                'data': 'a=b; c=[; d=r; f=h',
36                'dict': {'a':'b', 'c':'[', 'd':'r', 'f':'h'},
37                'repr': "<SimpleCookie: a='b' c='[' d='r' f='h'>",
38                'output': '\n'.join((
39                    'Set-Cookie: a=b',
40                    'Set-Cookie: c=[',
41                    'Set-Cookie: d=r',
42                    'Set-Cookie: f=h'
43                ))
44            }
45        ]
46
47        for case in cases:
48            C = Cookie.SimpleCookie()
49            C.load(case['data'])
50            self.assertEqual(repr(C), case['repr'])
51            self.assertEqual(C.output(sep='\n'), case['output'])
52            for k, v in sorted(case['dict'].iteritems()):
53                self.assertEqual(C[k].value, v)
54
55    def test_load(self):
56        C = Cookie.SimpleCookie()
57        C.load('Customer="WILE_E_COYOTE"; Version=1; Path=/acme')
58
59        self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
60        self.assertEqual(C['Customer']['version'], '1')
61        self.assertEqual(C['Customer']['path'], '/acme')
62
63        self.assertEqual(C.output(['path']),
64            'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme')
65        self.assertEqual(C.js_output(), r"""
66        <script type="text/javascript">
67        <!-- begin hiding
68        document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1";
69        // end hiding -->
70        </script>
71        """)
72        self.assertEqual(C.js_output(['path']), r"""
73        <script type="text/javascript">
74        <!-- begin hiding
75        document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme";
76        // end hiding -->
77        </script>
78        """)
79
80        # loading 'expires'
81        C = Cookie.SimpleCookie()
82        C.load('Customer="W"; expires=Wed, 01 Jan 2010 00:00:00 GMT')
83        self.assertEqual(C['Customer']['expires'],
84                         'Wed, 01 Jan 2010 00:00:00 GMT')
85        C = Cookie.SimpleCookie()
86        C.load('Customer="W"; expires=Wed, 01 Jan 98 00:00:00 GMT')
87        self.assertEqual(C['Customer']['expires'],
88                         'Wed, 01 Jan 98 00:00:00 GMT')
89
90    def test_extended_encode(self):
91        # Issue 9824: some browsers don't follow the standard; we now
92        # encode , and ; to keep them from tripping up.
93        C = Cookie.SimpleCookie()
94        C['val'] = "some,funky;stuff"
95        self.assertEqual(C.output(['val']),
96            'Set-Cookie: val="some\\054funky\\073stuff"')
97
98    def test_set_secure_httponly_attrs(self):
99        C = Cookie.SimpleCookie('Customer="WILE_E_COYOTE"')
100        C['Customer']['secure'] = True
101        C['Customer']['httponly'] = True
102        self.assertEqual(C.output(),
103            'Set-Cookie: Customer="WILE_E_COYOTE"; httponly; secure')
104
105    def test_secure_httponly_false_if_not_present(self):
106        C = Cookie.SimpleCookie()
107        C.load('eggs=scrambled; Path=/bacon')
108        self.assertFalse(C['eggs']['httponly'])
109        self.assertFalse(C['eggs']['secure'])
110
111    def test_secure_httponly_true_if_present(self):
112        # Issue 16611
113        C = Cookie.SimpleCookie()
114        C.load('eggs=scrambled; httponly; secure; Path=/bacon')
115        self.assertTrue(C['eggs']['httponly'])
116        self.assertTrue(C['eggs']['secure'])
117
118    def test_secure_httponly_true_if_have_value(self):
119        # This isn't really valid, but demonstrates what the current code
120        # is expected to do in this case.
121        C = Cookie.SimpleCookie()
122        C.load('eggs=scrambled; httponly=foo; secure=bar; Path=/bacon')
123        self.assertTrue(C['eggs']['httponly'])
124        self.assertTrue(C['eggs']['secure'])
125        # Here is what it actually does; don't depend on this behavior.  These
126        # checks are testing backward compatibility for issue 16611.
127        self.assertEqual(C['eggs']['httponly'], 'foo')
128        self.assertEqual(C['eggs']['secure'], 'bar')
129
130    def test_bad_attrs(self):
131        # Issue 16611: make sure we don't break backward compatibility.
132        C = Cookie.SimpleCookie()
133        C.load('cookie=with; invalid; version; second=cookie;')
134        self.assertEqual(C.output(),
135            'Set-Cookie: cookie=with\r\nSet-Cookie: second=cookie')
136
137    def test_extra_spaces(self):
138        C = Cookie.SimpleCookie()
139        C.load('eggs  =  scrambled  ;  secure  ;  path  =  bar   ; foo=foo   ')
140        self.assertEqual(C.output(),
141            'Set-Cookie: eggs=scrambled; Path=bar; secure\r\nSet-Cookie: foo=foo')
142
143    def test_quoted_meta(self):
144        # Try cookie with quoted meta-data
145        C = Cookie.SimpleCookie()
146        C.load('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
147        self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
148        self.assertEqual(C['Customer']['version'], '1')
149        self.assertEqual(C['Customer']['path'], '/acme')
150
151    def test_invalid_cookies(self):
152        # Accepting these could be a security issue
153        C = Cookie.SimpleCookie()
154        for s in (']foo=x', '[foo=x', 'blah]foo=x', 'blah[foo=x'):
155            C.load(s)
156            self.assertEqual(dict(C), {})
157            self.assertEqual(C.output(), '')
158
159    def test_pickle(self):
160        rawdata = 'Customer="WILE_E_COYOTE"; Path=/acme; Version=1'
161        expected_output = 'Set-Cookie: %s' % rawdata
162
163        C = Cookie.SimpleCookie()
164        C.load(rawdata)
165        self.assertEqual(C.output(), expected_output)
166
167        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
168            C1 = pickle.loads(pickle.dumps(C, protocol=proto))
169            self.assertEqual(C1.output(), expected_output)
170
171
172def test_main():
173    run_unittest(CookieTests)
174    if Cookie.__doc__ is not None:
175        with check_warnings(('.+Cookie class is insecure; do not use it',
176                             DeprecationWarning)):
177            run_doctest(Cookie)
178
179if __name__ == '__main__':
180    test_main()
181