home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / var / lib / python-support / python2.6 / atom / mock_service.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  10.0 KB  |  220 lines

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