/atom/mock_service.py

http://radioappz.googlecode.com/ · Python · 243 lines · 172 code · 14 blank · 57 comment · 17 complexity · 3832989352a1630fbd83a05df3bdbfe5 MD5 · raw file

  1. #!/usr/bin/python
  2. #
  3. # Copyright (C) 2008 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """MockService provides CRUD ops. for mocking calls to AtomPub services.
  17. MockService: Exposes the publicly used methods of AtomService to provide
  18. a mock interface which can be used in unit tests.
  19. """
  20. import atom.service
  21. import pickle
  22. __author__ = 'api.jscudder (Jeffrey Scudder)'
  23. # Recordings contains pairings of HTTP MockRequest objects with MockHttpResponse objects.
  24. recordings = []
  25. # If set, the mock service HttpRequest are actually made through this object.
  26. real_request_handler = None
  27. def ConcealValueWithSha(source):
  28. import sha
  29. return sha.new(source[:-5]).hexdigest()
  30. def DumpRecordings(conceal_func=ConcealValueWithSha):
  31. if conceal_func:
  32. for recording_pair in recordings:
  33. recording_pair[0].ConcealSecrets(conceal_func)
  34. return pickle.dumps(recordings)
  35. def LoadRecordings(recordings_file_or_string):
  36. if isinstance(recordings_file_or_string, str):
  37. atom.mock_service.recordings = pickle.loads(recordings_file_or_string)
  38. elif hasattr(recordings_file_or_string, 'read'):
  39. atom.mock_service.recordings = pickle.loads(
  40. recordings_file_or_string.read())
  41. def HttpRequest(service, operation, data, uri, extra_headers=None,
  42. url_params=None, escape_params=True, content_type='application/atom+xml'):
  43. """Simulates an HTTP call to the server, makes an actual HTTP request if
  44. real_request_handler is set.
  45. This function operates in two different modes depending on if
  46. real_request_handler is set or not. If real_request_handler is not set,
  47. HttpRequest will look in this module's recordings list to find a response
  48. which matches the parameters in the function call. If real_request_handler
  49. is set, this function will call real_request_handler.HttpRequest, add the
  50. response to the recordings list, and respond with the actual response.
  51. Args:
  52. service: atom.AtomService object which contains some of the parameters
  53. needed to make the request. The following members are used to
  54. construct the HTTP call: server (str), additional_headers (dict),
  55. port (int), and ssl (bool).
  56. operation: str The HTTP operation to be performed. This is usually one of
  57. 'GET', 'POST', 'PUT', or 'DELETE'
  58. data: ElementTree, filestream, list of parts, or other object which can be
  59. converted to a string.
  60. Should be set to None when performing a GET or PUT.
  61. If data is a file-like object which can be read, this method will read
  62. a chunk of 100K bytes at a time and send them.
  63. If the data is a list of parts to be sent, each part will be evaluated
  64. and sent.
  65. uri: The beginning of the URL to which the request should be sent.
  66. Examples: '/', '/base/feeds/snippets',
  67. '/m8/feeds/contacts/default/base'
  68. extra_headers: dict of strings. HTTP headers which should be sent
  69. in the request. These headers are in addition to those stored in
  70. service.additional_headers.
  71. url_params: dict of strings. Key value pairs to be added to the URL as
  72. URL parameters. For example {'foo':'bar', 'test':'param'} will
  73. become ?foo=bar&test=param.
  74. escape_params: bool default True. If true, the keys and values in
  75. url_params will be URL escaped when the form is constructed
  76. (Special characters converted to %XX form.)
  77. content_type: str The MIME type for the data being sent. Defaults to
  78. 'application/atom+xml', this is only used if data is set.
  79. """
  80. full_uri = atom.service.BuildUri(uri, url_params, escape_params)
  81. (server, port, ssl, uri) = atom.service.ProcessUrl(service, uri)
  82. current_request = MockRequest(operation, full_uri, host=server, ssl=ssl,
  83. data=data, extra_headers=extra_headers, url_params=url_params,
  84. escape_params=escape_params, content_type=content_type)
  85. # If the request handler is set, we should actually make the request using
  86. # the request handler and record the response to replay later.
  87. if real_request_handler:
  88. response = real_request_handler.HttpRequest(service, operation, data, uri,
  89. extra_headers=extra_headers, url_params=url_params,
  90. escape_params=escape_params, content_type=content_type)
  91. # TODO: need to copy the HTTP headers from the real response into the
  92. # recorded_response.
  93. recorded_response = MockHttpResponse(body=response.read(),
  94. status=response.status, reason=response.reason)
  95. # Insert a tuple which maps the request to the response object returned
  96. # when making an HTTP call using the real_request_handler.
  97. recordings.append((current_request, recorded_response))
  98. return recorded_response
  99. else:
  100. # Look through available recordings to see if one matches the current
  101. # request.
  102. for request_response_pair in recordings:
  103. if request_response_pair[0].IsMatch(current_request):
  104. return request_response_pair[1]
  105. return None
  106. class MockRequest(object):
  107. """Represents a request made to an AtomPub server.
  108. These objects are used to determine if a client request matches a recorded
  109. HTTP request to determine what the mock server's response will be.
  110. """
  111. def __init__(self, operation, uri, host=None, ssl=False, port=None,
  112. data=None, extra_headers=None, url_params=None, escape_params=True,
  113. content_type='application/atom+xml'):
  114. """Constructor for a MockRequest
  115. Args:
  116. operation: str One of 'GET', 'POST', 'PUT', or 'DELETE' this is the
  117. HTTP operation requested on the resource.
  118. uri: str The URL describing the resource to be modified or feed to be
  119. retrieved. This should include the protocol (http/https) and the host
  120. (aka domain). For example, these are some valud full_uris:
  121. 'http://example.com', 'https://www.google.com/accounts/ClientLogin'
  122. host: str (optional) The server name which will be placed at the
  123. beginning of the URL if the uri parameter does not begin with 'http'.
  124. Examples include 'example.com', 'www.google.com', 'www.blogger.com'.
  125. ssl: boolean (optional) If true, the request URL will begin with https
  126. instead of http.
  127. data: ElementTree, filestream, list of parts, or other object which can be
  128. converted to a string. (optional)
  129. Should be set to None when performing a GET or PUT.
  130. If data is a file-like object which can be read, the constructor
  131. will read the entire file into memory. If the data is a list of
  132. parts to be sent, each part will be evaluated and stored.
  133. extra_headers: dict (optional) HTTP headers included in the request.
  134. url_params: dict (optional) Key value pairs which should be added to
  135. the URL as URL parameters in the request. For example uri='/',
  136. url_parameters={'foo':'1','bar':'2'} could become '/?foo=1&bar=2'.
  137. escape_params: boolean (optional) Perform URL escaping on the keys and
  138. values specified in url_params. Defaults to True.
  139. content_type: str (optional) Provides the MIME type of the data being
  140. sent.
  141. """
  142. self.operation = operation
  143. self.uri = _ConstructFullUrlBase(uri, host=host, ssl=ssl)
  144. self.data = data
  145. self.extra_headers = extra_headers
  146. self.url_params = url_params or {}
  147. self.escape_params = escape_params
  148. self.content_type = content_type
  149. def ConcealSecrets(self, conceal_func):
  150. """Conceal secret data in this request."""
  151. if self.extra_headers.has_key('Authorization'):
  152. self.extra_headers['Authorization'] = conceal_func(
  153. self.extra_headers['Authorization'])
  154. def IsMatch(self, other_request):
  155. """Check to see if the other_request is equivalent to this request.
  156. Used to determine if a recording matches an incoming request so that a
  157. recorded response should be sent to the client.
  158. The matching is not exact, only the operation and URL are examined
  159. currently.
  160. Args:
  161. other_request: MockRequest The request which we want to check this
  162. (self) MockRequest against to see if they are equivalent.
  163. """
  164. # More accurate matching logic will likely be required.
  165. return (self.operation == other_request.operation and self.uri ==
  166. other_request.uri)
  167. def _ConstructFullUrlBase(uri, host=None, ssl=False):
  168. """Puts URL components into the form http(s)://full.host.strinf/uri/path
  169. Used to construct a roughly canonical URL so that URLs which begin with
  170. 'http://example.com/' can be compared to a uri of '/' when the host is
  171. set to 'example.com'
  172. If the uri contains 'http://host' already, the host and ssl parameters
  173. are ignored.
  174. Args:
  175. uri: str The path component of the URL, examples include '/'
  176. host: str (optional) The host name which should prepend the URL. Example:
  177. 'example.com'
  178. ssl: boolean (optional) If true, the returned URL will begin with https
  179. instead of http.
  180. Returns:
  181. String which has the form http(s)://example.com/uri/string/contents
  182. """
  183. if uri.startswith('http'):
  184. return uri
  185. if ssl:
  186. return 'https://%s%s' % (host, uri)
  187. else:
  188. return 'http://%s%s' % (host, uri)
  189. class MockHttpResponse(object):
  190. """Returned from MockService crud methods as the server's response."""
  191. def __init__(self, body=None, status=None, reason=None, headers=None):
  192. """Construct a mock HTTPResponse and set members.
  193. Args:
  194. body: str (optional) The HTTP body of the server's response.
  195. status: int (optional)
  196. reason: str (optional)
  197. headers: dict (optional)
  198. """
  199. self.body = body
  200. self.status = status
  201. self.reason = reason
  202. self.headers = headers or {}
  203. def read(self):
  204. return self.body
  205. def getheader(self, header_name):
  206. return self.headers[header_name]