Joe Gregorio | 20a5aa9 | 2011-04-01 17:44:25 -0400 | [diff] [blame] | 1 | # Copyright (C) 2010 Google Inc. |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 14 | |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 15 | """Classes to encapsulate a single HTTP request. |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 16 | |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 17 | The classes implement a command pattern, with every |
| 18 | object supporting an execute() method that does the |
| 19 | actuall HTTP request. |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 20 | """ |
| 21 | |
| 22 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 23 | __all__ = [ |
Joe Gregorio | cb8103d | 2011-02-11 23:20:52 -0500 | [diff] [blame] | 24 | 'HttpRequest', 'RequestMockBuilder', 'HttpMock' |
Joe Gregorio | f415342 | 2011-03-18 22:45:18 -0400 | [diff] [blame] | 25 | 'set_user_agent', 'tunnel_patch' |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 26 | ] |
| 27 | |
Joe Gregorio | c672246 | 2010-12-20 14:29:28 -0500 | [diff] [blame] | 28 | import httplib2 |
Joe Gregorio | cb8103d | 2011-02-11 23:20:52 -0500 | [diff] [blame] | 29 | import os |
| 30 | |
Joe Gregorio | 89174d2 | 2010-12-20 14:37:36 -0500 | [diff] [blame] | 31 | from model import JsonModel |
Joe Gregorio | 4939655 | 2011-03-08 10:39:00 -0500 | [diff] [blame] | 32 | from errors import HttpError |
Joe Gregorio | f415342 | 2011-03-18 22:45:18 -0400 | [diff] [blame] | 33 | from anyjson import simplejson |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 34 | |
| 35 | |
| 36 | class HttpRequest(object): |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 37 | """Encapsulates a single HTTP request. |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 38 | """ |
| 39 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 40 | def __init__(self, http, postproc, uri, |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 41 | method='GET', |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 42 | body=None, |
| 43 | headers=None, |
Joe Gregorio | abda96f | 2011-02-11 20:19:33 -0500 | [diff] [blame] | 44 | methodId=None): |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 45 | """Constructor for an HttpRequest. |
| 46 | |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 47 | Args: |
| 48 | http: httplib2.Http, the transport object to use to make a request |
Joe Gregorio | abda96f | 2011-02-11 20:19:33 -0500 | [diff] [blame] | 49 | postproc: callable, called on the HTTP response and content to transform |
| 50 | it into a data object before returning, or raising an exception |
| 51 | on an error. |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 52 | uri: string, the absolute URI to send the request to |
| 53 | method: string, the HTTP method to use |
| 54 | body: string, the request body of the HTTP request |
| 55 | headers: dict, the HTTP request headers |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 56 | methodId: string, a unique identifier for the API method being called. |
| 57 | """ |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 58 | self.uri = uri |
| 59 | self.method = method |
| 60 | self.body = body |
| 61 | self.headers = headers or {} |
| 62 | self.http = http |
| 63 | self.postproc = postproc |
| 64 | |
| 65 | def execute(self, http=None): |
| 66 | """Execute the request. |
| 67 | |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 68 | Args: |
| 69 | http: httplib2.Http, an http object to be used in place of the |
| 70 | one the HttpRequest request object was constructed with. |
| 71 | |
| 72 | Returns: |
| 73 | A deserialized object model of the response body as determined |
| 74 | by the postproc. |
| 75 | |
| 76 | Raises: |
| 77 | apiclient.errors.HttpError if the response was not a 2xx. |
| 78 | httplib2.Error if a transport error has occured. |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 79 | """ |
| 80 | if http is None: |
| 81 | http = self.http |
| 82 | resp, content = http.request(self.uri, self.method, |
| 83 | body=self.body, |
| 84 | headers=self.headers) |
Joe Gregorio | 4939655 | 2011-03-08 10:39:00 -0500 | [diff] [blame] | 85 | |
| 86 | if resp.status >= 300: |
| 87 | raise HttpError(resp, content, self.uri) |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 88 | return self.postproc(resp, content) |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 89 | |
| 90 | |
| 91 | class HttpRequestMock(object): |
| 92 | """Mock of HttpRequest. |
| 93 | |
| 94 | Do not construct directly, instead use RequestMockBuilder. |
| 95 | """ |
| 96 | |
| 97 | def __init__(self, resp, content, postproc): |
| 98 | """Constructor for HttpRequestMock |
| 99 | |
| 100 | Args: |
| 101 | resp: httplib2.Response, the response to emulate coming from the request |
| 102 | content: string, the response body |
| 103 | postproc: callable, the post processing function usually supplied by |
| 104 | the model class. See model.JsonModel.response() as an example. |
| 105 | """ |
| 106 | self.resp = resp |
| 107 | self.content = content |
| 108 | self.postproc = postproc |
| 109 | if resp is None: |
Joe Gregorio | c672246 | 2010-12-20 14:29:28 -0500 | [diff] [blame] | 110 | self.resp = httplib2.Response({'status': 200, 'reason': 'OK'}) |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 111 | if 'reason' in self.resp: |
| 112 | self.resp.reason = self.resp['reason'] |
| 113 | |
| 114 | def execute(self, http=None): |
| 115 | """Execute the request. |
| 116 | |
| 117 | Same behavior as HttpRequest.execute(), but the response is |
| 118 | mocked and not really from an HTTP request/response. |
| 119 | """ |
| 120 | return self.postproc(self.resp, self.content) |
| 121 | |
| 122 | |
| 123 | class RequestMockBuilder(object): |
| 124 | """A simple mock of HttpRequest |
| 125 | |
| 126 | Pass in a dictionary to the constructor that maps request methodIds to |
| 127 | tuples of (httplib2.Response, content) that should be returned when that |
| 128 | method is called. None may also be passed in for the httplib2.Response, in |
| 129 | which case a 200 OK response will be generated. |
| 130 | |
| 131 | Example: |
| 132 | response = '{"data": {"id": "tag:google.c...' |
| 133 | requestBuilder = RequestMockBuilder( |
| 134 | { |
| 135 | 'chili.activities.get': (None, response), |
| 136 | } |
| 137 | ) |
| 138 | apiclient.discovery.build("buzz", "v1", requestBuilder=requestBuilder) |
| 139 | |
| 140 | Methods that you do not supply a response for will return a |
| 141 | 200 OK with an empty string as the response content. The methodId |
| 142 | is taken from the rpcName in the discovery document. |
| 143 | |
| 144 | For more details see the project wiki. |
| 145 | """ |
| 146 | |
| 147 | def __init__(self, responses): |
| 148 | """Constructor for RequestMockBuilder |
| 149 | |
| 150 | The constructed object should be a callable object |
| 151 | that can replace the class HttpResponse. |
| 152 | |
| 153 | responses - A dictionary that maps methodIds into tuples |
| 154 | of (httplib2.Response, content). The methodId |
| 155 | comes from the 'rpcName' field in the discovery |
| 156 | document. |
| 157 | """ |
| 158 | self.responses = responses |
| 159 | |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 160 | def __call__(self, http, postproc, uri, method='GET', body=None, |
Joe Gregorio | abda96f | 2011-02-11 20:19:33 -0500 | [diff] [blame] | 161 | headers=None, methodId=None): |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 162 | """Implements the callable interface that discovery.build() expects |
| 163 | of requestBuilder, which is to build an object compatible with |
| 164 | HttpRequest.execute(). See that method for the description of the |
| 165 | parameters and the expected response. |
| 166 | """ |
| 167 | if methodId in self.responses: |
| 168 | resp, content = self.responses[methodId] |
| 169 | return HttpRequestMock(resp, content, postproc) |
| 170 | else: |
Joe Gregorio | d433b2a | 2011-02-22 10:51:51 -0500 | [diff] [blame] | 171 | model = JsonModel(False) |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 172 | return HttpRequestMock(None, '{}', model.response) |
Joe Gregorio | cb8103d | 2011-02-11 23:20:52 -0500 | [diff] [blame] | 173 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 174 | |
Joe Gregorio | cb8103d | 2011-02-11 23:20:52 -0500 | [diff] [blame] | 175 | class HttpMock(object): |
| 176 | """Mock of httplib2.Http""" |
| 177 | |
Joe Gregorio | ec34365 | 2011-02-16 16:52:51 -0500 | [diff] [blame] | 178 | def __init__(self, filename, headers=None): |
Joe Gregorio | cb8103d | 2011-02-11 23:20:52 -0500 | [diff] [blame] | 179 | """ |
| 180 | Args: |
| 181 | filename: string, absolute filename to read response from |
| 182 | headers: dict, header to return with response |
| 183 | """ |
Joe Gregorio | ec34365 | 2011-02-16 16:52:51 -0500 | [diff] [blame] | 184 | if headers is None: |
| 185 | headers = {'status': '200 OK'} |
Joe Gregorio | cb8103d | 2011-02-11 23:20:52 -0500 | [diff] [blame] | 186 | f = file(filename, 'r') |
| 187 | self.data = f.read() |
| 188 | f.close() |
| 189 | self.headers = headers |
| 190 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 191 | def request(self, uri, |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 192 | method='GET', |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 193 | body=None, |
| 194 | headers=None, |
| 195 | redirections=1, |
| 196 | connection_type=None): |
Joe Gregorio | cb8103d | 2011-02-11 23:20:52 -0500 | [diff] [blame] | 197 | return httplib2.Response(self.headers), self.data |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 198 | |
| 199 | |
| 200 | class HttpMockSequence(object): |
| 201 | """Mock of httplib2.Http |
| 202 | |
| 203 | Mocks a sequence of calls to request returning different responses for each |
| 204 | call. Create an instance initialized with the desired response headers |
| 205 | and content and then use as if an httplib2.Http instance. |
| 206 | |
| 207 | http = HttpMockSequence([ |
| 208 | ({'status': '401'}, ''), |
| 209 | ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'), |
| 210 | ({'status': '200'}, 'echo_request_headers'), |
| 211 | ]) |
| 212 | resp, content = http.request("http://examples.com") |
| 213 | |
| 214 | There are special values you can pass in for content to trigger |
| 215 | behavours that are helpful in testing. |
| 216 | |
| 217 | 'echo_request_headers' means return the request headers in the response body |
Joe Gregorio | e9e236f | 2011-03-21 22:23:14 -0400 | [diff] [blame] | 218 | 'echo_request_headers_as_json' means return the request headers in |
| 219 | the response body |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 220 | 'echo_request_body' means return the request body in the response body |
Joe Gregorio | 0bc7091 | 2011-05-24 15:30:49 -0400 | [diff] [blame] | 221 | 'echo_request_uri' means return the request uri in the response body |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 222 | """ |
| 223 | |
| 224 | def __init__(self, iterable): |
| 225 | """ |
| 226 | Args: |
| 227 | iterable: iterable, a sequence of pairs of (headers, body) |
| 228 | """ |
| 229 | self._iterable = iterable |
| 230 | |
| 231 | def request(self, uri, |
| 232 | method='GET', |
| 233 | body=None, |
| 234 | headers=None, |
| 235 | redirections=1, |
| 236 | connection_type=None): |
| 237 | resp, content = self._iterable.pop(0) |
| 238 | if content == 'echo_request_headers': |
| 239 | content = headers |
Joe Gregorio | f415342 | 2011-03-18 22:45:18 -0400 | [diff] [blame] | 240 | elif content == 'echo_request_headers_as_json': |
| 241 | content = simplejson.dumps(headers) |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 242 | elif content == 'echo_request_body': |
| 243 | content = body |
Joe Gregorio | 0bc7091 | 2011-05-24 15:30:49 -0400 | [diff] [blame] | 244 | elif content == 'echo_request_uri': |
| 245 | content = uri |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 246 | return httplib2.Response(resp), content |
Joe Gregorio | 6bcbcea | 2011-03-10 15:26:05 -0500 | [diff] [blame] | 247 | |
| 248 | |
| 249 | def set_user_agent(http, user_agent): |
Joe Gregorio | f415342 | 2011-03-18 22:45:18 -0400 | [diff] [blame] | 250 | """Set the user-agent on every request. |
| 251 | |
Joe Gregorio | 6bcbcea | 2011-03-10 15:26:05 -0500 | [diff] [blame] | 252 | Args: |
| 253 | http - An instance of httplib2.Http |
| 254 | or something that acts like it. |
| 255 | user_agent: string, the value for the user-agent header. |
| 256 | |
| 257 | Returns: |
| 258 | A modified instance of http that was passed in. |
| 259 | |
| 260 | Example: |
| 261 | |
| 262 | h = httplib2.Http() |
| 263 | h = set_user_agent(h, "my-app-name/6.0") |
| 264 | |
| 265 | Most of the time the user-agent will be set doing auth, this is for the rare |
| 266 | cases where you are accessing an unauthenticated endpoint. |
| 267 | """ |
| 268 | request_orig = http.request |
| 269 | |
| 270 | # The closure that will replace 'httplib2.Http.request'. |
| 271 | def new_request(uri, method='GET', body=None, headers=None, |
| 272 | redirections=httplib2.DEFAULT_MAX_REDIRECTS, |
| 273 | connection_type=None): |
| 274 | """Modify the request headers to add the user-agent.""" |
| 275 | if headers is None: |
| 276 | headers = {} |
| 277 | if 'user-agent' in headers: |
| 278 | headers['user-agent'] = user_agent + ' ' + headers['user-agent'] |
| 279 | else: |
| 280 | headers['user-agent'] = user_agent |
| 281 | resp, content = request_orig(uri, method, body, headers, |
| 282 | redirections, connection_type) |
| 283 | return resp, content |
| 284 | |
| 285 | http.request = new_request |
| 286 | return http |
Joe Gregorio | f415342 | 2011-03-18 22:45:18 -0400 | [diff] [blame] | 287 | |
| 288 | |
| 289 | def tunnel_patch(http): |
| 290 | """Tunnel PATCH requests over POST. |
| 291 | Args: |
| 292 | http - An instance of httplib2.Http |
| 293 | or something that acts like it. |
| 294 | |
| 295 | Returns: |
| 296 | A modified instance of http that was passed in. |
| 297 | |
| 298 | Example: |
| 299 | |
| 300 | h = httplib2.Http() |
| 301 | h = tunnel_patch(h, "my-app-name/6.0") |
| 302 | |
| 303 | Useful if you are running on a platform that doesn't support PATCH. |
| 304 | Apply this last if you are using OAuth 1.0, as changing the method |
| 305 | will result in a different signature. |
| 306 | """ |
| 307 | request_orig = http.request |
| 308 | |
| 309 | # The closure that will replace 'httplib2.Http.request'. |
| 310 | def new_request(uri, method='GET', body=None, headers=None, |
| 311 | redirections=httplib2.DEFAULT_MAX_REDIRECTS, |
| 312 | connection_type=None): |
| 313 | """Modify the request headers to add the user-agent.""" |
| 314 | if headers is None: |
| 315 | headers = {} |
| 316 | if method == 'PATCH': |
Joe Gregorio | 06d852b | 2011-03-25 15:03:10 -0400 | [diff] [blame] | 317 | if 'oauth_token' in headers.get('authorization', ''): |
Joe Gregorio | e9e236f | 2011-03-21 22:23:14 -0400 | [diff] [blame] | 318 | logging.warning( |
Joe Gregorio | 06d852b | 2011-03-25 15:03:10 -0400 | [diff] [blame] | 319 | 'OAuth 1.0 request made with Credentials after tunnel_patch.') |
Joe Gregorio | f415342 | 2011-03-18 22:45:18 -0400 | [diff] [blame] | 320 | headers['x-http-method-override'] = "PATCH" |
| 321 | method = 'POST' |
| 322 | resp, content = request_orig(uri, method, body, headers, |
| 323 | redirections, connection_type) |
| 324 | return resp, content |
| 325 | |
| 326 | http.request = new_request |
| 327 | return http |