blob: f882b17e33c7a16ce7a7309a8f6e2092e6e78a2e [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
Joe Gregoriob628c0b2009-07-16 12:28:04 -0400190 def testHeadRead(self):
191 # Test that we don't try to read the response of a HEAD request
192 # since httplib blocks response.read() for HEAD requests.
193 # Oddly enough this doesn't appear as a problem when doing HEAD requests
194 # against Apache servers.
195 uri = "http://www.google.com/"
196 (response, content) = self.http.request(uri, "HEAD")
197 self.assertEqual(response.status, 200)
198 self.assertEqual(content, "")
199
jcgregorio2d66d4f2006-02-07 05:34:14 +0000200 def testGetNoCache(self):
201 # Test that can do a GET w/o the cache turned on.
202 http = httplib2.Http()
203 uri = urlparse.urljoin(base, "304/test_etag.txt")
204 (response, content) = http.request(uri, "GET")
205 self.assertEqual(response.status, 200)
jcgregorioa0713ab2006-07-01 05:21:34 +0000206 self.assertEqual(response.previous, None)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000207
jcgregorioe4ce13e2006-04-02 03:05:08 +0000208 def testGetOnlyIfCachedCacheMiss(self):
209 # Test that can do a GET with no cache with 'only-if-cached'
jcgregorio36140b52006-06-13 02:17:52 +0000210 http = httplib2.Http()
jcgregorioe4ce13e2006-04-02 03:05:08 +0000211 uri = urlparse.urljoin(base, "304/test_etag.txt")
212 (response, content) = http.request(uri, "GET", headers={'cache-control': 'only-if-cached'})
213 self.assertEqual(response.fromcache, False)
jcgregorio36140b52006-06-13 02:17:52 +0000214 self.assertEqual(response.status, 200)
jcgregorioe4ce13e2006-04-02 03:05:08 +0000215
216 def testGetOnlyIfCachedNoCacheAtAll(self):
217 # Test that can do a GET with no cache with 'only-if-cached'
218 # Of course, there might be an intermediary beyond us
219 # that responds to the 'only-if-cached', so this
220 # test can't really be guaranteed to pass.
221 http = httplib2.Http()
222 uri = urlparse.urljoin(base, "304/test_etag.txt")
223 (response, content) = http.request(uri, "GET", headers={'cache-control': 'only-if-cached'})
224 self.assertEqual(response.fromcache, False)
225 self.assertEqual(response.status, 200)
226
jcgregorio2d66d4f2006-02-07 05:34:14 +0000227 def testUserAgent(self):
228 # Test that we provide a default user-agent
229 uri = urlparse.urljoin(base, "user-agent/test.cgi")
jcgregorio36140b52006-06-13 02:17:52 +0000230 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000231 self.assertEqual(response.status, 200)
232 self.assertTrue(content.startswith("Python-httplib2/"))
233
234 def testUserAgentNonDefault(self):
235 # Test that the default user-agent can be over-ridden
joe.gregoriof28536d2007-10-23 14:10:11 +0000236
jcgregorio2d66d4f2006-02-07 05:34:14 +0000237 uri = urlparse.urljoin(base, "user-agent/test.cgi")
jcgregorio36140b52006-06-13 02:17:52 +0000238 (response, content) = self.http.request(uri, "GET", headers={'User-Agent': 'fred/1.0'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000239 self.assertEqual(response.status, 200)
240 self.assertTrue(content.startswith("fred/1.0"))
241
242 def testGet300WithLocation(self):
243 # Test the we automatically follow 300 redirects if a Location: header is provided
244 uri = urlparse.urljoin(base, "300/with-location-header.asis")
jcgregorio36140b52006-06-13 02:17:52 +0000245 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000246 self.assertEqual(response.status, 200)
247 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000248 self.assertEqual(response.previous.status, 300)
249 self.assertEqual(response.previous.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000250
251 # Confirm that the intermediate 300 is not cached
jcgregorio36140b52006-06-13 02:17:52 +0000252 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000253 self.assertEqual(response.status, 200)
254 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000255 self.assertEqual(response.previous.status, 300)
256 self.assertEqual(response.previous.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000257
jcgregorio2f1e1422007-05-03 13:17:33 +0000258 def testGet300WithLocationNoRedirect(self):
259 # Test the we automatically follow 300 redirects if a Location: header is provided
260 self.http.follow_redirects = False
261 uri = urlparse.urljoin(base, "300/with-location-header.asis")
262 (response, content) = self.http.request(uri, "GET")
263 self.assertEqual(response.status, 300)
264
jcgregorio2d66d4f2006-02-07 05:34:14 +0000265 def testGet300WithoutLocation(self):
266 # Not giving a Location: header in a 300 response is acceptable
267 # In which case we just return the 300 response
268 uri = urlparse.urljoin(base, "300/without-location-header.asis")
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, 300)
271 self.assertTrue(response['content-type'].startswith("text/html"))
jcgregorioa0713ab2006-07-01 05:21:34 +0000272 self.assertEqual(response.previous, None)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000273
274 def testGet301(self):
275 # Test that we automatically follow 301 redirects
276 # and that we cache the 301 response
277 uri = urlparse.urljoin(base, "301/onestep.asis")
jcgregorio8e300b92006-11-07 16:44:35 +0000278 destination = urlparse.urljoin(base, "302/final-destination.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000279 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000280 self.assertEqual(response.status, 200)
jcgregorio772adc82006-11-17 21:52:34 +0000281 self.assertTrue(response.has_key('content-location'))
282 self.assertEqual(response['content-location'], destination)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000283 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000284 self.assertEqual(response.previous.status, 301)
285 self.assertEqual(response.previous.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000286
jcgregorio36140b52006-06-13 02:17:52 +0000287 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000288 self.assertEqual(response.status, 200)
jcgregorio772adc82006-11-17 21:52:34 +0000289 self.assertEqual(response['content-location'], destination)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000290 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000291 self.assertEqual(response.previous.status, 301)
292 self.assertEqual(response.previous.fromcache, True)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000293
jcgregorio2f1e1422007-05-03 13:17:33 +0000294
295 def testGet301NoRedirect(self):
296 # Test that we automatically follow 301 redirects
297 # and that we cache the 301 response
298 self.http.follow_redirects = False
299 uri = urlparse.urljoin(base, "301/onestep.asis")
300 destination = urlparse.urljoin(base, "302/final-destination.txt")
301 (response, content) = self.http.request(uri, "GET")
302 self.assertEqual(response.status, 301)
303
304
jcgregorio2d66d4f2006-02-07 05:34:14 +0000305 def testGet302(self):
306 # Test that we automatically follow 302 redirects
307 # and that we DO NOT cache the 302 response
308 uri = urlparse.urljoin(base, "302/onestep.asis")
jcgregorio8e300b92006-11-07 16:44:35 +0000309 destination = urlparse.urljoin(base, "302/final-destination.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000310 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000311 self.assertEqual(response.status, 200)
jcgregorio772adc82006-11-17 21:52:34 +0000312 self.assertEqual(response['content-location'], destination)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000313 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000314 self.assertEqual(response.previous.status, 302)
315 self.assertEqual(response.previous.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000316
317 uri = urlparse.urljoin(base, "302/onestep.asis")
jcgregorio36140b52006-06-13 02:17:52 +0000318 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000319 self.assertEqual(response.status, 200)
320 self.assertEqual(response.fromcache, True)
jcgregorio772adc82006-11-17 21:52:34 +0000321 self.assertEqual(response['content-location'], destination)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000322 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)
jcgregorio772adc82006-11-17 21:52:34 +0000325 self.assertEqual(response.previous['content-location'], uri)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000326
327 uri = urlparse.urljoin(base, "302/twostep.asis")
328
jcgregorio36140b52006-06-13 02:17:52 +0000329 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000330 self.assertEqual(response.status, 200)
331 self.assertEqual(response.fromcache, True)
332 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000333 self.assertEqual(response.previous.status, 302)
334 self.assertEqual(response.previous.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000335
336 def testGet302RedirectionLimit(self):
337 # Test that we can set a lower redirection limit
338 # and that we raise an exception when we exceed
339 # that limit.
jcgregorio07a9a4a2007-03-08 21:18:39 +0000340 self.http.force_exception_to_status_code = False
341
jcgregorio2d66d4f2006-02-07 05:34:14 +0000342 uri = urlparse.urljoin(base, "302/twostep.asis")
343 try:
jcgregorio36140b52006-06-13 02:17:52 +0000344 (response, content) = self.http.request(uri, "GET", redirections = 1)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000345 self.fail("This should not happen")
346 except httplib2.RedirectLimit:
347 pass
348 except Exception, e:
349 self.fail("Threw wrong kind of exception ")
350
jcgregorio07a9a4a2007-03-08 21:18:39 +0000351 # Re-run the test with out the exceptions
352 self.http.force_exception_to_status_code = True
353
354 (response, content) = self.http.request(uri, "GET", redirections = 1)
355 self.assertEqual(response.status, 500)
356 self.assertTrue(response.reason.startswith("Redirected more"))
357 self.assertEqual("302", response['status'])
358 self.assertTrue(content.startswith("<html>"))
359 self.assertTrue(response.previous != None)
360
jcgregorio2d66d4f2006-02-07 05:34:14 +0000361 def testGet302NoLocation(self):
362 # Test that we throw an exception when we get
363 # a 302 with no Location: header.
jcgregorio07a9a4a2007-03-08 21:18:39 +0000364 self.http.force_exception_to_status_code = False
jcgregorio2d66d4f2006-02-07 05:34:14 +0000365 uri = urlparse.urljoin(base, "302/no-location.asis")
366 try:
jcgregorio36140b52006-06-13 02:17:52 +0000367 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000368 self.fail("Should never reach here")
369 except httplib2.RedirectMissingLocation:
370 pass
371 except Exception, e:
372 self.fail("Threw wrong kind of exception ")
373
jcgregorio07a9a4a2007-03-08 21:18:39 +0000374 # Re-run the test with out the exceptions
375 self.http.force_exception_to_status_code = True
376
377 (response, content) = self.http.request(uri, "GET")
378 self.assertEqual(response.status, 500)
379 self.assertTrue(response.reason.startswith("Redirected but"))
380 self.assertEqual("302", response['status'])
381 self.assertTrue(content.startswith("This is content"))
382
jcgregorio2d66d4f2006-02-07 05:34:14 +0000383 def testGet302ViaHttps(self):
jcgregorioadbb4f82006-05-19 15:17:42 +0000384 # Google always redirects to http://google.com
jcgregorio36140b52006-06-13 02:17:52 +0000385 (response, content) = self.http.request("https://google.com", "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000386 self.assertEqual(200, response.status)
jcgregorioa0713ab2006-07-01 05:21:34 +0000387 self.assertEqual(302, response.previous.status)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000388
389 def testGetViaHttps(self):
390 # Test that we can handle HTTPS
jcgregorio36140b52006-06-13 02:17:52 +0000391 (response, content) = self.http.request("https://google.com/adsense/", "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000392 self.assertEqual(200, response.status)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000393
394 def testGetViaHttpsSpecViolationOnLocation(self):
395 # Test that we follow redirects through HTTPS
396 # even if they violate the spec by including
397 # a relative Location: header instead of an
398 # absolute one.
jcgregorio36140b52006-06-13 02:17:52 +0000399 (response, content) = self.http.request("https://google.com/adsense", "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000400 self.assertEqual(200, response.status)
jcgregorioa0713ab2006-07-01 05:21:34 +0000401 self.assertNotEqual(None, response.previous)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000402
jcgregoriode8238d2007-03-07 19:08:26 +0000403
404 def testGetViaHttpsKeyCert(self):
jcgregorio2f1e1422007-05-03 13:17:33 +0000405 # At this point I can only test
406 # that the key and cert files are passed in
407 # correctly to httplib. It would be nice to have
408 # a real https endpoint to test against.
409 http = httplib2.Http(timeout=2)
jcgregoriode8238d2007-03-07 19:08:26 +0000410
411 http.add_certificate("akeyfile", "acertfile", "bitworking.org")
412 try:
413 (response, content) = http.request("https://bitworking.org", "GET")
414 except:
415 pass
416 self.assertEqual(http.connections["https:bitworking.org"].key_file, "akeyfile")
417 self.assertEqual(http.connections["https:bitworking.org"].cert_file, "acertfile")
418
jcgregorio2f1e1422007-05-03 13:17:33 +0000419 try:
420 (response, content) = http.request("https://notthere.bitworking.org", "GET")
421 except:
422 pass
423 self.assertEqual(http.connections["https:notthere.bitworking.org"].key_file, None)
424 self.assertEqual(http.connections["https:notthere.bitworking.org"].cert_file, None)
425
426
427
jcgregoriode8238d2007-03-07 19:08:26 +0000428
jcgregorio2d66d4f2006-02-07 05:34:14 +0000429 def testGet303(self):
430 # Do a follow-up GET on a Location: header
431 # returned from a POST that gave a 303.
432 uri = urlparse.urljoin(base, "303/303.cgi")
jcgregorio36140b52006-06-13 02:17:52 +0000433 (response, content) = self.http.request(uri, "POST", " ")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000434 self.assertEqual(response.status, 200)
435 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000436 self.assertEqual(response.previous.status, 303)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000437
jcgregorio2f1e1422007-05-03 13:17:33 +0000438 def testGet303NoRedirect(self):
439 # Do a follow-up GET on a Location: header
440 # returned from a POST that gave a 303.
441 self.http.follow_redirects = False
442 uri = urlparse.urljoin(base, "303/303.cgi")
443 (response, content) = self.http.request(uri, "POST", " ")
444 self.assertEqual(response.status, 303)
445
jcgregorio2d66d4f2006-02-07 05:34:14 +0000446 def test303ForDifferentMethods(self):
447 # Test that all methods can be used
448 uri = urlparse.urljoin(base, "303/redirect-to-reflector.cgi")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000449 for (method, method_on_303) in [("PUT", "GET"), ("DELETE", "GET"), ("POST", "GET"), ("GET", "GET"), ("HEAD", "GET")]:
jcgregorio36140b52006-06-13 02:17:52 +0000450 (response, content) = self.http.request(uri, method, body=" ")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000451 self.assertEqual(response['x-method'], method_on_303)
452
453 def testGet304(self):
454 # Test that we use ETags properly to validate our cache
455 uri = urlparse.urljoin(base, "304/test_etag.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000456 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000457 self.assertNotEqual(response['etag'], "")
458
jcgregorio36140b52006-06-13 02:17:52 +0000459 (response, content) = self.http.request(uri, "GET")
460 (response, content) = self.http.request(uri, "GET", headers = {'cache-control': 'must-revalidate'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000461 self.assertEqual(response.status, 200)
462 self.assertEqual(response.fromcache, True)
463
jcgregorio90fb4a42006-11-17 16:19:47 +0000464 cache_file_name = os.path.join(cacheDirName, httplib2.safename(httplib2.urlnorm(uri)[-1]))
465 f = open(cache_file_name, "r")
466 status_line = f.readline()
467 f.close()
468
469 self.assertTrue(status_line.startswith("status:"))
470
jcgregorio36140b52006-06-13 02:17:52 +0000471 (response, content) = self.http.request(uri, "HEAD")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000472 self.assertEqual(response.status, 200)
473 self.assertEqual(response.fromcache, True)
474
jcgregorio36140b52006-06-13 02:17:52 +0000475 (response, content) = self.http.request(uri, "GET", headers = {'range': 'bytes=0-0'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000476 self.assertEqual(response.status, 206)
477 self.assertEqual(response.fromcache, False)
478
jcgregorio25185622006-10-28 05:12:34 +0000479 def testGetIgnoreEtag(self):
480 # Test that we can forcibly ignore ETags
481 uri = urlparse.urljoin(base, "reflector/reflector.cgi")
482 (response, content) = self.http.request(uri, "GET")
483 self.assertNotEqual(response['etag'], "")
484
485 (response, content) = self.http.request(uri, "GET", headers = {'cache-control': 'max-age=0'})
486 d = self.reflector(content)
487 self.assertTrue(d.has_key('HTTP_IF_NONE_MATCH'))
488
489 self.http.ignore_etag = True
490 (response, content) = self.http.request(uri, "GET", headers = {'cache-control': 'max-age=0'})
491 d = self.reflector(content)
492 self.assertEqual(response.fromcache, False)
493 self.assertFalse(d.has_key('HTTP_IF_NONE_MATCH'))
494
jcgregorio4b145e82007-01-18 19:46:34 +0000495 def testOverrideEtag(self):
496 # Test that we can forcibly ignore ETags
497 uri = urlparse.urljoin(base, "reflector/reflector.cgi")
498 (response, content) = self.http.request(uri, "GET")
499 self.assertNotEqual(response['etag'], "")
500
501 (response, content) = self.http.request(uri, "GET", headers = {'cache-control': 'max-age=0'})
502 d = self.reflector(content)
503 self.assertTrue(d.has_key('HTTP_IF_NONE_MATCH'))
504 self.assertNotEqual(d['HTTP_IF_NONE_MATCH'], "fred")
505
pilgrim00a352e2009-05-29 04:04:44 +0000506 (response, content) = self.http.request(uri, "GET", headers = {'cache-control': 'max-age=0', 'if-none-match': 'fred'})
jcgregorio4b145e82007-01-18 19:46:34 +0000507 d = self.reflector(content)
508 self.assertTrue(d.has_key('HTTP_IF_NONE_MATCH'))
509 self.assertEqual(d['HTTP_IF_NONE_MATCH'], "fred")
jcgregorio25185622006-10-28 05:12:34 +0000510
pilgrim00a352e2009-05-29 04:04:44 +0000511#MAP-commented this out because it consistently fails
512# def testGet304EndToEnd(self):
513# # Test that end to end headers get overwritten in the cache
514# uri = urlparse.urljoin(base, "304/end2end.cgi")
515# (response, content) = self.http.request(uri, "GET")
516# self.assertNotEqual(response['etag'], "")
517# old_date = response['date']
518# time.sleep(2)
519#
520# (response, content) = self.http.request(uri, "GET", headers = {'Cache-Control': 'max-age=0'})
521# # The response should be from the cache, but the Date: header should be updated.
522# new_date = response['date']
523# self.assertNotEqual(new_date, old_date)
524# self.assertEqual(response.status, 200)
525# self.assertEqual(response.fromcache, True)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000526
527 def testGet304LastModified(self):
528 # Test that we can still handle a 304
529 # by only using the last-modified cache validator.
530 uri = urlparse.urljoin(base, "304/last-modified-only/last-modified-only.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000531 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000532
533 self.assertNotEqual(response['last-modified'], "")
jcgregorio36140b52006-06-13 02:17:52 +0000534 (response, content) = self.http.request(uri, "GET")
535 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000536 self.assertEqual(response.status, 200)
537 self.assertEqual(response.fromcache, True)
538
539 def testGet307(self):
540 # Test that we do follow 307 redirects but
541 # do not cache the 307
542 uri = urlparse.urljoin(base, "307/onestep.asis")
jcgregorio36140b52006-06-13 02:17:52 +0000543 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000544 self.assertEqual(response.status, 200)
545 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000546 self.assertEqual(response.previous.status, 307)
547 self.assertEqual(response.previous.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000548
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, 200)
551 self.assertEqual(response.fromcache, True)
552 self.assertEqual(content, "This is the final destination.\n")
jcgregorioa0713ab2006-07-01 05:21:34 +0000553 self.assertEqual(response.previous.status, 307)
554 self.assertEqual(response.previous.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000555
556 def testGet410(self):
557 # Test that we pass 410's through
558 uri = urlparse.urljoin(base, "410/410.asis")
jcgregorio36140b52006-06-13 02:17:52 +0000559 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000560 self.assertEqual(response.status, 410)
561
joe.gregorio0d4a2b82007-10-23 14:28:35 +0000562 def testHeadGZip(self):
563 # Test that we don't try to decompress a HEAD response
564 uri = urlparse.urljoin(base, "gzip/final-destination.txt")
565 (response, content) = self.http.request(uri, "HEAD")
566 self.assertEqual(response.status, 200)
567 self.assertNotEqual(int(response['content-length']), 0)
568 self.assertEqual(content, "")
569
jcgregorio2d66d4f2006-02-07 05:34:14 +0000570 def testGetGZip(self):
571 # Test that we support gzip compression
572 uri = urlparse.urljoin(base, "gzip/final-destination.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000573 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000574 self.assertEqual(response.status, 200)
jcgregorio90fb4a42006-11-17 16:19:47 +0000575 self.assertFalse(response.has_key('content-encoding'))
joe.gregorio8b6d2312007-12-16 05:42:07 +0000576 self.assertTrue(response.has_key('-content-encoding'))
jcgregorio153f5882006-11-06 03:33:24 +0000577 self.assertEqual(int(response['content-length']), len("This is the final destination.\n"))
jcgregorio2d66d4f2006-02-07 05:34:14 +0000578 self.assertEqual(content, "This is the final destination.\n")
579
580 def testGetGZipFailure(self):
581 # Test that we raise a good exception when the gzip fails
jcgregorio07a9a4a2007-03-08 21:18:39 +0000582 self.http.force_exception_to_status_code = False
jcgregorio2d66d4f2006-02-07 05:34:14 +0000583 uri = urlparse.urljoin(base, "gzip/failed-compression.asis")
584 try:
jcgregorio36140b52006-06-13 02:17:52 +0000585 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000586 self.fail("Should never reach here")
587 except httplib2.FailedToDecompressContent:
588 pass
589 except Exception:
590 self.fail("Threw wrong kind of exception")
591
jcgregorio07a9a4a2007-03-08 21:18:39 +0000592 # Re-run the test with out the exceptions
593 self.http.force_exception_to_status_code = True
594
595 (response, content) = self.http.request(uri, "GET")
596 self.assertEqual(response.status, 500)
597 self.assertTrue(response.reason.startswith("Content purported"))
598
599 def testTimeout(self):
jcgregoriob2697912007-03-09 02:23:47 +0000600 self.http.force_exception_to_status_code = True
jcgregorio07a9a4a2007-03-08 21:18:39 +0000601 uri = urlparse.urljoin(base, "timeout/timeout.cgi")
602 try:
603 import socket
604 socket.setdefaulttimeout(1)
605 except:
606 # Don't run the test if we can't set the timeout
607 return
608 (response, content) = self.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
jcgregoriob2697912007-03-09 02:23:47 +0000613 def testIndividualTimeout(self):
jcgregoriob2697912007-03-09 02:23:47 +0000614 uri = urlparse.urljoin(base, "timeout/timeout.cgi")
615 http = httplib2.Http(timeout=1)
joe.gregoriof28536d2007-10-23 14:10:11 +0000616 http.force_exception_to_status_code = True
jcgregoriob2697912007-03-09 02:23:47 +0000617
618 (response, content) = http.request(uri)
619 self.assertEqual(response.status, 408)
620 self.assertTrue(response.reason.startswith("Request Timeout"))
621 self.assertTrue(content.startswith("Request Timeout"))
622
jcgregorio07a9a4a2007-03-08 21:18:39 +0000623
Joe Gregorio1a7609f2009-07-16 10:59:44 -0400624 def testHTTPSInitTimeout(self):
625 c = httplib2.HTTPSConnectionWithTimeout('localhost', 80, timeout=47)
626 self.assertEqual(47, c.timeout)
627
jcgregorio2d66d4f2006-02-07 05:34:14 +0000628 def testGetDeflate(self):
629 # Test that we support deflate compression
630 uri = urlparse.urljoin(base, "deflate/deflated.asis")
jcgregorio36140b52006-06-13 02:17:52 +0000631 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000632 self.assertEqual(response.status, 200)
jcgregorio90fb4a42006-11-17 16:19:47 +0000633 self.assertFalse(response.has_key('content-encoding'))
jcgregorio153f5882006-11-06 03:33:24 +0000634 self.assertEqual(int(response['content-length']), len("This is the final destination."))
jcgregorio2d66d4f2006-02-07 05:34:14 +0000635 self.assertEqual(content, "This is the final destination.")
636
637 def testGetDeflateFailure(self):
638 # Test that we raise a good exception when the deflate fails
jcgregorio07a9a4a2007-03-08 21:18:39 +0000639 self.http.force_exception_to_status_code = False
640
jcgregorio2d66d4f2006-02-07 05:34:14 +0000641 uri = urlparse.urljoin(base, "deflate/failed-compression.asis")
642 try:
jcgregorio36140b52006-06-13 02:17:52 +0000643 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000644 self.fail("Should never reach here")
645 except httplib2.FailedToDecompressContent:
646 pass
647 except Exception:
648 self.fail("Threw wrong kind of exception")
649
jcgregorio07a9a4a2007-03-08 21:18:39 +0000650 # Re-run the test with out the exceptions
651 self.http.force_exception_to_status_code = True
652
653 (response, content) = self.http.request(uri, "GET")
654 self.assertEqual(response.status, 500)
655 self.assertTrue(response.reason.startswith("Content purported"))
656
jcgregorio2d66d4f2006-02-07 05:34:14 +0000657 def testGetDuplicateHeaders(self):
658 # Test that duplicate headers get concatenated via ','
659 uri = urlparse.urljoin(base, "duplicate-headers/multilink.asis")
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(content, "This is content\n")
663 self.assertEqual(response['link'].split(",")[0], '<http://bitworking.org>; rel="home"; title="BitWorking"')
664
665 def testGetCacheControlNoCache(self):
666 # Test Cache-Control: no-cache on requests
667 uri = urlparse.urljoin(base, "304/test_etag.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000668 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000669 self.assertNotEqual(response['etag'], "")
jcgregorio36140b52006-06-13 02:17:52 +0000670 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000671 self.assertEqual(response.status, 200)
672 self.assertEqual(response.fromcache, True)
673
jcgregorio36140b52006-06-13 02:17:52 +0000674 (response, content) = self.http.request(uri, "GET", headers={'Cache-Control': 'no-cache'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000675 self.assertEqual(response.status, 200)
676 self.assertEqual(response.fromcache, False)
677
678 def testGetCacheControlPragmaNoCache(self):
679 # Test Pragma: no-cache on requests
680 uri = urlparse.urljoin(base, "304/test_etag.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000681 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000682 self.assertNotEqual(response['etag'], "")
jcgregorio36140b52006-06-13 02:17:52 +0000683 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000684 self.assertEqual(response.status, 200)
685 self.assertEqual(response.fromcache, True)
686
jcgregorio36140b52006-06-13 02:17:52 +0000687 (response, content) = self.http.request(uri, "GET", headers={'Pragma': 'no-cache'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000688 self.assertEqual(response.status, 200)
689 self.assertEqual(response.fromcache, False)
690
691 def testGetCacheControlNoStoreRequest(self):
692 # A no-store request means that the response should not be stored.
693 uri = urlparse.urljoin(base, "304/test_etag.txt")
694
jcgregorio36140b52006-06-13 02:17:52 +0000695 (response, content) = self.http.request(uri, "GET", headers={'Cache-Control': 'no-store'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000696 self.assertEqual(response.status, 200)
697 self.assertEqual(response.fromcache, False)
698
jcgregorio36140b52006-06-13 02:17:52 +0000699 (response, content) = self.http.request(uri, "GET", headers={'Cache-Control': 'no-store'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000700 self.assertEqual(response.status, 200)
701 self.assertEqual(response.fromcache, False)
702
703 def testGetCacheControlNoStoreResponse(self):
704 # A no-store response means that the response should not be stored.
705 uri = urlparse.urljoin(base, "no-store/no-store.asis")
706
jcgregorio36140b52006-06-13 02:17:52 +0000707 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000708 self.assertEqual(response.status, 200)
709 self.assertEqual(response.fromcache, False)
710
jcgregorio36140b52006-06-13 02:17:52 +0000711 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000712 self.assertEqual(response.status, 200)
713 self.assertEqual(response.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000714
715 def testGetCacheControlNoCacheNoStoreRequest(self):
716 # Test that a no-store, no-cache clears the entry from the cache
717 # even if it was cached previously.
718 uri = urlparse.urljoin(base, "304/test_etag.txt")
719
jcgregorio36140b52006-06-13 02:17:52 +0000720 (response, content) = self.http.request(uri, "GET")
721 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000722 self.assertEqual(response.fromcache, True)
jcgregorio36140b52006-06-13 02:17:52 +0000723 (response, content) = self.http.request(uri, "GET", headers={'Cache-Control': 'no-store, no-cache'})
724 (response, content) = self.http.request(uri, "GET", headers={'Cache-Control': 'no-store, no-cache'})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000725 self.assertEqual(response.status, 200)
726 self.assertEqual(response.fromcache, False)
jcgregorio2d66d4f2006-02-07 05:34:14 +0000727
728 def testUpdateInvalidatesCache(self):
729 # Test that calling PUT or DELETE on a
730 # URI that is cache invalidates that cache.
731 uri = urlparse.urljoin(base, "304/test_etag.txt")
732
jcgregorio36140b52006-06-13 02:17:52 +0000733 (response, content) = self.http.request(uri, "GET")
734 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000735 self.assertEqual(response.fromcache, True)
jcgregorio36140b52006-06-13 02:17:52 +0000736 (response, content) = self.http.request(uri, "DELETE")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000737 self.assertEqual(response.status, 405)
738
jcgregorio36140b52006-06-13 02:17:52 +0000739 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000740 self.assertEqual(response.fromcache, False)
741
742 def testUpdateUsesCachedETag(self):
743 # Test that we natively support http://www.w3.org/1999/04/Editing/
744 uri = urlparse.urljoin(base, "conditional-updates/test.cgi")
745
jcgregorio36140b52006-06-13 02:17:52 +0000746 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000747 self.assertEqual(response.status, 200)
748 self.assertEqual(response.fromcache, False)
jcgregorio36140b52006-06-13 02:17:52 +0000749 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000750 self.assertEqual(response.status, 200)
751 self.assertEqual(response.fromcache, True)
jcgregorio36140b52006-06-13 02:17:52 +0000752 (response, content) = self.http.request(uri, "PUT")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000753 self.assertEqual(response.status, 200)
jcgregorio36140b52006-06-13 02:17:52 +0000754 (response, content) = self.http.request(uri, "PUT")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000755 self.assertEqual(response.status, 412)
756
joe.gregorio700f04d2008-09-06 04:46:32 +0000757 def testUpdateUsesCachedETagAndOCMethod(self):
758 # Test that we natively support http://www.w3.org/1999/04/Editing/
759 uri = urlparse.urljoin(base, "conditional-updates/test.cgi")
760
761 (response, content) = self.http.request(uri, "GET")
762 self.assertEqual(response.status, 200)
763 self.assertEqual(response.fromcache, False)
764 (response, content) = self.http.request(uri, "GET")
765 self.assertEqual(response.status, 200)
766 self.assertEqual(response.fromcache, True)
767 self.http.optimistic_concurrency_methods.append("DELETE")
768 (response, content) = self.http.request(uri, "DELETE")
769 self.assertEqual(response.status, 200)
770
771
jcgregorio4b145e82007-01-18 19:46:34 +0000772 def testUpdateUsesCachedETagOverridden(self):
773 # Test that we natively support http://www.w3.org/1999/04/Editing/
774 uri = urlparse.urljoin(base, "conditional-updates/test.cgi")
775
776 (response, content) = self.http.request(uri, "GET")
777 self.assertEqual(response.status, 200)
778 self.assertEqual(response.fromcache, False)
779 (response, content) = self.http.request(uri, "GET")
780 self.assertEqual(response.status, 200)
781 self.assertEqual(response.fromcache, True)
782 (response, content) = self.http.request(uri, "PUT", headers={'if-match': 'fred'})
783 self.assertEqual(response.status, 412)
784
jcgregorio2d66d4f2006-02-07 05:34:14 +0000785 def testBasicAuth(self):
786 # Test Basic Authentication
787 uri = urlparse.urljoin(base, "basic/file.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000788 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000789 self.assertEqual(response.status, 401)
790
791 uri = urlparse.urljoin(base, "basic/")
jcgregorio36140b52006-06-13 02:17:52 +0000792 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000793 self.assertEqual(response.status, 401)
794
jcgregorio36140b52006-06-13 02:17:52 +0000795 self.http.add_credentials('joe', 'password')
796 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000797 self.assertEqual(response.status, 200)
798
799 uri = urlparse.urljoin(base, "basic/file.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000800 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000801 self.assertEqual(response.status, 200)
802
jcgregoriode8238d2007-03-07 19:08:26 +0000803 def testBasicAuthWithDomain(self):
804 # Test Basic Authentication
805 uri = urlparse.urljoin(base, "basic/file.txt")
806 (response, content) = self.http.request(uri, "GET")
807 self.assertEqual(response.status, 401)
808
809 uri = urlparse.urljoin(base, "basic/")
810 (response, content) = self.http.request(uri, "GET")
811 self.assertEqual(response.status, 401)
812
813 self.http.add_credentials('joe', 'password', "example.org")
814 (response, content) = self.http.request(uri, "GET")
815 self.assertEqual(response.status, 401)
816
817 uri = urlparse.urljoin(base, "basic/file.txt")
818 (response, content) = self.http.request(uri, "GET")
819 self.assertEqual(response.status, 401)
820
821 domain = urlparse.urlparse(base)[1]
822 self.http.add_credentials('joe', 'password', domain)
823 (response, content) = self.http.request(uri, "GET")
824 self.assertEqual(response.status, 200)
825
826 uri = urlparse.urljoin(base, "basic/file.txt")
827 (response, content) = self.http.request(uri, "GET")
828 self.assertEqual(response.status, 200)
829
830
831
832
833
834
jcgregorio2d66d4f2006-02-07 05:34:14 +0000835 def testBasicAuthTwoDifferentCredentials(self):
jcgregorioadbb4f82006-05-19 15:17:42 +0000836 # Test Basic Authentication with multiple sets of credentials
jcgregorio2d66d4f2006-02-07 05:34:14 +0000837 uri = urlparse.urljoin(base, "basic2/file.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000838 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000839 self.assertEqual(response.status, 401)
840
841 uri = urlparse.urljoin(base, "basic2/")
jcgregorio36140b52006-06-13 02:17:52 +0000842 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000843 self.assertEqual(response.status, 401)
844
jcgregorio36140b52006-06-13 02:17:52 +0000845 self.http.add_credentials('fred', 'barney')
846 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000847 self.assertEqual(response.status, 200)
848
849 uri = urlparse.urljoin(base, "basic2/file.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000850 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000851 self.assertEqual(response.status, 200)
852
853 def testBasicAuthNested(self):
854 # Test Basic Authentication with resources
855 # that are nested
856 uri = urlparse.urljoin(base, "basic-nested/")
jcgregorio36140b52006-06-13 02:17:52 +0000857 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000858 self.assertEqual(response.status, 401)
859
860 uri = urlparse.urljoin(base, "basic-nested/subdir")
jcgregorio36140b52006-06-13 02:17:52 +0000861 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000862 self.assertEqual(response.status, 401)
863
jcgregorioadbb4f82006-05-19 15:17:42 +0000864 # Now add in credentials one at a time and test.
jcgregorio36140b52006-06-13 02:17:52 +0000865 self.http.add_credentials('joe', 'password')
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, 401)
874
jcgregorio36140b52006-06-13 02:17:52 +0000875 self.http.add_credentials('fred', 'barney')
jcgregorio2d66d4f2006-02-07 05:34:14 +0000876
877 uri = urlparse.urljoin(base, "basic-nested/")
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, 200)
880
881 uri = urlparse.urljoin(base, "basic-nested/subdir")
jcgregorio36140b52006-06-13 02:17:52 +0000882 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000883 self.assertEqual(response.status, 200)
884
885 def testDigestAuth(self):
886 # Test that we support Digest Authentication
887 uri = urlparse.urljoin(base, "digest/")
jcgregorio36140b52006-06-13 02:17:52 +0000888 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000889 self.assertEqual(response.status, 401)
890
jcgregorio36140b52006-06-13 02:17:52 +0000891 self.http.add_credentials('joe', 'password')
892 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000893 self.assertEqual(response.status, 200)
894
895 uri = urlparse.urljoin(base, "digest/file.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000896 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000897
898 def testDigestAuthNextNonceAndNC(self):
899 # Test that if the server sets nextnonce that we reset
900 # the nonce count back to 1
901 uri = urlparse.urljoin(base, "digest/file.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000902 self.http.add_credentials('joe', 'password')
903 (response, content) = self.http.request(uri, "GET", headers = {"cache-control":"no-cache"})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000904 info = httplib2._parse_www_authenticate(response, 'authentication-info')
905 self.assertEqual(response.status, 200)
jcgregorio36140b52006-06-13 02:17:52 +0000906 (response, content) = self.http.request(uri, "GET", headers = {"cache-control":"no-cache"})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000907 info2 = httplib2._parse_www_authenticate(response, 'authentication-info')
908 self.assertEqual(response.status, 200)
909
910 if info.has_key('nextnonce'):
911 self.assertEqual(info2['nc'], 1)
912
913 def testDigestAuthStale(self):
914 # Test that we can handle a nonce becoming stale
915 uri = urlparse.urljoin(base, "digest-expire/file.txt")
jcgregorio36140b52006-06-13 02:17:52 +0000916 self.http.add_credentials('joe', 'password')
917 (response, content) = self.http.request(uri, "GET", headers = {"cache-control":"no-cache"})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000918 info = httplib2._parse_www_authenticate(response, 'authentication-info')
919 self.assertEqual(response.status, 200)
920
921 time.sleep(3)
922 # Sleep long enough that the nonce becomes stale
923
jcgregorio36140b52006-06-13 02:17:52 +0000924 (response, content) = self.http.request(uri, "GET", headers = {"cache-control":"no-cache"})
jcgregorio2d66d4f2006-02-07 05:34:14 +0000925 self.assertFalse(response.fromcache)
926 self.assertTrue(response._stale_digest)
927 info3 = httplib2._parse_www_authenticate(response, 'authentication-info')
928 self.assertEqual(response.status, 200)
929
930 def reflector(self, content):
jcgregorio25185622006-10-28 05:12:34 +0000931 return dict( [tuple(x.split("=", 1)) for x in content.strip().split("\n")] )
jcgregorio2d66d4f2006-02-07 05:34:14 +0000932
933 def testReflector(self):
934 uri = urlparse.urljoin(base, "reflector/reflector.cgi")
jcgregorio36140b52006-06-13 02:17:52 +0000935 (response, content) = self.http.request(uri, "GET")
jcgregorio2d66d4f2006-02-07 05:34:14 +0000936 d = self.reflector(content)
937 self.assertTrue(d.has_key('HTTP_USER_AGENT'))
938
jcgregorio36140b52006-06-13 02:17:52 +0000939try:
940 import memcache
941 class HttpTestMemCached(HttpTest):
942 def setUp(self):
943 self.cache = memcache.Client(['127.0.0.1:11211'], debug=0)
jcgregorio47d24672006-06-29 05:18:59 +0000944 #self.cache = memcache.Client(['10.0.0.4:11211'], debug=1)
jcgregorio36140b52006-06-13 02:17:52 +0000945 self.http = httplib2.Http(self.cache)
946 self.cache.flush_all()
jcgregorio47d24672006-06-29 05:18:59 +0000947 # Not exactly sure why the sleep is needed here, but
948 # if not present then some unit tests that rely on caching
949 # fail. Memcached seems to lose some sets immediately
950 # after a flush_all if the set is to a value that
951 # was previously cached. (Maybe the flush is handled async?)
952 time.sleep(1)
jcgregorio36140b52006-06-13 02:17:52 +0000953 self.http.clear_credentials()
954except:
955 pass
956
957
958
jcgregoriodb8dfc82006-03-31 14:59:46 +0000959# ------------------------------------------------------------------------
jcgregorio2d66d4f2006-02-07 05:34:14 +0000960
961class HttpPrivateTest(unittest.TestCase):
962
963 def testParseCacheControl(self):
964 # Test that we can parse the Cache-Control header
965 self.assertEqual({}, httplib2._parse_cache_control({}))
966 self.assertEqual({'no-cache': 1}, httplib2._parse_cache_control({'cache-control': ' no-cache'}))
967 cc = httplib2._parse_cache_control({'cache-control': ' no-cache, max-age = 7200'})
968 self.assertEqual(cc['no-cache'], 1)
969 self.assertEqual(cc['max-age'], '7200')
970 cc = httplib2._parse_cache_control({'cache-control': ' , '})
971 self.assertEqual(cc[''], 1)
972
973 def testNormalizeHeaders(self):
974 # Test that we normalize headers to lowercase
975 h = httplib2._normalize_headers({'Cache-Control': 'no-cache', 'Other': 'Stuff'})
976 self.assertTrue(h.has_key('cache-control'))
977 self.assertTrue(h.has_key('other'))
978 self.assertEqual('Stuff', h['other'])
979
980 def testExpirationModelTransparent(self):
981 # Test that no-cache makes our request TRANSPARENT
982 response_headers = {
983 'cache-control': 'max-age=7200'
984 }
985 request_headers = {
986 'cache-control': 'no-cache'
987 }
988 self.assertEqual("TRANSPARENT", httplib2._entry_disposition(response_headers, request_headers))
989
jcgregorio45865012007-01-18 16:38:22 +0000990 def testMaxAgeNonNumeric(self):
991 # Test that no-cache makes our request TRANSPARENT
992 response_headers = {
993 'cache-control': 'max-age=fred, min-fresh=barney'
994 }
995 request_headers = {
996 }
997 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
998
999
jcgregorio2d66d4f2006-02-07 05:34:14 +00001000 def testExpirationModelNoCacheResponse(self):
1001 # The date and expires point to an entry that should be
1002 # FRESH, but the no-cache over-rides that.
1003 now = time.time()
1004 response_headers = {
1005 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now)),
1006 'expires': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now+4)),
1007 'cache-control': 'no-cache'
1008 }
1009 request_headers = {
1010 }
1011 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1012
1013 def testExpirationModelStaleRequestMustReval(self):
1014 # must-revalidate forces STALE
1015 self.assertEqual("STALE", httplib2._entry_disposition({}, {'cache-control': 'must-revalidate'}))
1016
1017 def testExpirationModelStaleResponseMustReval(self):
1018 # must-revalidate forces STALE
1019 self.assertEqual("STALE", httplib2._entry_disposition({'cache-control': 'must-revalidate'}, {}))
1020
1021 def testExpirationModelFresh(self):
1022 response_headers = {
1023 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime()),
1024 'cache-control': 'max-age=2'
1025 }
1026 request_headers = {
1027 }
1028 self.assertEqual("FRESH", httplib2._entry_disposition(response_headers, request_headers))
1029 time.sleep(3)
1030 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1031
1032 def testExpirationMaxAge0(self):
1033 response_headers = {
1034 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime()),
1035 'cache-control': 'max-age=0'
1036 }
1037 request_headers = {
1038 }
1039 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1040
1041 def testExpirationModelDateAndExpires(self):
1042 now = time.time()
1043 response_headers = {
1044 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now)),
1045 'expires': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now+2)),
1046 }
1047 request_headers = {
1048 }
1049 self.assertEqual("FRESH", httplib2._entry_disposition(response_headers, request_headers))
1050 time.sleep(3)
1051 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1052
jcgregoriof9511052007-06-01 14:56:34 +00001053 def testExpiresZero(self):
1054 now = time.time()
1055 response_headers = {
1056 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now)),
1057 'expires': "0",
1058 }
1059 request_headers = {
1060 }
1061 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1062
jcgregorio2d66d4f2006-02-07 05:34:14 +00001063 def testExpirationModelDateOnly(self):
1064 now = time.time()
1065 response_headers = {
1066 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now+3)),
1067 }
1068 request_headers = {
1069 }
1070 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1071
1072 def testExpirationModelOnlyIfCached(self):
1073 response_headers = {
1074 }
1075 request_headers = {
1076 'cache-control': 'only-if-cached',
1077 }
1078 self.assertEqual("FRESH", httplib2._entry_disposition(response_headers, request_headers))
1079
1080 def testExpirationModelMaxAgeBoth(self):
1081 now = time.time()
1082 response_headers = {
1083 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now)),
1084 'cache-control': 'max-age=2'
1085 }
1086 request_headers = {
1087 'cache-control': 'max-age=0'
1088 }
1089 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1090
1091 def testExpirationModelDateAndExpiresMinFresh1(self):
1092 now = time.time()
1093 response_headers = {
1094 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now)),
1095 'expires': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now+2)),
1096 }
1097 request_headers = {
1098 'cache-control': 'min-fresh=2'
1099 }
1100 self.assertEqual("STALE", httplib2._entry_disposition(response_headers, request_headers))
1101
1102 def testExpirationModelDateAndExpiresMinFresh2(self):
1103 now = time.time()
1104 response_headers = {
1105 'date': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now)),
1106 'expires': time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now+4)),
1107 }
1108 request_headers = {
1109 'cache-control': 'min-fresh=2'
1110 }
1111 self.assertEqual("FRESH", httplib2._entry_disposition(response_headers, request_headers))
1112
1113 def testParseWWWAuthenticateEmpty(self):
1114 res = httplib2._parse_www_authenticate({})
1115 self.assertEqual(len(res.keys()), 0)
1116
jcgregoriofd22e432006-04-27 02:00:08 +00001117 def testParseWWWAuthenticate(self):
1118 # different uses of spaces around commas
1119 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'Test realm="test realm" , foo=foo ,bar="bar", baz=baz,qux=qux'})
1120 self.assertEqual(len(res.keys()), 1)
1121 self.assertEqual(len(res['test'].keys()), 5)
1122
1123 # tokens with non-alphanum
1124 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'T*!%#st realm=to*!%#en, to*!%#en="quoted string"'})
1125 self.assertEqual(len(res.keys()), 1)
1126 self.assertEqual(len(res['t*!%#st'].keys()), 2)
1127
1128 # quoted string with quoted pairs
1129 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'Test realm="a \\"test\\" realm"'})
1130 self.assertEqual(len(res.keys()), 1)
1131 self.assertEqual(res['test']['realm'], 'a "test" realm')
1132
1133 def testParseWWWAuthenticateStrict(self):
1134 httplib2.USE_WWW_AUTH_STRICT_PARSING = 1;
1135 self.testParseWWWAuthenticate();
1136 httplib2.USE_WWW_AUTH_STRICT_PARSING = 0;
1137
jcgregorio2d66d4f2006-02-07 05:34:14 +00001138 def testParseWWWAuthenticateBasic(self):
1139 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'Basic realm="me"'})
1140 basic = res['basic']
1141 self.assertEqual('me', basic['realm'])
1142
1143 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'Basic realm="me", algorithm="MD5"'})
1144 basic = res['basic']
1145 self.assertEqual('me', basic['realm'])
1146 self.assertEqual('MD5', basic['algorithm'])
1147
1148 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'Basic realm="me", algorithm=MD5'})
1149 basic = res['basic']
1150 self.assertEqual('me', basic['realm'])
1151 self.assertEqual('MD5', basic['algorithm'])
1152
1153 def testParseWWWAuthenticateBasic2(self):
1154 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'Basic realm="me",other="fred" '})
1155 basic = res['basic']
1156 self.assertEqual('me', basic['realm'])
1157 self.assertEqual('fred', basic['other'])
1158
1159 def testParseWWWAuthenticateBasic3(self):
1160 res = httplib2._parse_www_authenticate({ 'www-authenticate': 'Basic REAlm="me" '})
1161 basic = res['basic']
1162 self.assertEqual('me', basic['realm'])
1163
1164
1165 def testParseWWWAuthenticateDigest(self):
1166 res = httplib2._parse_www_authenticate({ 'www-authenticate':
1167 'Digest realm="testrealm@host.com", qop="auth,auth-int", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41"'})
1168 digest = res['digest']
1169 self.assertEqual('testrealm@host.com', digest['realm'])
1170 self.assertEqual('auth,auth-int', digest['qop'])
1171
1172
1173 def testParseWWWAuthenticateMultiple(self):
1174 res = httplib2._parse_www_authenticate({ 'www-authenticate':
1175 'Digest realm="testrealm@host.com", qop="auth,auth-int", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41" Basic REAlm="me" '})
1176 digest = res['digest']
1177 self.assertEqual('testrealm@host.com', digest['realm'])
1178 self.assertEqual('auth,auth-int', digest['qop'])
1179 self.assertEqual('dcd98b7102dd2f0e8b11d0f600bfb0c093', digest['nonce'])
1180 self.assertEqual('5ccc069c403ebaf9f0171e9517f40e41', digest['opaque'])
1181 basic = res['basic']
1182 self.assertEqual('me', basic['realm'])
1183
1184 def testParseWWWAuthenticateMultiple2(self):
1185 # Handle an added comma between challenges, which might get thrown in if the challenges were
1186 # originally sent in separate www-authenticate headers.
1187 res = httplib2._parse_www_authenticate({ 'www-authenticate':
1188 'Digest realm="testrealm@host.com", qop="auth,auth-int", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41", Basic REAlm="me" '})
1189 digest = res['digest']
1190 self.assertEqual('testrealm@host.com', digest['realm'])
1191 self.assertEqual('auth,auth-int', digest['qop'])
1192 self.assertEqual('dcd98b7102dd2f0e8b11d0f600bfb0c093', digest['nonce'])
1193 self.assertEqual('5ccc069c403ebaf9f0171e9517f40e41', digest['opaque'])
1194 basic = res['basic']
1195 self.assertEqual('me', basic['realm'])
1196
1197 def testParseWWWAuthenticateMultiple3(self):
1198 # Handle an added comma between challenges, which might get thrown in if the challenges were
1199 # originally sent in separate www-authenticate headers.
1200 res = httplib2._parse_www_authenticate({ 'www-authenticate':
1201 'Digest realm="testrealm@host.com", qop="auth,auth-int", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41", Basic REAlm="me", WSSE realm="foo", profile="UsernameToken"'})
1202 digest = res['digest']
1203 self.assertEqual('testrealm@host.com', digest['realm'])
1204 self.assertEqual('auth,auth-int', digest['qop'])
1205 self.assertEqual('dcd98b7102dd2f0e8b11d0f600bfb0c093', digest['nonce'])
1206 self.assertEqual('5ccc069c403ebaf9f0171e9517f40e41', digest['opaque'])
1207 basic = res['basic']
1208 self.assertEqual('me', basic['realm'])
1209 wsse = res['wsse']
1210 self.assertEqual('foo', wsse['realm'])
1211 self.assertEqual('UsernameToken', wsse['profile'])
1212
1213 def testParseWWWAuthenticateMultiple4(self):
1214 res = httplib2._parse_www_authenticate({ 'www-authenticate':
1215 'Digest realm="test-real.m@host.com", qop \t=\t"\tauth,auth-int", nonce="(*)&^&$%#",opaque="5ccc069c403ebaf9f0171e9517f40e41", Basic REAlm="me", WSSE realm="foo", profile="UsernameToken"'})
1216 digest = res['digest']
1217 self.assertEqual('test-real.m@host.com', digest['realm'])
1218 self.assertEqual('\tauth,auth-int', digest['qop'])
1219 self.assertEqual('(*)&^&$%#', digest['nonce'])
1220
1221 def testParseWWWAuthenticateMoreQuoteCombos(self):
1222 res = httplib2._parse_www_authenticate({'www-authenticate':'Digest realm="myrealm", nonce="Ygk86AsKBAA=3516200d37f9a3230352fde99977bd6d472d4306", algorithm=MD5, qop="auth", stale=true'})
1223 digest = res['digest']
1224 self.assertEqual('myrealm', digest['realm'])
1225
1226 def testDigestObject(self):
1227 credentials = ('joe', 'password')
1228 host = None
1229 request_uri = '/projects/httplib2/test/digest/'
1230 headers = {}
1231 response = {
1232 'www-authenticate': 'Digest realm="myrealm", nonce="Ygk86AsKBAA=3516200d37f9a3230352fde99977bd6d472d4306", algorithm=MD5, qop="auth"'
1233 }
1234 content = ""
1235
jcgregorio6cbab7e2006-04-21 20:35:43 +00001236 d = httplib2.DigestAuthentication(credentials, host, request_uri, headers, response, content, None)
jcgregorio2d66d4f2006-02-07 05:34:14 +00001237 d.request("GET", request_uri, headers, content, cnonce="33033375ec278a46")
1238 our_request = "Authorization: %s" % headers['Authorization']
1239 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"'
1240 self.assertEqual(our_request, working_request)
1241
1242
1243 def testDigestObjectStale(self):
1244 credentials = ('joe', 'password')
1245 host = None
1246 request_uri = '/projects/httplib2/test/digest/'
1247 headers = {}
1248 response = httplib2.Response({ })
1249 response['www-authenticate'] = 'Digest realm="myrealm", nonce="Ygk86AsKBAA=3516200d37f9a3230352fde99977bd6d472d4306", algorithm=MD5, qop="auth", stale=true'
1250 response.status = 401
1251 content = ""
jcgregorio6cbab7e2006-04-21 20:35:43 +00001252 d = httplib2.DigestAuthentication(credentials, host, request_uri, headers, response, content, None)
jcgregorio2d66d4f2006-02-07 05:34:14 +00001253 # Returns true to force a retry
1254 self.assertTrue( d.response(response, content) )
1255
1256 def testDigestObjectAuthInfo(self):
1257 credentials = ('joe', 'password')
1258 host = None
1259 request_uri = '/projects/httplib2/test/digest/'
1260 headers = {}
1261 response = httplib2.Response({ })
1262 response['www-authenticate'] = 'Digest realm="myrealm", nonce="Ygk86AsKBAA=3516200d37f9a3230352fde99977bd6d472d4306", algorithm=MD5, qop="auth", stale=true'
1263 response['authentication-info'] = 'nextnonce="fred"'
1264 content = ""
jcgregorio6cbab7e2006-04-21 20:35:43 +00001265 d = httplib2.DigestAuthentication(credentials, host, request_uri, headers, response, content, None)
jcgregorio2d66d4f2006-02-07 05:34:14 +00001266 # Returns true to force a retry
1267 self.assertFalse( d.response(response, content) )
1268 self.assertEqual('fred', d.challenge['nonce'])
1269 self.assertEqual(1, d.challenge['nc'])
1270
1271 def testWsseAlgorithm(self):
1272 digest = httplib2._wsse_username_token("d36e316282959a9ed4c89851497a717f", "2003-12-15T14:43:07Z", "taadtaadpstcsm")
1273 expected = "quR/EWLAV4xLf9Zqyw4pDmfV9OY="
1274 self.assertEqual(expected, digest)
1275
jcgregoriodb8dfc82006-03-31 14:59:46 +00001276 def testEnd2End(self):
1277 # one end to end header
1278 response = {'content-type': 'application/atom+xml', 'te': 'deflate'}
1279 end2end = httplib2._get_end2end_headers(response)
1280 self.assertTrue('content-type' in end2end)
1281 self.assertTrue('te' not in end2end)
1282 self.assertTrue('connection' not in end2end)
1283
1284 # one end to end header that gets eliminated
1285 response = {'connection': 'content-type', 'content-type': 'application/atom+xml', 'te': 'deflate'}
1286 end2end = httplib2._get_end2end_headers(response)
1287 self.assertTrue('content-type' not in end2end)
1288 self.assertTrue('te' not in end2end)
1289 self.assertTrue('connection' not in end2end)
1290
1291 # Degenerate case of no headers
1292 response = {}
1293 end2end = httplib2._get_end2end_headers(response)
1294 self.assertEquals(0, len(end2end))
1295
1296 # Degenerate case of connection referrring to a header not passed in
1297 response = {'connection': 'content-type'}
1298 end2end = httplib2._get_end2end_headers(response)
1299 self.assertEquals(0, len(end2end))
jcgregorio2d66d4f2006-02-07 05:34:14 +00001300
1301unittest.main()