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