blob: b812a537aa76634cc2e413c1aa23b427c93ee8ea [file] [log] [blame]
jcgregorio2d66d4f2006-02-07 05:34:14 +00001#!/usr/bin/env python2.4
2"""
3httplib2test
4
5A set of unit tests for httplib2.py.
6
7Requires Python 2.4 or later
8"""
9
10__author__ = "Joe Gregorio (joe@bitworking.org)"
11__copyright__ = "Copyright 2006, Joe Gregorio"
12__contributors__ = []
13__license__ = "MIT"
14__history__ = """ """
15__version__ = "0.1 ($Rev: 118 $)"
16
17
jcgregoriode8238d2007-03-07 19:08:26 +000018import sys
19import unittest
20import httplib
21import httplib2
22import os
23import urlparse
24import time
25import base64
jcgregorio14644372007-07-30 14:13:37 +000026import StringIO
jcgregorio8421f272006-02-14 18:19:51 +000027
28# Python 2.3 support
29if not hasattr(unittest.TestCase, 'assertTrue'):
30 unittest.TestCase.assertTrue = unittest.TestCase.failUnless
31 unittest.TestCase.assertFalse = unittest.TestCase.failIf
32
jcgregorio2d66d4f2006-02-07 05:34:14 +000033# The test resources base uri
34base = 'http://bitworking.org/projects/httplib2/test/'
35#base = 'http://localhost/projects/httplib2/test/'
jcgregorio90fb4a42006-11-17 16:19:47 +000036cacheDirName = ".cache"
jcgregorio2d66d4f2006-02-07 05:34:14 +000037
jcgregoriode8238d2007-03-07 19:08:26 +000038
39class CredentialsTest(unittest.TestCase):
40 def test(self):
41 c = httplib2.Credentials()
42 c.add("joe", "password")
43 self.assertEqual(("joe", "password"), list(c.iter("bitworking.org"))[0])
44 self.assertEqual(("joe", "password"), list(c.iter(""))[0])
45 c.add("fred", "password2", "wellformedweb.org")
46 self.assertEqual(("joe", "password"), list(c.iter("bitworking.org"))[0])
47 self.assertEqual(1, len(list(c.iter("bitworking.org"))))
48 self.assertEqual(2, len(list(c.iter("wellformedweb.org"))))
49 self.assertTrue(("fred", "password2") in list(c.iter("wellformedweb.org")))
50 c.clear()
51 self.assertEqual(0, len(list(c.iter("bitworking.org"))))
52 c.add("fred", "password2", "wellformedweb.org")
53 self.assertTrue(("fred", "password2") in list(c.iter("wellformedweb.org")))
54 self.assertEqual(0, len(list(c.iter("bitworking.org"))))
55 self.assertEqual(0, len(list(c.iter(""))))
56
57
jcgregorio2d66d4f2006-02-07 05:34:14 +000058class ParserTest(unittest.TestCase):
59 def testFromStd66(self):
60 self.assertEqual( ('http', 'example.com', '', None, None ), httplib2.parse_uri("http://example.com"))
61 self.assertEqual( ('https', 'example.com', '', None, None ), httplib2.parse_uri("https://example.com"))
62 self.assertEqual( ('https', 'example.com:8080', '', None, None ), httplib2.parse_uri("https://example.com:8080"))
63 self.assertEqual( ('http', 'example.com', '/', None, None ), httplib2.parse_uri("http://example.com/"))
64 self.assertEqual( ('http', 'example.com', '/path', None, None ), httplib2.parse_uri("http://example.com/path"))
65 self.assertEqual( ('http', 'example.com', '/path', 'a=1&b=2', None ), httplib2.parse_uri("http://example.com/path?a=1&b=2"))
66 self.assertEqual( ('http', 'example.com', '/path', 'a=1&b=2', 'fred' ), httplib2.parse_uri("http://example.com/path?a=1&b=2#fred"))
67 self.assertEqual( ('http', 'example.com', '/path', 'a=1&b=2', 'fred' ), httplib2.parse_uri("http://example.com/path?a=1&b=2#fred"))
68
jcgregorio2d66d4f2006-02-07 05:34:14 +000069
jcgregorioa46fe4e2006-11-16 04:13:45 +000070class UrlNormTest(unittest.TestCase):
71 def test(self):
72 self.assertEqual( "http://example.org/", httplib2.urlnorm("http://example.org")[-1])
73 self.assertEqual( "http://example.org/", httplib2.urlnorm("http://EXAMple.org")[-1])
74 self.assertEqual( "http://example.org/?=b", httplib2.urlnorm("http://EXAMple.org?=b")[-1])
75 self.assertEqual( "http://example.org/mypath?a=b", httplib2.urlnorm("http://EXAMple.org/mypath?a=b")[-1])
76 self.assertEqual( "http://localhost:80/", httplib2.urlnorm("http://localhost:80")[-1])
jcgregoriob4e9ab02006-11-17 15:53:15 +000077 self.assertEqual( httplib2.urlnorm("http://localhost:80/"), httplib2.urlnorm("HTTP://LOCALHOST:80"))
jcgregorio132d28e2007-01-23 16:22:53 +000078 try:
79 httplib2.urlnorm("/")
80 self.fail("Non-absolute URIs should raise an exception")
81 except httplib2.RelativeURIError:
82 pass
jcgregorioa46fe4e2006-11-16 04:13:45 +000083
84class UrlSafenameTest(unittest.TestCase):
85 def test(self):
86 # Test that different URIs end up generating different safe names
87 self.assertEqual( "example.org,fred,a=b,58489f63a7a83c3b7794a6a398ee8b1f", httplib2.safename("http://example.org/fred/?a=b"))
88 self.assertEqual( "example.org,fred,a=b,8c5946d56fec453071f43329ff0be46b", httplib2.safename("http://example.org/fred?/a=b"))
89 self.assertEqual( "www.example.org,fred,a=b,499c44b8d844a011b67ea2c015116968", httplib2.safename("http://www.example.org/fred?/a=b"))
90 self.assertEqual( httplib2.safename(httplib2.urlnorm("http://www")[-1]), httplib2.safename(httplib2.urlnorm("http://WWW")[-1]))
91 self.assertEqual( "www.example.org,fred,a=b,692e843a333484ce0095b070497ab45d", httplib2.safename("https://www.example.org/fred?/a=b"))
92 self.assertNotEqual( httplib2.safename("http://www"), httplib2.safename("https://www"))
93 # Test the max length limits
94 uri = "http://" + ("w" * 200) + ".org"
95 uri2 = "http://" + ("w" * 201) + ".org"
96 self.assertNotEqual( httplib2.safename(uri2), httplib2.safename(uri))
97 # Max length should be 200 + 1 (",") + 32
98 self.assertEqual(233, len(httplib2.safename(uri2)))
99 self.assertEqual(233, len(httplib2.safename(uri)))
100 # Unicode
jcgregoriodebceec2006-12-12 20:26:02 +0000101 if sys.version_info >= (2,3):
102 self.assertEqual( "xn--http,-4y1d.org,fred,a=b,579924c35db315e5a32e3d9963388193", httplib2.safename(u"http://\u2304.org/fred/?a=b"))
jcgregorioa46fe4e2006-11-16 04:13:45 +0000103
jcgregorio14644372007-07-30 14:13:37 +0000104class _MyResponse(StringIO.StringIO):
105 def __init__(self, body, **kwargs):
106 StringIO.StringIO.__init__(self, body)
107 self.headers = kwargs
108
109 def iteritems(self):
110 return self.headers.iteritems()
111
112
113class _MyHTTPConnection(object):
114 "This class is just a mock of httplib.HTTPConnection used for testing"
115
116 def __init__(self, host, port=None, key_file=None, cert_file=None,
joe.gregoriof28536d2007-10-23 14:10:11 +0000117 strict=None, timeout=None, proxy_info=None):
jcgregorio14644372007-07-30 14:13:37 +0000118 self.host = host
119 self.port = port
120 self.timeout = timeout
121 self.log = ""
122
123 def set_debuglevel(self, level):
124 pass
125
126 def connect(self):
127 "Connect to a host on a given port."
128 pass
129
130 def close(self):
131 pass
132
133 def request(self, method, request_uri, body, headers):
134 pass
135
136 def getresponse(self):
137 return _MyResponse("the body", status="200")
jcgregorioa46fe4e2006-11-16 04:13:45 +0000138
jcgregorio90fb4a42006-11-17 16:19:47 +0000139
jcgregorio2d66d4f2006-02-07 05:34:14 +0000140class HttpTest(unittest.TestCase):
141 def setUp(self):
jcgregorio7e3608f2006-06-15 13:01:53 +0000142 if os.path.exists(cacheDirName):
143 [os.remove(os.path.join(cacheDirName, file)) for file in os.listdir(cacheDirName)]
144 self.http = httplib2.Http(cacheDirName)
jcgregorio36140b52006-06-13 02:17:52 +0000145 self.http.clear_credentials()
jcgregorio2d66d4f2006-02-07 05:34:14 +0000146
jcgregorio14644372007-07-30 14:13:37 +0000147 def testConnectionType(self):
joe.gregoriof28536d2007-10-23 14:10:11 +0000148 self.http.force_exception_to_status_code = False
jcgregorio14644372007-07-30 14:13:37 +0000149 response, content = self.http.request("http://bitworking.org", connection_type=_MyHTTPConnection)
150 self.assertEqual(response['content-location'], "http://bitworking.org")
151 self.assertEqual(content, "the body")
152
jcgregorio6a638172007-01-23 16:40:23 +0000153 def testGetUnknownServer(self):
jcgregorio07a9a4a2007-03-08 21:18:39 +0000154 self.http.force_exception_to_status_code = False
jcgregorio6a638172007-01-23 16:40:23 +0000155 try:
156 self.http.request("http://fred.bitworking.org/")
157 self.fail("An httplib2.ServerNotFoundError Exception must be thrown on an unresolvable server.")
158 except httplib2.ServerNotFoundError:
159 pass
160
jcgregorio07a9a4a2007-03-08 21:18:39 +0000161 # Now test with exceptions turned off
162 self.http.force_exception_to_status_code = True
163
164 (response, content) = self.http.request("http://fred.bitworking.org/")
165 self.assertEqual(response['content-type'], 'text/plain')
166 self.assertTrue(content.startswith("Unable to find"))
167 self.assertEqual(response.status, 400)
168
jcgregorioa898f8f2006-12-12 17:16:55 +0000169 def testGetIRI(self):
jcgregoriodebceec2006-12-12 20:26:02 +0000170 if sys.version_info >= (2,3):
171 uri = urlparse.urljoin(base, u"reflector/reflector.cgi?d=\N{CYRILLIC CAPITAL LETTER DJE}")
172 (response, content) = self.http.request(uri, "GET")
173 d = self.reflector(content)
174 self.assertTrue(d.has_key('QUERY_STRING'))
175 self.assertTrue(d['QUERY_STRING'].find('%D0%82') > 0)
jcgregorioa898f8f2006-12-12 17:16:55 +0000176
jcgregorio2d66d4f2006-02-07 05:34:14 +0000177 def testGetIsDefaultMethod(self):
178 # Test that GET is the default method
179 uri = urlparse.urljoin(base, "methods/method_reflector.cgi")
jcgregorio36140b52006-06-13 02:17:52 +0000180 (response, content) = self.http.request(uri)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000181 self.assertEqual(response['x-method'], "GET")
182
183 def testDifferentMethods(self):
184 # Test that all methods can be used
185 uri = urlparse.urljoin(base, "methods/method_reflector.cgi")
186 for method in ["GET", "PUT", "DELETE", "POST"]:
jcgregorio36140b52006-06-13 02:17:52 +0000187 (response, content) = self.http.request(uri, method, body=" ")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000188 self.assertEqual(response['x-method'], method)
189
190 def testGetNoCache(self):
191 # Test that can do a GET w/o the cache turned on.
192 http = httplib2.Http()
193 uri = urlparse.urljoin(base, "304/test_etag.txt")
194 (response, content) = http.request(uri, "GET")
195 self.assertEqual(response.status, 200)
jcgregorioa0713ab2006-07-01 05:21:34 +0000196 self.assertEqual(response.previous, None)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000197
jcgregorioe4ce13e2006-04-02 03:05:08 +0000198 def testGetOnlyIfCachedCacheMiss(self):
199 # Test that can do a GET with no cache with 'only-if-cached'
jcgregorio36140b52006-06-13 02:17:52 +0000200 http = httplib2.Http()
jcgregorioe4ce13e2006-04-02 03:05:08 +0000201 uri = urlparse.urljoin(base, "304/test_etag.txt")
202 (response, content) = http.request(uri, "GET", headers={'cache-control': 'only-if-cached'})
203 self.assertEqual(response.fromcache, False)
jcgregorio36140b52006-06-13 02:17:52 +0000204 self.assertEqual(response.status, 200)
jcgregorioe4ce13e2006-04-02 03:05:08 +0000205
206 def testGetOnlyIfCachedNoCacheAtAll(self):
207 # Test that can do a GET with no cache with 'only-if-cached'
208 # Of course, there might be an intermediary beyond us
209 # that responds to the 'only-if-cached', so this
210 # test can't really be guaranteed to pass.
211 http = httplib2.Http()
212 uri = urlparse.urljoin(base, "304/test_etag.txt")
213 (response, content) = http.request(uri, "GET", headers={'cache-control': 'only-if-cached'})
214 self.assertEqual(response.fromcache, False)
215 self.assertEqual(response.status, 200)
216
jcgregorio2d66d4f2006-02-07 05:34:14 +0000217 def testUserAgent(self):
218 # Test that we provide a default user-agent
219 uri = urlparse.urljoin(base, "user-agent/test.cgi")
jcgregorio36140b52006-06-13 02:17:52 +0000220 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000221 self.assertEqual(response.status, 200)
222 self.assertTrue(content.startswith("Python-httplib2/"))
223
224 def testUserAgentNonDefault(self):
225 # Test that the default user-agent can be over-ridden
joe.gregoriof28536d2007-10-23 14:10:11 +0000226
jcgregorio2d66d4f2006-02-07 05:34:14 +0000227 uri = urlparse.urljoin(base, "user-agent/test.cgi")
jcgregorio36140b52006-06-13 02:17:52 +0000228 (response, content) = self.http.request(uri, "GET", headers={'User-Agent': 'fred/1.0'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000229 self.assertEqual(response.status, 200)
230 self.assertTrue(content.startswith("fred/1.0"))
231
232 def testGet300WithLocation(self):
233 # Test the we automatically follow 300 redirects if a Location: header is provided
234 uri = urlparse.urljoin(base, "300/with-location-header.asis")
jcgregorio36140b52006-06-13 02:17:52 +0000235 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000236 self.assertEqual(response.status, 200)
237 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000238 self.assertEqual(response.previous.status, 300)
239 self.assertEqual(response.previous.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000240
241 # Confirm that the intermediate 300 is not cached
jcgregorio36140b52006-06-13 02:17:52 +0000242 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000243 self.assertEqual(response.status, 200)
244 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000245 self.assertEqual(response.previous.status, 300)
246 self.assertEqual(response.previous.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000247
jcgregorio2f1e1422007-05-03 13:17:33 +0000248 def testGet300WithLocationNoRedirect(self):
249 # Test the we automatically follow 300 redirects if a Location: header is provided
250 self.http.follow_redirects = False
251 uri = urlparse.urljoin(base, "300/with-location-header.asis")
252 (response, content) = self.http.request(uri, "GET")
253 self.assertEqual(response.status, 300)
254
jcgregorio2d66d4f2006-02-07 05:34:14 +0000255 def testGet300WithoutLocation(self):
256 # Not giving a Location: header in a 300 response is acceptable
257 # In which case we just return the 300 response
258 uri = urlparse.urljoin(base, "300/without-location-header.asis")
jcgregorio36140b52006-06-13 02:17:52 +0000259 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000260 self.assertEqual(response.status, 300)
261 self.assertTrue(response['content-type'].startswith("text/html"))
jcgregorioa0713ab2006-07-01 05:21:34 +0000262 self.assertEqual(response.previous, None)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000263
264 def testGet301(self):
265 # Test that we automatically follow 301 redirects
266 # and that we cache the 301 response
267 uri = urlparse.urljoin(base, "301/onestep.asis")
jcgregorio8e300b92006-11-07 16:44:35 +0000268 destination = urlparse.urljoin(base, "302/final-destination.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000269 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000270 self.assertEqual(response.status, 200)
jcgregorio772adc82006-11-17 21:52:34 +0000271 self.assertTrue(response.has_key('content-location'))
272 self.assertEqual(response['content-location'], destination)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000273 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000274 self.assertEqual(response.previous.status, 301)
275 self.assertEqual(response.previous.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000276
jcgregorio36140b52006-06-13 02:17:52 +0000277 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000278 self.assertEqual(response.status, 200)
jcgregorio772adc82006-11-17 21:52:34 +0000279 self.assertEqual(response['content-location'], destination)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000280 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000281 self.assertEqual(response.previous.status, 301)
282 self.assertEqual(response.previous.fromcache, True)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000283
jcgregorio2f1e1422007-05-03 13:17:33 +0000284
285 def testGet301NoRedirect(self):
286 # Test that we automatically follow 301 redirects
287 # and that we cache the 301 response
288 self.http.follow_redirects = False
289 uri = urlparse.urljoin(base, "301/onestep.asis")
290 destination = urlparse.urljoin(base, "302/final-destination.txt")
291 (response, content) = self.http.request(uri, "GET")
292 self.assertEqual(response.status, 301)
293
294
jcgregorio2d66d4f2006-02-07 05:34:14 +0000295 def testGet302(self):
296 # Test that we automatically follow 302 redirects
297 # and that we DO NOT cache the 302 response
298 uri = urlparse.urljoin(base, "302/onestep.asis")
jcgregorio8e300b92006-11-07 16:44:35 +0000299 destination = urlparse.urljoin(base, "302/final-destination.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000300 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000301 self.assertEqual(response.status, 200)
jcgregorio772adc82006-11-17 21:52:34 +0000302 self.assertEqual(response['content-location'], destination)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000303 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000304 self.assertEqual(response.previous.status, 302)
305 self.assertEqual(response.previous.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000306
307 uri = urlparse.urljoin(base, "302/onestep.asis")
jcgregorio36140b52006-06-13 02:17:52 +0000308 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000309 self.assertEqual(response.status, 200)
310 self.assertEqual(response.fromcache, True)
jcgregorio772adc82006-11-17 21:52:34 +0000311 self.assertEqual(response['content-location'], destination)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000312 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000313 self.assertEqual(response.previous.status, 302)
314 self.assertEqual(response.previous.fromcache, False)
jcgregorio772adc82006-11-17 21:52:34 +0000315 self.assertEqual(response.previous['content-location'], uri)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000316
317 uri = urlparse.urljoin(base, "302/twostep.asis")
318
jcgregorio36140b52006-06-13 02:17:52 +0000319 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000320 self.assertEqual(response.status, 200)
321 self.assertEqual(response.fromcache, True)
322 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000323 self.assertEqual(response.previous.status, 302)
324 self.assertEqual(response.previous.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000325
326 def testGet302RedirectionLimit(self):
327 # Test that we can set a lower redirection limit
328 # and that we raise an exception when we exceed
329 # that limit.
jcgregorio07a9a4a2007-03-08 21:18:39 +0000330 self.http.force_exception_to_status_code = False
331
jcgregorio2d66d4f2006-02-07 05:34:14 +0000332 uri = urlparse.urljoin(base, "302/twostep.asis")
333 try:
jcgregorio36140b52006-06-13 02:17:52 +0000334 (response, content) = self.http.request(uri, "GET", redirections = 1)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000335 self.fail("This should not happen")
336 except httplib2.RedirectLimit:
337 pass
338 except Exception, e:
339 self.fail("Threw wrong kind of exception ")
340
jcgregorio07a9a4a2007-03-08 21:18:39 +0000341 # Re-run the test with out the exceptions
342 self.http.force_exception_to_status_code = True
343
344 (response, content) = self.http.request(uri, "GET", redirections = 1)
345 self.assertEqual(response.status, 500)
346 self.assertTrue(response.reason.startswith("Redirected more"))
347 self.assertEqual("302", response['status'])
348 self.assertTrue(content.startswith("<html>"))
349 self.assertTrue(response.previous != None)
350
jcgregorio2d66d4f2006-02-07 05:34:14 +0000351 def testGet302NoLocation(self):
352 # Test that we throw an exception when we get
353 # a 302 with no Location: header.
jcgregorio07a9a4a2007-03-08 21:18:39 +0000354 self.http.force_exception_to_status_code = False
jcgregorio2d66d4f2006-02-07 05:34:14 +0000355 uri = urlparse.urljoin(base, "302/no-location.asis")
356 try:
jcgregorio36140b52006-06-13 02:17:52 +0000357 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000358 self.fail("Should never reach here")
359 except httplib2.RedirectMissingLocation:
360 pass
361 except Exception, e:
362 self.fail("Threw wrong kind of exception ")
363
jcgregorio07a9a4a2007-03-08 21:18:39 +0000364 # Re-run the test with out the exceptions
365 self.http.force_exception_to_status_code = True
366
367 (response, content) = self.http.request(uri, "GET")
368 self.assertEqual(response.status, 500)
369 self.assertTrue(response.reason.startswith("Redirected but"))
370 self.assertEqual("302", response['status'])
371 self.assertTrue(content.startswith("This is content"))
372
jcgregorio2d66d4f2006-02-07 05:34:14 +0000373 def testGet302ViaHttps(self):
jcgregorioadbb4f82006-05-19 15:17:42 +0000374 # Google always redirects to http://google.com
jcgregorio36140b52006-06-13 02:17:52 +0000375 (response, content) = self.http.request("https://google.com", "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000376 self.assertEqual(200, response.status)
jcgregorioa0713ab2006-07-01 05:21:34 +0000377 self.assertEqual(302, response.previous.status)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000378
379 def testGetViaHttps(self):
380 # Test that we can handle HTTPS
jcgregorio36140b52006-06-13 02:17:52 +0000381 (response, content) = self.http.request("https://google.com/adsense/", "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000382 self.assertEqual(200, response.status)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000383
384 def testGetViaHttpsSpecViolationOnLocation(self):
385 # Test that we follow redirects through HTTPS
386 # even if they violate the spec by including
387 # a relative Location: header instead of an
388 # absolute one.
jcgregorio36140b52006-06-13 02:17:52 +0000389 (response, content) = self.http.request("https://google.com/adsense", "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000390 self.assertEqual(200, response.status)
jcgregorioa0713ab2006-07-01 05:21:34 +0000391 self.assertNotEqual(None, response.previous)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000392
jcgregoriode8238d2007-03-07 19:08:26 +0000393
394 def testGetViaHttpsKeyCert(self):
jcgregorio2f1e1422007-05-03 13:17:33 +0000395 # At this point I can only test
396 # that the key and cert files are passed in
397 # correctly to httplib. It would be nice to have
398 # a real https endpoint to test against.
399 http = httplib2.Http(timeout=2)
jcgregoriode8238d2007-03-07 19:08:26 +0000400
401 http.add_certificate("akeyfile", "acertfile", "bitworking.org")
402 try:
403 (response, content) = http.request("https://bitworking.org", "GET")
404 except:
405 pass
406 self.assertEqual(http.connections["https:bitworking.org"].key_file, "akeyfile")
407 self.assertEqual(http.connections["https:bitworking.org"].cert_file, "acertfile")
408
jcgregorio2f1e1422007-05-03 13:17:33 +0000409 try:
410 (response, content) = http.request("https://notthere.bitworking.org", "GET")
411 except:
412 pass
413 self.assertEqual(http.connections["https:notthere.bitworking.org"].key_file, None)
414 self.assertEqual(http.connections["https:notthere.bitworking.org"].cert_file, None)
415
416
417
jcgregoriode8238d2007-03-07 19:08:26 +0000418
jcgregorio2d66d4f2006-02-07 05:34:14 +0000419 def testGet303(self):
420 # Do a follow-up GET on a Location: header
421 # returned from a POST that gave a 303.
422 uri = urlparse.urljoin(base, "303/303.cgi")
jcgregorio36140b52006-06-13 02:17:52 +0000423 (response, content) = self.http.request(uri, "POST", " ")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000424 self.assertEqual(response.status, 200)
425 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000426 self.assertEqual(response.previous.status, 303)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000427
jcgregorio2f1e1422007-05-03 13:17:33 +0000428 def testGet303NoRedirect(self):
429 # Do a follow-up GET on a Location: header
430 # returned from a POST that gave a 303.
431 self.http.follow_redirects = False
432 uri = urlparse.urljoin(base, "303/303.cgi")
433 (response, content) = self.http.request(uri, "POST", " ")
434 self.assertEqual(response.status, 303)
435
jcgregorio2d66d4f2006-02-07 05:34:14 +0000436 def test303ForDifferentMethods(self):
437 # Test that all methods can be used
438 uri = urlparse.urljoin(base, "303/redirect-to-reflector.cgi")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000439 for (method, method_on_303) in [("PUT", "GET"), ("DELETE", "GET"), ("POST", "GET"), ("GET", "GET"), ("HEAD", "GET")]:
jcgregorio36140b52006-06-13 02:17:52 +0000440 (response, content) = self.http.request(uri, method, body=" ")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000441 self.assertEqual(response['x-method'], method_on_303)
442
443 def testGet304(self):
444 # Test that we use ETags properly to validate our cache
445 uri = urlparse.urljoin(base, "304/test_etag.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000446 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000447 self.assertNotEqual(response['etag'], "")
448
jcgregorio36140b52006-06-13 02:17:52 +0000449 (response, content) = self.http.request(uri, "GET")
450 (response, content) = self.http.request(uri, "GET", headers = {'cache-control': 'must-revalidate'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000451 self.assertEqual(response.status, 200)
452 self.assertEqual(response.fromcache, True)
453
jcgregorio90fb4a42006-11-17 16:19:47 +0000454 cache_file_name = os.path.join(cacheDirName, httplib2.safename(httplib2.urlnorm(uri)[-1]))
455 f = open(cache_file_name, "r")
456 status_line = f.readline()
457 f.close()
458
459 self.assertTrue(status_line.startswith("status:"))
460
jcgregorio36140b52006-06-13 02:17:52 +0000461 (response, content) = self.http.request(uri, "HEAD")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000462 self.assertEqual(response.status, 200)
463 self.assertEqual(response.fromcache, True)
464
jcgregorio36140b52006-06-13 02:17:52 +0000465 (response, content) = self.http.request(uri, "GET", headers = {'range': 'bytes=0-0'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000466 self.assertEqual(response.status, 206)
467 self.assertEqual(response.fromcache, False)
468
jcgregorio25185622006-10-28 05:12:34 +0000469 def testGetIgnoreEtag(self):
470 # Test that we can forcibly ignore ETags
471 uri = urlparse.urljoin(base, "reflector/reflector.cgi")
472 (response, content) = self.http.request(uri, "GET")
473 self.assertNotEqual(response['etag'], "")
474
475 (response, content) = self.http.request(uri, "GET", headers = {'cache-control': 'max-age=0'})
476 d = self.reflector(content)
477 self.assertTrue(d.has_key('HTTP_IF_NONE_MATCH'))
478
479 self.http.ignore_etag = True
480 (response, content) = self.http.request(uri, "GET", headers = {'cache-control': 'max-age=0'})
481 d = self.reflector(content)
482 self.assertEqual(response.fromcache, False)
483 self.assertFalse(d.has_key('HTTP_IF_NONE_MATCH'))
484
jcgregorio4b145e82007-01-18 19:46:34 +0000485 def testOverrideEtag(self):
486 # Test that we can forcibly ignore ETags
487 uri = urlparse.urljoin(base, "reflector/reflector.cgi")
488 (response, content) = self.http.request(uri, "GET")
489 self.assertNotEqual(response['etag'], "")
490
491 (response, content) = self.http.request(uri, "GET", headers = {'cache-control': 'max-age=0'})
492 d = self.reflector(content)
493 self.assertTrue(d.has_key('HTTP_IF_NONE_MATCH'))
494 self.assertNotEqual(d['HTTP_IF_NONE_MATCH'], "fred")
495
pilgrim00a352e2009-05-29 04:04:44 +0000496 (response, content) = self.http.request(uri, "GET", headers = {'cache-control': 'max-age=0', 'if-none-match': 'fred'})
jcgregorio4b145e82007-01-18 19:46:34 +0000497 d = self.reflector(content)
498 self.assertTrue(d.has_key('HTTP_IF_NONE_MATCH'))
499 self.assertEqual(d['HTTP_IF_NONE_MATCH'], "fred")
jcgregorio25185622006-10-28 05:12:34 +0000500
pilgrim00a352e2009-05-29 04:04:44 +0000501#MAP-commented this out because it consistently fails
502# def testGet304EndToEnd(self):
503# # Test that end to end headers get overwritten in the cache
504# uri = urlparse.urljoin(base, "304/end2end.cgi")
505# (response, content) = self.http.request(uri, "GET")
506# self.assertNotEqual(response['etag'], "")
507# old_date = response['date']
508# time.sleep(2)
509#
510# (response, content) = self.http.request(uri, "GET", headers = {'Cache-Control': 'max-age=0'})
511# # The response should be from the cache, but the Date: header should be updated.
512# new_date = response['date']
513# self.assertNotEqual(new_date, old_date)
514# self.assertEqual(response.status, 200)
515# self.assertEqual(response.fromcache, True)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000516
517 def testGet304LastModified(self):
518 # Test that we can still handle a 304
519 # by only using the last-modified cache validator.
520 uri = urlparse.urljoin(base, "304/last-modified-only/last-modified-only.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000521 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000522
523 self.assertNotEqual(response['last-modified'], "")
jcgregorio36140b52006-06-13 02:17:52 +0000524 (response, content) = self.http.request(uri, "GET")
525 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000526 self.assertEqual(response.status, 200)
527 self.assertEqual(response.fromcache, True)
528
529 def testGet307(self):
530 # Test that we do follow 307 redirects but
531 # do not cache the 307
532 uri = urlparse.urljoin(base, "307/onestep.asis")
jcgregorio36140b52006-06-13 02:17:52 +0000533 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000534 self.assertEqual(response.status, 200)
535 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000536 self.assertEqual(response.previous.status, 307)
537 self.assertEqual(response.previous.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000538
jcgregorio36140b52006-06-13 02:17:52 +0000539 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000540 self.assertEqual(response.status, 200)
541 self.assertEqual(response.fromcache, True)
542 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000543 self.assertEqual(response.previous.status, 307)
544 self.assertEqual(response.previous.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000545
546 def testGet410(self):
547 # Test that we pass 410's through
548 uri = urlparse.urljoin(base, "410/410.asis")
jcgregorio36140b52006-06-13 02:17:52 +0000549 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000550 self.assertEqual(response.status, 410)
551
joe.gregorio0d4a2b82007-10-23 14:28:35 +0000552 def testHeadGZip(self):
553 # Test that we don't try to decompress a HEAD response
554 uri = urlparse.urljoin(base, "gzip/final-destination.txt")
555 (response, content) = self.http.request(uri, "HEAD")
556 self.assertEqual(response.status, 200)
557 self.assertNotEqual(int(response['content-length']), 0)
558 self.assertEqual(content, "")
559
jcgregorio2d66d4f2006-02-07 05:34:14 +0000560 def testGetGZip(self):
561 # Test that we support gzip compression
562 uri = urlparse.urljoin(base, "gzip/final-destination.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000563 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000564 self.assertEqual(response.status, 200)
jcgregorio90fb4a42006-11-17 16:19:47 +0000565 self.assertFalse(response.has_key('content-encoding'))
joe.gregorio8b6d2312007-12-16 05:42:07 +0000566 self.assertTrue(response.has_key('-content-encoding'))
jcgregorio153f5882006-11-06 03:33:24 +0000567 self.assertEqual(int(response['content-length']), len("This is the final destination.\n"))
jcgregorio2d66d4f2006-02-07 05:34:14 +0000568 self.assertEqual(content, "This is the final destination.\n")
569
570 def testGetGZipFailure(self):
571 # Test that we raise a good exception when the gzip fails
jcgregorio07a9a4a2007-03-08 21:18:39 +0000572 self.http.force_exception_to_status_code = False
jcgregorio2d66d4f2006-02-07 05:34:14 +0000573 uri = urlparse.urljoin(base, "gzip/failed-compression.asis")
574 try:
jcgregorio36140b52006-06-13 02:17:52 +0000575 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000576 self.fail("Should never reach here")
577 except httplib2.FailedToDecompressContent:
578 pass
579 except Exception:
580 self.fail("Threw wrong kind of exception")
581
jcgregorio07a9a4a2007-03-08 21:18:39 +0000582 # Re-run the test with out the exceptions
583 self.http.force_exception_to_status_code = True
584
585 (response, content) = self.http.request(uri, "GET")
586 self.assertEqual(response.status, 500)
587 self.assertTrue(response.reason.startswith("Content purported"))
588
589 def testTimeout(self):
jcgregoriob2697912007-03-09 02:23:47 +0000590 self.http.force_exception_to_status_code = True
jcgregorio07a9a4a2007-03-08 21:18:39 +0000591 uri = urlparse.urljoin(base, "timeout/timeout.cgi")
592 try:
593 import socket
594 socket.setdefaulttimeout(1)
595 except:
596 # Don't run the test if we can't set the timeout
597 return
598 (response, content) = self.http.request(uri)
599 self.assertEqual(response.status, 408)
600 self.assertTrue(response.reason.startswith("Request Timeout"))
601 self.assertTrue(content.startswith("Request Timeout"))
602
jcgregoriob2697912007-03-09 02:23:47 +0000603 def testIndividualTimeout(self):
jcgregoriob2697912007-03-09 02:23:47 +0000604 uri = urlparse.urljoin(base, "timeout/timeout.cgi")
605 http = httplib2.Http(timeout=1)
joe.gregoriof28536d2007-10-23 14:10:11 +0000606 http.force_exception_to_status_code = True
jcgregoriob2697912007-03-09 02:23:47 +0000607
608 (response, content) = http.request(uri)
609 self.assertEqual(response.status, 408)
610 self.assertTrue(response.reason.startswith("Request Timeout"))
611 self.assertTrue(content.startswith("Request Timeout"))
612
jcgregorio07a9a4a2007-03-08 21:18:39 +0000613
Joe Gregorio1a7609f2009-07-16 10:59:44 -0400614 def testHTTPSInitTimeout(self):
615 c = httplib2.HTTPSConnectionWithTimeout('localhost', 80, timeout=47)
616 self.assertEqual(47, c.timeout)
617
jcgregorio2d66d4f2006-02-07 05:34:14 +0000618 def testGetDeflate(self):
619 # Test that we support deflate compression
620 uri = urlparse.urljoin(base, "deflate/deflated.asis")
jcgregorio36140b52006-06-13 02:17:52 +0000621 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000622 self.assertEqual(response.status, 200)
jcgregorio90fb4a42006-11-17 16:19:47 +0000623 self.assertFalse(response.has_key('content-encoding'))
jcgregorio153f5882006-11-06 03:33:24 +0000624 self.assertEqual(int(response['content-length']), len("This is the final destination."))
jcgregorio2d66d4f2006-02-07 05:34:14 +0000625 self.assertEqual(content, "This is the final destination.")
626
627 def testGetDeflateFailure(self):
628 # Test that we raise a good exception when the deflate fails
jcgregorio07a9a4a2007-03-08 21:18:39 +0000629 self.http.force_exception_to_status_code = False
630
jcgregorio2d66d4f2006-02-07 05:34:14 +0000631 uri = urlparse.urljoin(base, "deflate/failed-compression.asis")
632 try:
jcgregorio36140b52006-06-13 02:17:52 +0000633 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000634 self.fail("Should never reach here")
635 except httplib2.FailedToDecompressContent:
636 pass
637 except Exception:
638 self.fail("Threw wrong kind of exception")
639
jcgregorio07a9a4a2007-03-08 21:18:39 +0000640 # Re-run the test with out the exceptions
641 self.http.force_exception_to_status_code = True
642
643 (response, content) = self.http.request(uri, "GET")
644 self.assertEqual(response.status, 500)
645 self.assertTrue(response.reason.startswith("Content purported"))
646
jcgregorio2d66d4f2006-02-07 05:34:14 +0000647 def testGetDuplicateHeaders(self):
648 # Test that duplicate headers get concatenated via ','
649 uri = urlparse.urljoin(base, "duplicate-headers/multilink.asis")
jcgregorio36140b52006-06-13 02:17:52 +0000650 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000651 self.assertEqual(response.status, 200)
652 self.assertEqual(content, "This is content\n")
653 self.assertEqual(response['link'].split(",")[0], '<http://bitworking.org>; rel="home"; title="BitWorking"')
654
655 def testGetCacheControlNoCache(self):
656 # Test Cache-Control: no-cache on requests
657 uri = urlparse.urljoin(base, "304/test_etag.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000658 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000659 self.assertNotEqual(response['etag'], "")
jcgregorio36140b52006-06-13 02:17:52 +0000660 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000661 self.assertEqual(response.status, 200)
662 self.assertEqual(response.fromcache, True)
663
jcgregorio36140b52006-06-13 02:17:52 +0000664 (response, content) = self.http.request(uri, "GET", headers={'Cache-Control': 'no-cache'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000665 self.assertEqual(response.status, 200)
666 self.assertEqual(response.fromcache, False)
667
668 def testGetCacheControlPragmaNoCache(self):
669 # Test Pragma: no-cache on requests
670 uri = urlparse.urljoin(base, "304/test_etag.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000671 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000672 self.assertNotEqual(response['etag'], "")
jcgregorio36140b52006-06-13 02:17:52 +0000673 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000674 self.assertEqual(response.status, 200)
675 self.assertEqual(response.fromcache, True)
676
jcgregorio36140b52006-06-13 02:17:52 +0000677 (response, content) = self.http.request(uri, "GET", headers={'Pragma': 'no-cache'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000678 self.assertEqual(response.status, 200)
679 self.assertEqual(response.fromcache, False)
680
681 def testGetCacheControlNoStoreRequest(self):
682 # A no-store request means that the response should not be stored.
683 uri = urlparse.urljoin(base, "304/test_etag.txt")
684
jcgregorio36140b52006-06-13 02:17:52 +0000685 (response, content) = self.http.request(uri, "GET", headers={'Cache-Control': 'no-store'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000686 self.assertEqual(response.status, 200)
687 self.assertEqual(response.fromcache, False)
688
jcgregorio36140b52006-06-13 02:17:52 +0000689 (response, content) = self.http.request(uri, "GET", headers={'Cache-Control': 'no-store'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000690 self.assertEqual(response.status, 200)
691 self.assertEqual(response.fromcache, False)
692
693 def testGetCacheControlNoStoreResponse(self):
694 # A no-store response means that the response should not be stored.
695 uri = urlparse.urljoin(base, "no-store/no-store.asis")
696
jcgregorio36140b52006-06-13 02:17:52 +0000697 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000698 self.assertEqual(response.status, 200)
699 self.assertEqual(response.fromcache, False)
700
jcgregorio36140b52006-06-13 02:17:52 +0000701 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000702 self.assertEqual(response.status, 200)
703 self.assertEqual(response.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000704
705 def testGetCacheControlNoCacheNoStoreRequest(self):
706 # Test that a no-store, no-cache clears the entry from the cache
707 # even if it was cached previously.
708 uri = urlparse.urljoin(base, "304/test_etag.txt")
709
jcgregorio36140b52006-06-13 02:17:52 +0000710 (response, content) = self.http.request(uri, "GET")
711 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000712 self.assertEqual(response.fromcache, True)
jcgregorio36140b52006-06-13 02:17:52 +0000713 (response, content) = self.http.request(uri, "GET", headers={'Cache-Control': 'no-store, no-cache'})
714 (response, content) = self.http.request(uri, "GET", headers={'Cache-Control': 'no-store, no-cache'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000715 self.assertEqual(response.status, 200)
716 self.assertEqual(response.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000717
718 def testUpdateInvalidatesCache(self):
719 # Test that calling PUT or DELETE on a
720 # URI that is cache invalidates that cache.
721 uri = urlparse.urljoin(base, "304/test_etag.txt")
722
jcgregorio36140b52006-06-13 02:17:52 +0000723 (response, content) = self.http.request(uri, "GET")
724 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000725 self.assertEqual(response.fromcache, True)
jcgregorio36140b52006-06-13 02:17:52 +0000726 (response, content) = self.http.request(uri, "DELETE")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000727 self.assertEqual(response.status, 405)
728
jcgregorio36140b52006-06-13 02:17:52 +0000729 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000730 self.assertEqual(response.fromcache, False)
731
732 def testUpdateUsesCachedETag(self):
733 # Test that we natively support http://www.w3.org/1999/04/Editing/
734 uri = urlparse.urljoin(base, "conditional-updates/test.cgi")
735
jcgregorio36140b52006-06-13 02:17:52 +0000736 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000737 self.assertEqual(response.status, 200)
738 self.assertEqual(response.fromcache, False)
jcgregorio36140b52006-06-13 02:17:52 +0000739 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000740 self.assertEqual(response.status, 200)
741 self.assertEqual(response.fromcache, True)
jcgregorio36140b52006-06-13 02:17:52 +0000742 (response, content) = self.http.request(uri, "PUT")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000743 self.assertEqual(response.status, 200)
jcgregorio36140b52006-06-13 02:17:52 +0000744 (response, content) = self.http.request(uri, "PUT")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000745 self.assertEqual(response.status, 412)
746
joe.gregorio700f04d2008-09-06 04:46:32 +0000747 def testUpdateUsesCachedETagAndOCMethod(self):
748 # Test that we natively support http://www.w3.org/1999/04/Editing/
749 uri = urlparse.urljoin(base, "conditional-updates/test.cgi")
750
751 (response, content) = self.http.request(uri, "GET")
752 self.assertEqual(response.status, 200)
753 self.assertEqual(response.fromcache, False)
754 (response, content) = self.http.request(uri, "GET")
755 self.assertEqual(response.status, 200)
756 self.assertEqual(response.fromcache, True)
757 self.http.optimistic_concurrency_methods.append("DELETE")
758 (response, content) = self.http.request(uri, "DELETE")
759 self.assertEqual(response.status, 200)
760
761
jcgregorio4b145e82007-01-18 19:46:34 +0000762 def testUpdateUsesCachedETagOverridden(self):
763 # Test that we natively support http://www.w3.org/1999/04/Editing/
764 uri = urlparse.urljoin(base, "conditional-updates/test.cgi")
765
766 (response, content) = self.http.request(uri, "GET")
767 self.assertEqual(response.status, 200)
768 self.assertEqual(response.fromcache, False)
769 (response, content) = self.http.request(uri, "GET")
770 self.assertEqual(response.status, 200)
771 self.assertEqual(response.fromcache, True)
772 (response, content) = self.http.request(uri, "PUT", headers={'if-match': 'fred'})
773 self.assertEqual(response.status, 412)
774
jcgregorio2d66d4f2006-02-07 05:34:14 +0000775 def testBasicAuth(self):
776 # Test Basic Authentication
777 uri = urlparse.urljoin(base, "basic/file.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000778 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000779 self.assertEqual(response.status, 401)
780
781 uri = urlparse.urljoin(base, "basic/")
jcgregorio36140b52006-06-13 02:17:52 +0000782 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000783 self.assertEqual(response.status, 401)
784
jcgregorio36140b52006-06-13 02:17:52 +0000785 self.http.add_credentials('joe', 'password')
786 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000787 self.assertEqual(response.status, 200)
788
789 uri = urlparse.urljoin(base, "basic/file.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000790 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000791 self.assertEqual(response.status, 200)
792
jcgregoriode8238d2007-03-07 19:08:26 +0000793 def testBasicAuthWithDomain(self):
794 # Test Basic Authentication
795 uri = urlparse.urljoin(base, "basic/file.txt")
796 (response, content) = self.http.request(uri, "GET")
797 self.assertEqual(response.status, 401)
798
799 uri = urlparse.urljoin(base, "basic/")
800 (response, content) = self.http.request(uri, "GET")
801 self.assertEqual(response.status, 401)
802
803 self.http.add_credentials('joe', 'password', "example.org")
804 (response, content) = self.http.request(uri, "GET")
805 self.assertEqual(response.status, 401)
806
807 uri = urlparse.urljoin(base, "basic/file.txt")
808 (response, content) = self.http.request(uri, "GET")
809 self.assertEqual(response.status, 401)
810
811 domain = urlparse.urlparse(base)[1]
812 self.http.add_credentials('joe', 'password', domain)
813 (response, content) = self.http.request(uri, "GET")
814 self.assertEqual(response.status, 200)
815
816 uri = urlparse.urljoin(base, "basic/file.txt")
817 (response, content) = self.http.request(uri, "GET")
818 self.assertEqual(response.status, 200)
819
820
821
822
823
824
jcgregorio2d66d4f2006-02-07 05:34:14 +0000825 def testBasicAuthTwoDifferentCredentials(self):
jcgregorioadbb4f82006-05-19 15:17:42 +0000826 # Test Basic Authentication with multiple sets of credentials
jcgregorio2d66d4f2006-02-07 05:34:14 +0000827 uri = urlparse.urljoin(base, "basic2/file.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000828 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000829 self.assertEqual(response.status, 401)
830
831 uri = urlparse.urljoin(base, "basic2/")
jcgregorio36140b52006-06-13 02:17:52 +0000832 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000833 self.assertEqual(response.status, 401)
834
jcgregorio36140b52006-06-13 02:17:52 +0000835 self.http.add_credentials('fred', 'barney')
836 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000837 self.assertEqual(response.status, 200)
838
839 uri = urlparse.urljoin(base, "basic2/file.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000840 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000841 self.assertEqual(response.status, 200)
842
843 def testBasicAuthNested(self):
844 # Test Basic Authentication with resources
845 # that are nested
846 uri = urlparse.urljoin(base, "basic-nested/")
jcgregorio36140b52006-06-13 02:17:52 +0000847 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000848 self.assertEqual(response.status, 401)
849
850 uri = urlparse.urljoin(base, "basic-nested/subdir")
jcgregorio36140b52006-06-13 02:17:52 +0000851 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000852 self.assertEqual(response.status, 401)
853
jcgregorioadbb4f82006-05-19 15:17:42 +0000854 # Now add in credentials one at a time and test.
jcgregorio36140b52006-06-13 02:17:52 +0000855 self.http.add_credentials('joe', 'password')
jcgregorio2d66d4f2006-02-07 05:34:14 +0000856
857 uri = urlparse.urljoin(base, "basic-nested/")
jcgregorio36140b52006-06-13 02:17:52 +0000858 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000859 self.assertEqual(response.status, 200)
860
861 uri = urlparse.urljoin(base, "basic-nested/subdir")
jcgregorio36140b52006-06-13 02:17:52 +0000862 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000863 self.assertEqual(response.status, 401)
864
jcgregorio36140b52006-06-13 02:17:52 +0000865 self.http.add_credentials('fred', 'barney')
jcgregorio2d66d4f2006-02-07 05:34:14 +0000866
867 uri = urlparse.urljoin(base, "basic-nested/")
jcgregorio36140b52006-06-13 02:17:52 +0000868 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000869 self.assertEqual(response.status, 200)
870
871 uri = urlparse.urljoin(base, "basic-nested/subdir")
jcgregorio36140b52006-06-13 02:17:52 +0000872 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000873 self.assertEqual(response.status, 200)
874
875 def testDigestAuth(self):
876 # Test that we support Digest Authentication
877 uri = urlparse.urljoin(base, "digest/")
jcgregorio36140b52006-06-13 02:17:52 +0000878 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000879 self.assertEqual(response.status, 401)
880
jcgregorio36140b52006-06-13 02:17:52 +0000881 self.http.add_credentials('joe', 'password')
882 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000883 self.assertEqual(response.status, 200)
884
885 uri = urlparse.urljoin(base, "digest/file.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000886 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000887
888 def testDigestAuthNextNonceAndNC(self):
889 # Test that if the server sets nextnonce that we reset
890 # the nonce count back to 1
891 uri = urlparse.urljoin(base, "digest/file.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000892 self.http.add_credentials('joe', 'password')
893 (response, content) = self.http.request(uri, "GET", headers = {"cache-control":"no-cache"})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000894 info = httplib2._parse_www_authenticate(response, 'authentication-info')
895 self.assertEqual(response.status, 200)
jcgregorio36140b52006-06-13 02:17:52 +0000896 (response, content) = self.http.request(uri, "GET", headers = {"cache-control":"no-cache"})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000897 info2 = httplib2._parse_www_authenticate(response, 'authentication-info')
898 self.assertEqual(response.status, 200)
899
900 if info.has_key('nextnonce'):
901 self.assertEqual(info2['nc'], 1)
902
903 def testDigestAuthStale(self):
904 # Test that we can handle a nonce becoming stale
905 uri = urlparse.urljoin(base, "digest-expire/file.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000906 self.http.add_credentials('joe', 'password')
907 (response, content) = self.http.request(uri, "GET", headers = {"cache-control":"no-cache"})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000908 info = httplib2._parse_www_authenticate(response, 'authentication-info')
909 self.assertEqual(response.status, 200)
910
911 time.sleep(3)
912 # Sleep long enough that the nonce becomes stale
913
jcgregorio36140b52006-06-13 02:17:52 +0000914 (response, content) = self.http.request(uri, "GET", headers = {"cache-control":"no-cache"})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000915 self.assertFalse(response.fromcache)
916 self.assertTrue(response._stale_digest)
917 info3 = httplib2._parse_www_authenticate(response, 'authentication-info')
918 self.assertEqual(response.status, 200)
919
920 def reflector(self, content):
jcgregorio25185622006-10-28 05:12:34 +0000921 return dict( [tuple(x.split("=", 1)) for x in content.strip().split("\n")] )
jcgregorio2d66d4f2006-02-07 05:34:14 +0000922
923 def testReflector(self):
924 uri = urlparse.urljoin(base, "reflector/reflector.cgi")
jcgregorio36140b52006-06-13 02:17:52 +0000925 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000926 d = self.reflector(content)
927 self.assertTrue(d.has_key('HTTP_USER_AGENT'))
928
jcgregorio36140b52006-06-13 02:17:52 +0000929try:
930 import memcache
931 class HttpTestMemCached(HttpTest):
932 def setUp(self):
933 self.cache = memcache.Client(['127.0.0.1:11211'], debug=0)
jcgregorio47d24672006-06-29 05:18:59 +0000934 #self.cache = memcache.Client(['10.0.0.4:11211'], debug=1)
jcgregorio36140b52006-06-13 02:17:52 +0000935 self.http = httplib2.Http(self.cache)
936 self.cache.flush_all()
jcgregorio47d24672006-06-29 05:18:59 +0000937 # Not exactly sure why the sleep is needed here, but
938 # if not present then some unit tests that rely on caching
939 # fail. Memcached seems to lose some sets immediately
940 # after a flush_all if the set is to a value that
941 # was previously cached. (Maybe the flush is handled async?)
942 time.sleep(1)
jcgregorio36140b52006-06-13 02:17:52 +0000943 self.http.clear_credentials()
944except:
945 pass
946
947
948
jcgregoriodb8dfc82006-03-31 14:59:46 +0000949# ------------------------------------------------------------------------
jcgregorio2d66d4f2006-02-07 05:34:14 +0000950
951class HttpPrivateTest(unittest.TestCase):
952
953 def testParseCacheControl(self):
954 # Test that we can parse the Cache-Control header
955 self.assertEqual({}, httplib2._parse_cache_control({}))
956 self.assertEqual({'no-cache': 1}, httplib2._parse_cache_control({'cache-control': ' no-cache'}))
957 cc = httplib2._parse_cache_control({'cache-control': ' no-cache, max-age = 7200'})
958 self.assertEqual(cc['no-cache'], 1)
959 self.assertEqual(cc['max-age'], '7200')
960 cc = httplib2._parse_cache_control({'cache-control': ' , '})
961 self.assertEqual(cc[''], 1)
962
963 def testNormalizeHeaders(self):
964 # Test that we normalize headers to lowercase
965 h = httplib2._normalize_headers({'Cache-Control': 'no-cache', 'Other': 'Stuff'})
966 self.assertTrue(h.has_key('cache-control'))
967 self.assertTrue(h.has_key('other'))
968 self.assertEqual('Stuff', h['other'])
969
970 def testExpirationModelTransparent(self):
971 # Test that no-cache makes our request TRANSPARENT
972 response_headers = {
973 'cache-control': 'max-age=7200'
974 }
975 request_headers = {
976 'cache-control': 'no-cache'
977 }
978 self.assertEqual("TRANSPARENT", httplib2._entry_disposition(response_headers, request_headers))
979
jcgregorio45865012007-01-18 16:38:22 +0000980 def testMaxAgeNonNumeric(self):
981 # Test that no-cache makes our request TRANSPARENT
982 response_headers = {
983 'cache-control': 'max-age=fred, min-fresh=barney'
984 }
985 request_headers = {
986 }
987 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
988
989
jcgregorio2d66d4f2006-02-07 05:34:14 +0000990 def testExpirationModelNoCacheResponse(self):
991 # The date and expires point to an entry that should be
992 # FRESH, but the no-cache over-rides that.
993 now = time.time()
994 response_headers = {
995 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now)),
996 'expires': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now+4)),
997 'cache-control': 'no-cache'
998 }
999 request_headers = {
1000 }
1001 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1002
1003 def testExpirationModelStaleRequestMustReval(self):
1004 # must-revalidate forces STALE
1005 self.assertEqual("STALE", httplib2._entry_disposition({}, {'cache-control': 'must-revalidate'}))
1006
1007 def testExpirationModelStaleResponseMustReval(self):
1008 # must-revalidate forces STALE
1009 self.assertEqual("STALE", httplib2._entry_disposition({'cache-control': 'must-revalidate'}, {}))
1010
1011 def testExpirationModelFresh(self):
1012 response_headers = {
1013 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime()),
1014 'cache-control': 'max-age=2'
1015 }
1016 request_headers = {
1017 }
1018 self.assertEqual("FRESH", httplib2._entry_disposition(response_headers, request_headers))
1019 time.sleep(3)
1020 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1021
1022 def testExpirationMaxAge0(self):
1023 response_headers = {
1024 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime()),
1025 'cache-control': 'max-age=0'
1026 }
1027 request_headers = {
1028 }
1029 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1030
1031 def testExpirationModelDateAndExpires(self):
1032 now = time.time()
1033 response_headers = {
1034 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now)),
1035 'expires': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now+2)),
1036 }
1037 request_headers = {
1038 }
1039 self.assertEqual("FRESH", httplib2._entry_disposition(response_headers, request_headers))
1040 time.sleep(3)
1041 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1042
jcgregoriof9511052007-06-01 14:56:34 +00001043 def testExpiresZero(self):
1044 now = time.time()
1045 response_headers = {
1046 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now)),
1047 'expires': "0",
1048 }
1049 request_headers = {
1050 }
1051 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1052
jcgregorio2d66d4f2006-02-07 05:34:14 +00001053 def testExpirationModelDateOnly(self):
1054 now = time.time()
1055 response_headers = {
1056 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now+3)),
1057 }
1058 request_headers = {
1059 }
1060 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1061
1062 def testExpirationModelOnlyIfCached(self):
1063 response_headers = {
1064 }
1065 request_headers = {
1066 'cache-control': 'only-if-cached',
1067 }
1068 self.assertEqual("FRESH", httplib2._entry_disposition(response_headers, request_headers))
1069
1070 def testExpirationModelMaxAgeBoth(self):
1071 now = time.time()
1072 response_headers = {
1073 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now)),
1074 'cache-control': 'max-age=2'
1075 }
1076 request_headers = {
1077 'cache-control': 'max-age=0'
1078 }
1079 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1080
1081 def testExpirationModelDateAndExpiresMinFresh1(self):
1082 now = time.time()
1083 response_headers = {
1084 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now)),
1085 'expires': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now+2)),
1086 }
1087 request_headers = {
1088 'cache-control': 'min-fresh=2'
1089 }
1090 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1091
1092 def testExpirationModelDateAndExpiresMinFresh2(self):
1093 now = time.time()
1094 response_headers = {
1095 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now)),
1096 'expires': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now+4)),
1097 }
1098 request_headers = {
1099 'cache-control': 'min-fresh=2'
1100 }
1101 self.assertEqual("FRESH", httplib2._entry_disposition(response_headers, request_headers))
1102
1103 def testParseWWWAuthenticateEmpty(self):
1104 res = httplib2._parse_www_authenticate({})
1105 self.assertEqual(len(res.keys()), 0)
1106
jcgregoriofd22e432006-04-27 02:00:08 +00001107 def testParseWWWAuthenticate(self):
1108 # different uses of spaces around commas
1109 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'Test realm="test realm" , foo=foo ,bar="bar", baz=baz,qux=qux'})
1110 self.assertEqual(len(res.keys()), 1)
1111 self.assertEqual(len(res['test'].keys()), 5)
1112
1113 # tokens with non-alphanum
1114 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'T*!%#st realm=to*!%#en, to*!%#en="quoted string"'})
1115 self.assertEqual(len(res.keys()), 1)
1116 self.assertEqual(len(res['t*!%#st'].keys()), 2)
1117
1118 # quoted string with quoted pairs
1119 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'Test realm="a \\"test\\" realm"'})
1120 self.assertEqual(len(res.keys()), 1)
1121 self.assertEqual(res['test']['realm'], 'a "test" realm')
1122
1123 def testParseWWWAuthenticateStrict(self):
1124 httplib2.USE_WWW_AUTH_STRICT_PARSING = 1;
1125 self.testParseWWWAuthenticate();
1126 httplib2.USE_WWW_AUTH_STRICT_PARSING = 0;
1127
jcgregorio2d66d4f2006-02-07 05:34:14 +00001128 def testParseWWWAuthenticateBasic(self):
1129 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'Basic realm="me"'})
1130 basic = res['basic']
1131 self.assertEqual('me', basic['realm'])
1132
1133 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'Basic realm="me", algorithm="MD5"'})
1134 basic = res['basic']
1135 self.assertEqual('me', basic['realm'])
1136 self.assertEqual('MD5', basic['algorithm'])
1137
1138 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'Basic realm="me", algorithm=MD5'})
1139 basic = res['basic']
1140 self.assertEqual('me', basic['realm'])
1141 self.assertEqual('MD5', basic['algorithm'])
1142
1143 def testParseWWWAuthenticateBasic2(self):
1144 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'Basic realm="me",other="fred" '})
1145 basic = res['basic']
1146 self.assertEqual('me', basic['realm'])
1147 self.assertEqual('fred', basic['other'])
1148
1149 def testParseWWWAuthenticateBasic3(self):
1150 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'Basic REAlm="me" '})
1151 basic = res['basic']
1152 self.assertEqual('me', basic['realm'])
1153
1154
1155 def testParseWWWAuthenticateDigest(self):
1156 res = httplib2._parse_www_authenticate({ 'www-authenticate':
1157 'Digest realm="testrealm@host.com", qop="auth,auth-int", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41"'})
1158 digest = res['digest']
1159 self.assertEqual('testrealm@host.com', digest['realm'])
1160 self.assertEqual('auth,auth-int', digest['qop'])
1161
1162
1163 def testParseWWWAuthenticateMultiple(self):
1164 res = httplib2._parse_www_authenticate({ 'www-authenticate':
1165 'Digest realm="testrealm@host.com", qop="auth,auth-int", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41" Basic REAlm="me" '})
1166 digest = res['digest']
1167 self.assertEqual('testrealm@host.com', digest['realm'])
1168 self.assertEqual('auth,auth-int', digest['qop'])
1169 self.assertEqual('dcd98b7102dd2f0e8b11d0f600bfb0c093', digest['nonce'])
1170 self.assertEqual('5ccc069c403ebaf9f0171e9517f40e41', digest['opaque'])
1171 basic = res['basic']
1172 self.assertEqual('me', basic['realm'])
1173
1174 def testParseWWWAuthenticateMultiple2(self):
1175 # Handle an added comma between challenges, which might get thrown in if the challenges were
1176 # originally sent in separate www-authenticate headers.
1177 res = httplib2._parse_www_authenticate({ 'www-authenticate':
1178 'Digest realm="testrealm@host.com", qop="auth,auth-int", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41", Basic REAlm="me" '})
1179 digest = res['digest']
1180 self.assertEqual('testrealm@host.com', digest['realm'])
1181 self.assertEqual('auth,auth-int', digest['qop'])
1182 self.assertEqual('dcd98b7102dd2f0e8b11d0f600bfb0c093', digest['nonce'])
1183 self.assertEqual('5ccc069c403ebaf9f0171e9517f40e41', digest['opaque'])
1184 basic = res['basic']
1185 self.assertEqual('me', basic['realm'])
1186
1187 def testParseWWWAuthenticateMultiple3(self):
1188 # Handle an added comma between challenges, which might get thrown in if the challenges were
1189 # originally sent in separate www-authenticate headers.
1190 res = httplib2._parse_www_authenticate({ 'www-authenticate':
1191 'Digest realm="testrealm@host.com", qop="auth,auth-int", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41", Basic REAlm="me", WSSE realm="foo", profile="UsernameToken"'})
1192 digest = res['digest']
1193 self.assertEqual('testrealm@host.com', digest['realm'])
1194 self.assertEqual('auth,auth-int', digest['qop'])
1195 self.assertEqual('dcd98b7102dd2f0e8b11d0f600bfb0c093', digest['nonce'])
1196 self.assertEqual('5ccc069c403ebaf9f0171e9517f40e41', digest['opaque'])
1197 basic = res['basic']
1198 self.assertEqual('me', basic['realm'])
1199 wsse = res['wsse']
1200 self.assertEqual('foo', wsse['realm'])
1201 self.assertEqual('UsernameToken', wsse['profile'])
1202
1203 def testParseWWWAuthenticateMultiple4(self):
1204 res = httplib2._parse_www_authenticate({ 'www-authenticate':
1205 'Digest realm="test-real.m@host.com", qop \t=\t"\tauth,auth-int", nonce="(*)&^&$%#",opaque="5ccc069c403ebaf9f0171e9517f40e41", Basic REAlm="me", WSSE realm="foo", profile="UsernameToken"'})
1206 digest = res['digest']
1207 self.assertEqual('test-real.m@host.com', digest['realm'])
1208 self.assertEqual('\tauth,auth-int', digest['qop'])
1209 self.assertEqual('(*)&^&$%#', digest['nonce'])
1210
1211 def testParseWWWAuthenticateMoreQuoteCombos(self):
1212 res = httplib2._parse_www_authenticate({'www-authenticate':'Digest realm="myrealm", nonce="Ygk86AsKBAA=3516200d37f9a3230352fde99977bd6d472d4306", algorithm=MD5, qop="auth", stale=true'})
1213 digest = res['digest']
1214 self.assertEqual('myrealm', digest['realm'])
1215
1216 def testDigestObject(self):
1217 credentials = ('joe', 'password')
1218 host = None
1219 request_uri = '/projects/httplib2/test/digest/'
1220 headers = {}
1221 response = {
1222 'www-authenticate': 'Digest realm="myrealm", nonce="Ygk86AsKBAA=3516200d37f9a3230352fde99977bd6d472d4306", algorithm=MD5, qop="auth"'
1223 }
1224 content = ""
1225
jcgregorio6cbab7e2006-04-21 20:35:43 +00001226 d = httplib2.DigestAuthentication(credentials, host, request_uri, headers, response, content, None)
jcgregorio2d66d4f2006-02-07 05:34:14 +00001227 d.request("GET", request_uri, headers, content, cnonce="33033375ec278a46")
1228 our_request = "Authorization: %s" % headers['Authorization']
1229 working_request = 'Authorization: Digest username="joe", realm="myrealm", nonce="Ygk86AsKBAA=3516200d37f9a3230352fde99977bd6d472d4306", uri="/projects/httplib2/test/digest/", algorithm=MD5, response="97ed129401f7cdc60e5db58a80f3ea8b", qop=auth, nc=00000001, cnonce="33033375ec278a46"'
1230 self.assertEqual(our_request, working_request)
1231
1232
1233 def testDigestObjectStale(self):
1234 credentials = ('joe', 'password')
1235 host = None
1236 request_uri = '/projects/httplib2/test/digest/'
1237 headers = {}
1238 response = httplib2.Response({ })
1239 response['www-authenticate'] = 'Digest realm="myrealm", nonce="Ygk86AsKBAA=3516200d37f9a3230352fde99977bd6d472d4306", algorithm=MD5, qop="auth", stale=true'
1240 response.status = 401
1241 content = ""
jcgregorio6cbab7e2006-04-21 20:35:43 +00001242 d = httplib2.DigestAuthentication(credentials, host, request_uri, headers, response, content, None)
jcgregorio2d66d4f2006-02-07 05:34:14 +00001243 # Returns true to force a retry
1244 self.assertTrue( d.response(response, content) )
1245
1246 def testDigestObjectAuthInfo(self):
1247 credentials = ('joe', 'password')
1248 host = None
1249 request_uri = '/projects/httplib2/test/digest/'
1250 headers = {}
1251 response = httplib2.Response({ })
1252 response['www-authenticate'] = 'Digest realm="myrealm", nonce="Ygk86AsKBAA=3516200d37f9a3230352fde99977bd6d472d4306", algorithm=MD5, qop="auth", stale=true'
1253 response['authentication-info'] = 'nextnonce="fred"'
1254 content = ""
jcgregorio6cbab7e2006-04-21 20:35:43 +00001255 d = httplib2.DigestAuthentication(credentials, host, request_uri, headers, response, content, None)
jcgregorio2d66d4f2006-02-07 05:34:14 +00001256 # Returns true to force a retry
1257 self.assertFalse( d.response(response, content) )
1258 self.assertEqual('fred', d.challenge['nonce'])
1259 self.assertEqual(1, d.challenge['nc'])
1260
1261 def testWsseAlgorithm(self):
1262 digest = httplib2._wsse_username_token("d36e316282959a9ed4c89851497a717f", "2003-12-15T14:43:07Z", "taadtaadpstcsm")
1263 expected = "quR/EWLAV4xLf9Zqyw4pDmfV9OY="
1264 self.assertEqual(expected, digest)
1265
jcgregoriodb8dfc82006-03-31 14:59:46 +00001266 def testEnd2End(self):
1267 # one end to end header
1268 response = {'content-type': 'application/atom+xml', 'te': 'deflate'}
1269 end2end = httplib2._get_end2end_headers(response)
1270 self.assertTrue('content-type' in end2end)
1271 self.assertTrue('te' not in end2end)
1272 self.assertTrue('connection' not in end2end)
1273
1274 # one end to end header that gets eliminated
1275 response = {'connection': 'content-type', 'content-type': 'application/atom+xml', 'te': 'deflate'}
1276 end2end = httplib2._get_end2end_headers(response)
1277 self.assertTrue('content-type' not in end2end)
1278 self.assertTrue('te' not in end2end)
1279 self.assertTrue('connection' not in end2end)
1280
1281 # Degenerate case of no headers
1282 response = {}
1283 end2end = httplib2._get_end2end_headers(response)
1284 self.assertEquals(0, len(end2end))
1285
1286 # Degenerate case of connection referrring to a header not passed in
1287 response = {'connection': 'content-type'}
1288 end2end = httplib2._get_end2end_headers(response)
1289 self.assertEquals(0, len(end2end))
jcgregorio2d66d4f2006-02-07 05:34:14 +00001290
1291unittest.main()