Back to index

moin  1.9.0~rc2
Public Member Functions | Public Attributes | Static Public Attributes | Properties | Private Member Functions | Private Attributes
MoinMoin.support.werkzeug.test.EnvironBuilder Class Reference
Collaboration diagram for MoinMoin.support.werkzeug.test.EnvironBuilder:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def form_property
def server_name
def server_port
def __del__
def close
def get_environ
def get_request

Public Attributes

 charset
 path
 method
 headers
 errors_stream
 multithread
 multiprocess
 run_once
 environ_base
 environ_overrides
 closed
 script_root
 host
 url_scheme

Static Public Attributes

string server_protocol = 'HTTP/1.1'
tuple wsgi_version = (1, 0)
 request_class = BaseRequest
tuple form
tuple files

Properties

 base_url
 content_type
 content_length
 input_stream
 query_string
 args

Private Member Functions

def _add_file_from_data
def _get_base_url
def _set_base_url
def _get_content_type
def _set_content_type
def _get_content_length
def _set_content_length
def _get_input_stream
def _set_input_stream
def _get_query_string
def _set_query_string
def _get_args
def _set_args

Private Attributes

 _input_stream
 _form
 _files
 _query_string
 _args

Detailed Description

This class can be used to conveniently create a WSGI environment
for testing purposes.  It can be used to quickly create WSGI environments
or request objects from arbitrary data.

The signature of this class is also used in some other places as of
Werkzeug 0.5 (:func:`create_environ`, :meth:`BaseResponse.from_values`,
:meth:`Client.open`).  Because of this most of the functionality is
available through the constructor alone.

Files and regular form data can be manipulated independently of each
other with the :attr:`form` and :attr:`files` attributes, but are
passed with the same argument to the constructor: `data`.

`data` can be any of these values:

-   a `str`: If it's a string it is converted into a :attr:`input_stream`,
    the :attr:`content_length` is set and you have to provide a
    :attr:`content_type`.
-   a `dict`: If it's a dict the keys have to be strings and the values
    and of the following objects:

    -   a :class:`file`-like object.  These are converted into
        :class:`FileStorage` objects automatically.
    -   a tuple.  The :meth:`~FileMultiDict.add_file` method is called
        with the tuple items as positional arguments.

:param path: the path of the request.  In the WSGI environment this will
             end up as `PATH_INFO`.  If the `query_string` is not defined
             and there is a question mark in the `path` everything after
             it is used as query string.
:param base_url: the base URL is a URL that is used to extract the WSGI
                 URL scheme, host (server name + server port) and the
                 script root (`SCRIPT_NAME`).
:param query_string: an optional string or dict with URL parameters.
:param method: the HTTP method to use, defaults to `GET`.
:param input_stream: an optional input stream.  Do not specify this and
                     `data`.  As soon as an input stream is set you can't
                     modify :attr:`args` and :attr:`files` unless you
                     set the :attr:`input_stream` to `None` again.
:param content_type: The content type for the request.  As of 0.5 you
                     don't have to provide this when specifying files
                     and form data via `data`.
:param content_length: The content length for the request.  You don't
                       have to specify this when providing data via
                       `data`.
:param errors_stream: an optional error stream that is used for
                      `wsgi.errors`.  Defaults to :data:`stderr`.
:param multithread: controls `wsgi.multithread`.  Defaults to `False`.
:param multiprocess: controls `wsgi.multiprocess`.  Defaults to `False`.
:param run_once: controls `wsgi.run_once`.  Defaults to `False`.
:param headers: an optional list or :class:`Headers` object of headers.
:param data: a string or dict of form data.  See explanation above.
:param environ_base: an optional dict of environment defaults.
:param environ_overrides: an optional dict of environment overrides.
:param charset: the charset used to encode unicode data.

Definition at line 181 of file test.py.


Constructor & Destructor Documentation

def MoinMoin.support.werkzeug.test.EnvironBuilder.__init__ (   self,
  path = '/',
  base_url = None,
  query_string = None,
  method = 'GET',
  input_stream = None,
  content_type = None,
  content_length = None,
  errors_stream = None,
  multithread = False,
  multiprocess = False,
  run_once = False,
  headers = None,
  data = None,
  environ_base = None,
  environ_overrides = None,
  charset = 'utf-8' 
)

Definition at line 252 of file test.py.

00252 
00253                  environ_base=None, environ_overrides=None, charset='utf-8'):
00254         if query_string is None and '?' in path:
00255             path, query_string = path.split('?', 1)
00256         self.charset = charset
00257         self.path = path
00258         self.base_url = base_url
00259         if isinstance(query_string, basestring):
00260             self.query_string = query_string
00261         else:
00262             if query_string is None:
00263                 query_string = MultiDict()
00264             elif not isinstance(query_string, MultiDict):
00265                 query_string = MultiDict(query_string)
00266             self.args = query_string
00267         self.method = method
00268         if headers is None:
00269             headers = Headers()
00270         elif not isinstance(headers, Headers):
00271             headers = Headers(headers)
00272         self.headers = headers
00273         self.content_type = content_type
00274         if errors_stream is None:
00275             errors_stream = sys.stderr
00276         self.errors_stream = errors_stream
00277         self.multithread = multithread
00278         self.multiprocess = multiprocess
00279         self.run_once = run_once
00280         self.environ_base = environ_base
00281         self.environ_overrides = environ_overrides
00282         self.input_stream = input_stream
00283         self.content_length = content_length
00284         self.closed = False
00285 
00286         if data:
00287             if input_stream is not None:
00288                 raise TypeError('can\'t provide input stream and data')
00289             if isinstance(data, basestring):
00290                 self.input_stream = StringIO(data)
00291                 if self.content_length is None:
00292                     self.content_length = len(data)
00293             else:
00294                 for key, value in _iter_data(data):
00295                     if isinstance(value, (tuple, dict)) or \
00296                        hasattr(value, 'read'):
00297                         self._add_file_from_data(key, value)
00298                     else:
00299                         self.form[key] = value

Definition at line 461 of file test.py.

00461 
00462     def __del__(self):
00463         self.close()

Here is the call graph for this function:


Member Function Documentation

def MoinMoin.support.werkzeug.test.EnvironBuilder._add_file_from_data (   self,
  key,
  value 
) [private]
Called in the EnvironBuilder to add files from the data dict.

Definition at line 300 of file test.py.

00300 
00301     def _add_file_from_data(self, key, value):
00302         """Called in the EnvironBuilder to add files from the data dict."""
00303         if isinstance(value, tuple):
00304             self.files.add_file(key, *value)
00305         elif isinstance(value, dict):
00306             from warnings import warn
00307             warn(DeprecationWarning('it\'s no longer possible to pass dicts '
00308                                     'as `data`.  Use tuples or FileStorage '
00309                                     'objects intead'), stacklevel=2)
00310             args = v
00311             value = dict(value)
00312             mimetype = value.pop('mimetype', None)
00313             if mimetype is not None:
00314                 value['content_type'] = mimetype
00315             self.files.add_file(key, **value)
00316         else:
00317             self.files.add_file(key, value)

Definition at line 431 of file test.py.

00431 
00432     def _get_args(self):
00433         if self._query_string is not None:
00434             raise AttributeError('a query string is defined')
00435         if self._args is None:
00436             self._args = MultiDict()
00437         return self._args

Definition at line 318 of file test.py.

00318 
00319     def _get_base_url(self):
00320         return urlparse.urlunsplit((self.url_scheme, self.host,
00321                                     self.script_root, '', '')).rstrip('/') + '/'

Definition at line 365 of file test.py.

00365 
00366     def _get_content_length(self):
00367         return self.headers.get('Content-Length', type=int)

Definition at line 343 of file test.py.

00343 
00344     def _get_content_type(self):
00345         ct = self.headers.get('Content-Type')
00346         if ct is None and not self._input_stream:
00347             if self.method in ('POST', 'PUT'):
00348                 if self._files:
00349                     return 'multipart/form-data'
00350                 return 'application/x-www-form-urlencoded'
00351             return None
00352         return ct

Definition at line 403 of file test.py.

00403 
00404     def _get_input_stream(self):
00405         return self._input_stream

Definition at line 415 of file test.py.

00415 
00416     def _get_query_string(self):
00417         if self._query_string is None:
00418             if self._args is not None:
00419                 return url_encode(self._args, charset=self.charset)
00420             return ''
00421         return self._query_string

Here is the call graph for this function:

def MoinMoin.support.werkzeug.test.EnvironBuilder._set_args (   self,
  value 
) [private]

Definition at line 438 of file test.py.

00438 
00439     def _set_args(self, value):
00440         self._query_string = None
00441         self._args = value

def MoinMoin.support.werkzeug.test.EnvironBuilder._set_base_url (   self,
  value 
) [private]

Definition at line 322 of file test.py.

00322 
00323     def _set_base_url(self, value):
00324         if value is None:
00325             scheme = 'http'
00326             netloc = 'localhost'
00327             scheme = 'http'
00328             script_root = ''
00329         else:
00330             scheme, netloc, script_root, qs, anchor = urlparse.urlsplit(value)
00331             if qs or anchor:
00332                 raise ValueError('base url must not contain a query string '
00333                                  'or fragment')
00334         self.script_root = script_root.rstrip('/')
00335         self.host = netloc
00336         self.url_scheme = scheme

Definition at line 368 of file test.py.

00368 
00369     def _set_content_length(self, value):
00370         if value is None:
00371             self.headers.pop('Content-Length', None)
00372         else:
00373             self.headers['Content-Length'] = str(value)

Definition at line 353 of file test.py.

00353 
00354     def _set_content_type(self, value):
00355         if value is None:
00356             self.headers.pop('Content-Type', None)
00357         else:
00358             self.headers['Content-Type'] = value

Definition at line 406 of file test.py.

00406 
00407     def _set_input_stream(self, value):
00408         self._input_stream = value
00409         self._form = self._files = None

Definition at line 422 of file test.py.

00422 
00423     def _set_query_string(self, value):
00424         self._query_string = value
00425         self._args = None

Closes all files.  If you put real :class:`file` objects into the
:attr:`files` dict you can call this method to automatically close
them all in one go.

Definition at line 464 of file test.py.

00464 
00465     def close(self):
00466         """Closes all files.  If you put real :class:`file` objects into the
00467         :attr:`files` dict you can call this method to automatically close
00468         them all in one go.
00469         """
00470         if self.closed:
00471             return
00472         try:
00473             files = self.files.itervalues()
00474         except AttributeError:
00475             files = ()
00476         for f in files:
00477             try:
00478                 f.close()
00479             except Exception, e:
00480                 pass
00481         self.closed = True

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.test.EnvironBuilder.form_property (   name,
  storage,
  doc 
)

Definition at line 380 of file test.py.

00380 
00381     def form_property(name, storage, doc):
00382         key = '_' + name
00383         def getter(self):
00384             if self._input_stream is not None:
00385                 raise AttributeError('an input stream is defined')
00386             rv = getattr(self, key)
00387             if rv is None:
00388                 rv = storage()
00389                 setattr(self, key, rv)
00390             return rv
00391         def setter(self, value):
00392             self._input_stream = None
00393             setattr(self, key, value)
00394         return property(getter, setter, doc)

Return the built environ.

Definition at line 482 of file test.py.

00482 
00483     def get_environ(self):
00484         """Return the built environ."""
00485         input_stream = self.input_stream
00486         content_length = self.content_length
00487         content_type = self.content_type
00488 
00489         if input_stream is not None:
00490             start_pos = input_stream.tell()
00491             input_stream.seek(0, 2)
00492             end_pos = input_stream.tell()
00493             input_stream.seek(start_pos)
00494             content_length = end_pos - start_pos
00495         elif content_type == 'multipart/form-data':
00496             values = CombinedMultiDict([self.form, self.files])
00497             input_stream, content_length, boundary = \
00498                 stream_encode_multipart(values, charset=self.charset)
00499             content_type += '; boundary="%s"' % boundary
00500         elif content_type == 'application/x-www-form-urlencoded':
00501             values = url_encode(self.form, charset=self.charset)
00502             content_length = len(values)
00503             input_stream = StringIO(values)
00504         else:
00505             input_stream = _empty_stream
00506 
00507         result = {}
00508         if self.environ_base:
00509             result.update(self.environ_base)
00510 
00511         def _encode(x):
00512             if isinstance(x, unicode):
00513                 return x.encode(self.charset)
00514             return x
00515 
00516         result.update({
00517             'REQUEST_METHOD':       self.method,
00518             'SCRIPT_NAME':          _encode(self.script_root),
00519             'PATH_INFO':            _encode(self.path),
00520             'QUERY_STRING':         self.query_string,
00521             'SERVER_NAME':          self.server_name,
00522             'SERVER_PORT':          str(self.server_port),
00523             'HTTP_HOST':            self.host,
00524             'SERVER_PROTOCOL':      self.server_protocol,
00525             'CONTENT_TYPE':         content_type or '',
00526             'CONTENT_LENGTH':       str(content_length or '0'),
00527             'wsgi.version':         self.wsgi_version,
00528             'wsgi.url_scheme':      self.url_scheme,
00529             'wsgi.input':           input_stream,
00530             'wsgi.errors':          self.errors_stream,
00531             'wsgi.multithread':     self.multithread,
00532             'wsgi.multiprocess':    self.multiprocess,
00533             'wsgi.run_once':        self.run_once
00534         })
00535         for key, value in self.headers.to_list(self.charset):
00536             result['HTTP_%s' % key.upper().replace('-', '_')] = value
00537         if self.environ_overrides:
00538             result.update(self.environ_overrides)
00539         return result

Here is the call graph for this function:

Here is the caller graph for this function:

Returns a request with the data.  If the request class is not
specified :attr:`request_class` is used.

:param cls: The request wrapper to use.

Definition at line 540 of file test.py.

00540 
00541     def get_request(self, cls=None):
00542         """Returns a request with the data.  If the request class is not
00543         specified :attr:`request_class` is used.
00544 
00545         :param cls: The request wrapper to use.
00546         """
00547         if cls is None:
00548             cls = self.request_class
00549         return cls(self.get_environ())
00550 

Here is the call graph for this function:

The server name (read-only, use :attr:`host` to set)

Definition at line 447 of file test.py.

00447 
00448     def server_name(self):
00449         """The server name (read-only, use :attr:`host` to set)"""
00450         return self.host.split(':', 1)[0]

Here is the caller graph for this function:

The server port as integer (read-only, use :attr:`host` to set)

Definition at line 452 of file test.py.

00452 
00453     def server_port(self):
00454         """The server port as integer (read-only, use :attr:`host` to set)"""
00455         pieces = self.host.split(':', 1)
00456         if len(pieces) == 2 and pieces[1].isdigit():
00457             return int(pieces[1])
00458         elif self.url_scheme == 'https':
00459             return 443
00460         return 80

Here is the caller graph for this function:


Member Data Documentation

Definition at line 424 of file test.py.

Definition at line 408 of file test.py.

Definition at line 408 of file test.py.

Definition at line 391 of file test.py.

Definition at line 423 of file test.py.

Definition at line 255 of file test.py.

Definition at line 283 of file test.py.

Definition at line 279 of file test.py.

Definition at line 280 of file test.py.

Definition at line 275 of file test.py.

Initial value:
form_property('files', FileMultiDict, doc='''
    A :class:`FileMultiDict` of uploaded files.  You can use the
    :meth:`~FileMultiDict.add_file` method to add new files to the
    dict.''')

Definition at line 397 of file test.py.

Initial value:
form_property('form', MultiDict, doc='''
    A :class:`MultiDict` of form values.''')

Definition at line 395 of file test.py.

Definition at line 271 of file test.py.

Definition at line 334 of file test.py.

Definition at line 266 of file test.py.

Definition at line 277 of file test.py.

Definition at line 276 of file test.py.

Definition at line 256 of file test.py.

Definition at line 246 of file test.py.

Definition at line 278 of file test.py.

Definition at line 333 of file test.py.

Definition at line 240 of file test.py.

Definition at line 335 of file test.py.

Definition at line 243 of file test.py.


Property Documentation

Initial value:
property(_get_args, _set_args, doc='''
    The URL arguments as :class:`MultiDict`.''')

Definition at line 442 of file test.py.

Initial value:
property(_get_base_url, _set_base_url, doc='''
    The base URL is a URL that is used to extract the WSGI
    URL scheme, host (server name + server port) and the
    script root (`SCRIPT_NAME`).''')

Definition at line 337 of file test.py.

Initial value:
property(_get_content_length, _set_content_length, doc='''
    The content length as integer.  Reflected from and to the
    :attr:`headers`.  Do not set if you set :attr:`files` or
    :attr:`form` for auto detection.''')

Definition at line 374 of file test.py.

Initial value:
property(_get_content_type, _set_content_type, doc='''
    The content type for the request.  Reflected from and to the
    :attr:`headers`.  Do not set if you set :attr:`files` or
    :attr:`form` for auto detection.''')

Definition at line 359 of file test.py.

Initial value:
property(_get_input_stream, _set_input_stream, doc='''
    An optional input stream.  If you set this it will clear
    :attr:`form` and :attr:`files`.''')

Definition at line 410 of file test.py.

Initial value:
property(_get_query_string, _set_query_string, doc='''
    The query string.  If you set this to a string :attr:`args` will
    no longer be available.''')

Definition at line 426 of file test.py.


The documentation for this class was generated from the following file: