utils.py
Go to the documentation of this file.
00001 # -*- coding: utf-8 -*-
00002 import re
00003 import six
00004 from json import dumps
00005 
00006 from webtest.compat import urlencode
00007 
00008 
00009 class NoDefault(object):
00010     """Sentinel to uniquely represent no default value."""
00011 
00012     def __repr__(self):
00013         return '<NoDefault>'
00014 
00015 NoDefault = NoDefault()
00016 
00017 
00018 def json_method(method):
00019     """Do a %(method)s request.  Very like the
00020     :class:`~webtest.TestApp.%(lmethod)s` method.
00021 
00022     ``params`` are dumped to json and put in the body of the request.
00023     Content-Type is set to ``application/json``.
00024 
00025     Returns a :class:`webtest.TestResponse` object.
00026     """
00027 
00028     def wrapper(self, url, params=NoDefault, **kw):
00029         content_type = 'application/json'
00030         if params is not NoDefault:
00031             params = dumps(params, cls=self.JSONEncoder)
00032         kw.update(
00033             params=params,
00034             content_type=content_type,
00035             upload_files=None,
00036         )
00037         return self._gen_request(method, url, **kw)
00038 
00039     subst = dict(lmethod=method.lower(), method=method)
00040     wrapper.__doc__ = json_method.__doc__ % subst
00041     wrapper.__name__ = str('%(lmethod)s_json' % subst)
00042 
00043     return wrapper
00044 
00045 
00046 def stringify(value):
00047     if isinstance(value, six.text_type):
00048         return value
00049     elif isinstance(value, six.binary_type):
00050         return value.decode('utf8')
00051     else:
00052         return str(value)
00053 
00054 
00055 entity_pattern = re.compile(r"&(\w+|#\d+|#[xX][a-fA-F0-9]+);")
00056 
00057 
00058 def encode_params(params, content_type):
00059     if params is NoDefault:
00060         return ''
00061     if isinstance(params, dict) or hasattr(params, 'items'):
00062         params = list(params.items())
00063     if isinstance(params, (list, tuple)):
00064         if content_type:
00065             content_type = content_type.lower()
00066             if 'charset=' in content_type:
00067                 charset = content_type.split('charset=')[1]
00068                 charset = charset.strip('; ').lower()
00069                 encoded_params = []
00070                 for k, v in params:
00071                     if isinstance(v, six.text_type):
00072                         v = v.encode(charset)
00073                     encoded_params.append((k, v))
00074                 params = encoded_params
00075         params = urlencode(params, doseq=True)
00076     return params
00077 
00078 
00079 def make_pattern(pat):
00080     """Find element pattern can be a regex or a callable."""
00081     if pat is None:
00082         return None
00083     if isinstance(pat, six.binary_type):
00084         pat = pat.decode('utf8')
00085     if isinstance(pat, six.text_type):
00086         pat = re.compile(pat)
00087     if hasattr(pat, 'search'):
00088         return pat.search
00089     if hasattr(pat, '__call__'):
00090         return pat
00091     raise ValueError(
00092         "Cannot make callable pattern object out of %r" % pat)
00093 
00094 
00095 class _RequestCookieAdapter(object):
00096     """
00097     cookielib.CookieJar support for webob.Request
00098     """
00099     def __init__(self, request):
00100         self._request = request
00101         self.origin_req_host = request.host
00102 
00103     def is_unverifiable(self):
00104         return True  # sure? Why not?
00105 
00106     @property
00107     def unverifiable(self):  # NOQA
00108         # This is undocumented method that Python 3 cookielib uses
00109         return True
00110 
00111     def get_full_url(self):
00112         return self._request.url
00113 
00114     def get_host(self):
00115         return self.origin_req_host
00116     get_origin_req_host = get_host
00117 
00118     def add_unredirected_header(self, key, header):
00119         self._request.headers[key] = header
00120 
00121     def has_header(self, key):
00122         return key in self._request.headers
00123 
00124     def get_type(self):
00125         return self._request.scheme
00126 
00127     @property
00128     def type(self):  # NOQA
00129         # This is undocumented method that Python 3 cookielib uses
00130         return self.get_type()
00131 
00132     def header_items(self):  # pragma: no cover
00133         # This is unused on most python versions
00134         return self._request.headers.items()
00135 
00136 
00137 class _ResponseCookieAdapter(object):
00138     """
00139     cookielib.CookieJar support for webob.Response
00140     """
00141     def __init__(self, response):
00142         self._response = response
00143 
00144     def info(self):
00145         return self
00146 
00147     def getheaders(self, header):
00148         return self._response.headers.getall(header)
00149 
00150     def get_all(self, headers, default):  # NOQA
00151         # This is undocumented method that Python 3 cookielib uses
00152         return self._response.headers.getall(headers)


webtest
Author(s): AlexV
autogenerated on Sat Mar 25 2017 03:32:05