
_                 @   s  d  Z  d d l Z d d l Z d d l m Z d d l m Z d d l m Z d d l m	 Z	 d d l
 m
 Z
 d d	 l m Z d d
 l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m  Z  d d l m! Z! d d l" m# Z# d d l" m$ Z$ d d l" m% Z% d d l" m& Z& d d  l" m' Z' d d! l" m( Z( d d" l) m* Z* d d# l+ m, Z, d d$ l- m. Z. d d% l- m/ Z/ y d d& l0 m1 Z2 Wn" e3 k
 rvd d& l4 m1 Z2 Yn Xy d d' l5 m6 Z6 Wn" e3 k
 rd d' l7 m6 Z6 Yn Xd( d) d* d d+ d, d-  Z8 d d+ d. d/  Z9 Gd0 d1   d1 e:  Z; Gd2 d3   d3 e:  Z< Gd4 d5   d5 e6  Z= d6 d7   Z> Gd8 d9   d9 e:  Z? Gd: d;   d; e@  ZA Gd< d=   d= e:  ZB d> d?   ZC d@ dA dB  ZD d S)Cz
    werkzeug.test
    ~~~~~~~~~~~~~

    This module implements a client to WSGI applications for testing.

    :copyright: 2007 Pallets
    :license: BSD-3-Clause
    N)BytesIO)chain)random)TemporaryFile)time   )	iteritems)	iterlists)
itervalues)make_literal_wrapper)reraise)string_types)	text_type)to_bytes)wsgi_encoding_dance)_get_environ)CallbackDict)CombinedMultiDict)EnvironHeaders)FileMultiDict)Headers)	MultiDict)dump_cookie)dump_options_header)parse_options_header)
iri_to_uri)
url_encode)url_fix)	url_parse)url_unparse)url_unquote)get_content_type)BaseRequest)ClosingIterator)get_current_url)Request)	CookieJarTi   i  zutf-8c          	      s4  | d k r" d t    t   f } t   d d g   | rR    f d d    n   d j    f d d   } t |  t  s t |   }  x\t |   D]N\ } }  x?|  D]7} | d	 | | f  t | d
 d  } | d k	 rt | d t | d d   }	 t | d d  }
 |
 d k rB|	 r<t j	 |	  d p?d }
 |	 d k	 r_| d |	  n
 | d  | d |
  xb | d  } | sP |  qzWn> t | t
  st |  } t |   } | d   |  | d  q Wq W| d |  t   d j    }   d j d    d | | f S)zEncode a dict of values (either strings or file descriptors or
    :class:`FileStorage` objects.) into a multipart encoded string stored
    in a file descriptor.
    Nz$---------------WerkzeugFormPart_%s%sr   Fc                s     \ } } } | r% | j  |   n~ t |   } |   d  k rU | j  |   n@ t d  } | j  | j    | j  |   |   d <d   d <| |   d <d  S)Nr   zwb+r   T   )writelenr   getvalue)stringstreamtotal_lengthZon_disklengthZ
new_stream)_closure	threshold 1/tmp/pip-build-5gj8f0j9/Werkzeug/werkzeug/test.pywrite_binaryI   s    

z-stream_encode_multipart.<locals>.write_binaryc                s    |  j      d  S)N)encode)r+   )charsetr3   r1   r2   r(   \   s    z&stream_encode_multipart.<locals>.writez/--%s
Content-Disposition: form-data; name="%s"readfilenamenamecontent_typezapplication/octet-streamz; filename="%s"
z
zContent-Type: %s

i @  z

z--%s--
)r   r   r   r(   
isinstancer   r	   getattr	mimetypes
guess_typer   strr   inttellseek)valuesuse_tempfiler0   boundaryr5   r(   keyvaluereaderr7   r9   chunkr.   r1   )r/   r5   r0   r3   r2   stream_encode_multipart<   sN    


rI   c             C   s7   t  |  d d d | d | \ } } } | | j   f S)z|Like `stream_encode_multipart` but returns a tuple in the form
    (``boundary``, ``data``) where data is a bytestring.
    rC   FrD   r5   )rI   r6   )rB   rD   r5   r,   r.   r1   r1   r2   encode_multipart   s    $rJ   c               @   s=   e  Z d  Z d Z d d   Z d d   Z d d d  Z d S)	_TestCookieHeadersz$A headers adapter for cookielib
    c             C   s   | |  _  d  S)N)headers)selfrL   r1   r1   r2   __init__   s    z_TestCookieHeaders.__init__c             C   sO   g  } | j    } x6 |  j D]+ \ } } | j    | k r | j |  q W| S)N)lowerrL   append)rM   r8   rL   kvr1   r1   r2   
getheaders   s    z_TestCookieHeaders.getheadersNc             C   sU   g  } x< |  j  D]1 \ } } | j   | j   k r | j |  q W| pT | pT g  S)N)rL   rO   rP   )rM   r8   defaultrvrQ   rR   r1   r1   r2   get_all   s
    z_TestCookieHeaders.get_all)__name__
__module____qualname____doc__rN   rS   rV   r1   r1   r1   r2   rK      s   rK   c               @   s.   e  Z d  Z d Z d d   Z d d   Z d S)_TestCookieResponsezSomething that looks like a httplib.HTTPResponse, but is actually just an
    adapter for our test responses to make them available for cookielib.
    c             C   s   t  |  |  _ d  S)N)rK   rL   )rM   rL   r1   r1   r2   rN      s    z_TestCookieResponse.__init__c             C   s   |  j  S)N)rL   )rM   r1   r1   r2   info   s    z_TestCookieResponse.infoN)rW   rX   rY   rZ   rN   r\   r1   r1   r1   r2   r[      s   r[   c               @   s.   e  Z d  Z d Z d d   Z d d   Z d S)_TestCookieJarzA cookielib.CookieJar modified to inject and read cookie headers from
    and to wsgi environments, and wsgi application responses.
    c             C   sC   d d   |  D } | r/ d j  |  | d <n | j d d  d S)zYInject the cookies as client headers into the server's wsgi
        environment.
        c             S   s&   g  |  ] } d  | j  | j f  q S)z%s=%s)r8   rF   ).0cr1   r1   r2   
<listcomp>   s   	 z._TestCookieJar.inject_wsgi.<locals>.<listcomp>z; ZHTTP_COOKIEN)joinpop)rM   environZcvalsr1   r1   r2   inject_wsgi   s    z_TestCookieJar.inject_wsgic             C   s&   |  j  t |  t t |    d S)zXExtract the server's set-cookie headers as cookies into the
        cookie jar.
        N)extract_cookiesr[   	U2Requestr$   )rM   rc   rL   r1   r1   r2   extract_wsgi   s    z_TestCookieJar.extract_wsgiN)rW   rX   rY   rZ   rd   rg   r1   r1   r1   r2   r]      s   r]   c             c   s   t  |  t  rK x t |   D]( \ } } x | D] } | | f Vq/ Wq WnV xS t |   D]E \ } } t  | t  r x' | D] } | | f Vqz WqX | | f VqX Wd S)zIterates over a `dict` or :class:`MultiDict` yielding all keys and
    values.
    This is used to iterate over the data passed to the
    :class:`EnvironBuilder`.
    N)r:   r   r	   r   list)datarE   rB   rF   r1   r1   r2   
_iter_data   s    rj   c               @   s  e  Z d  Z d Z d Z d? Z e Z d d l Z e	 e j
  Z [ d d d d d d d d d d d d d d d d	 d d d
 d  Z e d d    Z d d   Z e	 d d    Z e d d    Z e j d d    Z e d d    Z e j d d    Z e d d    Z e j d d    Z e d d    Z e d d    Z e j d d    Z d  d!   Z d" d#   Z e d$ d%    Z e j d& d%    Z e d' d(    Z e j d) d(    Z e d* d+    Z e j d, d+    Z e d- d.    Z e j d/ d.    Z e d0 d1    Z e j d2 d1    Z e d3 d4    Z e d5 d6    Z  d7 d8   Z! d9 d:   Z" d; d<   Z# d d= d>  Z$ d S)@EnvironBuildera  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` or `bytes` object: The object is converted into an
        :attr:`input_stream`, the :attr:`content_length` is set and you have to
        provide a :attr:`content_type`.
    -   a `dict` or :class:`MultiDict`: The keys have to be strings. The values
        have to be either any of the following objects, or a list of any 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 key and the unpacked `tuple` items as positional
            arguments.
        -   a `str`:  The string is set as form data for the associated key.
    -   a file-like object: The object content is loaded in memory and then
        handled like a regular `str` or a `bytes`.

    :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 or a file-object.
                 See explanation above.
    :param json: An object to be serialized and assigned to ``data``.
        Defaults the content type to ``"application/json"``.
        Serialized with the function assigned to :attr:`json_dumps`.
    :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.

    .. versionadded:: 0.15
        The ``json`` param and :meth:`json_dumps` method.

    .. versionadded:: 0.15
        The environ has keys ``REQUEST_URI`` and ``RAW_URI`` containing
        the path before perecent-decoding. This is not part of the WSGI
        PEP, but many WSGI servers include it.

    .. versionchanged:: 0.6
       ``path`` and ``base_url`` can now be unicode strings that are
       encoded with :func:`iri_to_uri`.
    zHTTP/1.1r   r   N/GETFzutf-8c             C   s>  t  |  } | d  k	 r6 | d  | k r6 t d   | d  k rr | d  | k rr | j | d  d  \ } } | |  _ t |  |  _ | d  k	 r t t | |  |  } | |  _ t | t	 t
 f  r | |  _ n< | d  k r t   } n t | t  st |  } | |  _ | |  _ | d  k r5t   } n t | t  sPt |  } | |  _ | d  k	 rn| |  _ | d  k rt j } | |  _ |	 |  _ |
 |  _ | |  _ | |  _ | |  _ | |  _ | |  _ d |  _ | d  k	 r| d  k	 rt d   |  j |  } |  j d  k rd |  _ | r%| d  k	 r=t d   t | d  rX| j    } t | t
  ry| j! |  j  } t | t	  rt" |  |  _ |  j d  k r%t# |  |  _ nm xj t$ |  D]\ \ } } t | t% t& f  st | d  r|  j' | |  q|  j( j) |  j* |  qW| d  k	 r:| |  _+ d  S)	N?z6Query string is defined in the path and as an argumentr   Fz can't provide both json and datazapplication/jsonz#can't provide input stream and datar6   ),r   
ValueErrorsplitr5   r   pathr   base_urlr:   bytesr   query_stringr   argsmethodr   rL   r9   sysstderrerrors_streammultithreadmultiprocessrun_onceenviron_baseenviron_overridesinput_streamcontent_lengthclosed	TypeError
json_dumpshasattrr6   r4   r   r)   rj   tupledict_add_file_from_dataformZsetlistdefaultrP   mimetype)rM   rq   rr   rt   rv   r   r9   r   ry   rz   r{   r|   rL   ri   r}   r~   r5   r   jsonZpath_srE   rF   r1   r1   r2   rN   B  sv    																	$zEnvironBuilder.__init__c             K   s   t  t |   } d | d d |  j | d | j d  | d  d | d d	 | d
 d | d d | j d d  d | j d d  d | d d | d d | d d | d d | i } | j |  |  |   S)zTurn an environ dict back into a builder. Any extra kwargs
        override the args extracted from the environ.

        .. versionadded:: 0.15
        rq   	PATH_INFOrr   zwsgi.url_schemeHostSCRIPT_NAMErt   QUERY_STRINGrv   REQUEST_METHODr   z
wsgi.inputr9   zContent-TypeNr   zContent-Lengthry   zwsgi.errorsrz   zwsgi.multithreadr{   zwsgi.multiprocessr|   zwsgi.run_oncerL   )r   r   _make_base_urlrb   update)clsrc   kwargsrL   outr1   r1   r2   from_environ  s     
	






zEnvironBuilder.from_environc             C   s<   t  | t  r% |  j j | |  n |  j j | |  d S)z=Called in the EnvironBuilder to add files from the data dict.N)r:   r   filesZadd_file)rM   rE   rF   r1   r1   r2   r     s    z"EnvironBuilder._add_file_from_datac             C   s&   t  |  | | d d f  j d  d S)N rl   )r   rstrip)schemehostscript_rootr1   r1   r2   r     s    zEnvironBuilder._make_base_urlc             C   s   |  j  |  j |  j |  j  S)z`The base URL is used to extract the URL scheme, host name,
        port, and root path.
        )r   
url_schemer   r   )rM   r1   r1   r2   rr     s    zEnvironBuilder.base_urlc             C   s|   | d  k r! d } d } d } n3 t  |  \ } } } } } | sH | rT t d   | j d  |  _ | |  _ | |  _ d  S)Nhttp	localhostr   z4base url must not contain a query string or fragmentrl   )r   ro   r   r   r   r   )rM   rF   r   netlocr   qsanchorr1   r1   r2   rr     s    		c             C   sJ   |  j  j d  } | d k rF |  j rF |  j r5 d S|  j rB d Sd S| S)zThe 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.
        zContent-TypeNzmultipart/form-dataz!application/x-www-form-urlencoded)rL   get_input_stream_files_form)rM   ctr1   r1   r2   r9     s    		zEnvironBuilder.content_typec             C   s3   | d  k r" |  j  j d d   n | |  j  d <d  S)NzContent-Type)rL   rb   )rM   rF   r1   r1   r2   r9     s    c             C   s*   |  j  } | r& | j d  d j   Sd S)zYThe mimetype (content type without charset etc.)

        .. versionadded:: 0.14
        ;r   N)r9   rp   strip)rM   r   r1   r1   r2   r     s    	zEnvironBuilder.mimetypec             C   s   t  | |  j  |  _ d  S)N)r!   r5   r9   )rM   rF   r1   r1   r2   r     s    c                s>     f d d   } t    j j d d   d } t | |  S)z The mimetype parameters as dict.  For example if the
        content type is ``text/html; charset=utf-8`` the params would be
        ``{'charset': 'utf-8'}``.

        .. versionadded:: 0.14
        c                s   t    j |     j d <d  S)NzContent-Type)r   r   rL   )d)rM   r1   r2   	on_update  s    z1EnvironBuilder.mimetype_params.<locals>.on_updatezcontent-typer   r   )r   rL   r   r   )rM   r   r   r1   )rM   r2   mimetype_params  s    	zEnvironBuilder.mimetype_paramsc             C   s   |  j  j d d t S)zThe 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.
        zContent-Lengthtype)rL   r   r?   )rM   r1   r1   r2   r     s    zEnvironBuilder.content_lengthc             C   s9   | d  k r" |  j  j d d   n t |  |  j  d <d  S)NzContent-Length)rL   rb   r>   )rM   rF   r1   r1   r2   r     s    c             C   sS   |  j  d k	 r t d   t |  |  } | d k rO |   } t |  | |  | S)zCommon behavior for getting the :attr:`form` and
        :attr:`files` properties.

        :param name: Name of the internal cached attribute.
        :param storage: Storage class used for the data.
        Nzan input stream is defined)r   AttributeErrorr;   setattr)rM   r8   ZstoragerU   r1   r1   r2   	_get_form  s    	zEnvironBuilder._get_formc             C   s   d |  _  t |  | |  d S)zCommon behavior for setting the :attr:`form` and
        :attr:`files` properties.

        :param name: Name of the internal cached attribute.
        :param value: Value to assign to the attribute.
        N)r   r   )rM   r8   rF   r1   r1   r2   	_set_form)  s    	zEnvironBuilder._set_formc             C   s   |  j  d t  S)z$A :class:`MultiDict` of form values.r   )r   r   )rM   r1   r1   r2   r   3  s    zEnvironBuilder.formc             C   s   |  j  d |  d  S)Nr   )r   )rM   rF   r1   r1   r2   r   8  s    c             C   s   |  j  d t  S)zrA :class:`FileMultiDict` of uploaded files. Use
        :meth:`~FileMultiDict.add_file` to add new files.
        r   )r   r   )rM   r1   r1   r2   r   <  s    zEnvironBuilder.filesc             C   s   |  j  d |  d  S)Nr   )r   )rM   rF   r1   r1   r2   r   C  s    c             C   s   |  j  S)ziAn optional input stream.  If you set this it will clear
        :attr:`form` and :attr:`files`.
        )r   )rM   r1   r1   r2   r   G  s    zEnvironBuilder.input_streamc             C   s   | |  _  d  |  _ d  |  _ d  S)N)r   r   r   )rM   rF   r1   r1   r2   r   N  s    		c             C   s?   |  j  d k r8 |  j d k	 r4 t |  j d |  j Sd S|  j  S)ziThe query string.  If you set this to a string
        :attr:`args` will no longer be available.
        Nr5   r   )_query_string_argsr   r5   )rM   r1   r1   r2   rt   T  s
    zEnvironBuilder.query_stringc             C   s   | |  _  d  |  _ d  S)N)r   r   )rM   rF   r1   r1   r2   rt   _  s    	c             C   s=   |  j  d k	 r t d   |  j d k r6 t   |  _ |  j S)z(The URL arguments as :class:`MultiDict`.Nza query string is defined)r   r   r   r   )rM   r1   r1   r2   ru   d  s
    zEnvironBuilder.argsc             C   s   d  |  _  | |  _ d  S)N)r   r   )rM   rF   r1   r1   r2   ru   m  s    	c             C   s   |  j  j d d  d S)z4The server name (read-only, use :attr:`host` to set):r   r   )r   rp   )rM   r1   r1   r2   server_namer  s    zEnvironBuilder.server_namec             C   s\   |  j  j d d  } t |  d k rE | d j   rE t | d  S|  j d k rX d Sd S)z?The server port as integer (read-only, use :attr:`host` to set)r   r   r'   httpsi  P   )r   rp   r)   isdigitr?   r   )rM   piecesr1   r1   r2   server_portw  s    "zEnvironBuilder.server_portc             C   s'   y |  j    Wn t k
 r" Yn Xd  S)N)close	Exception)rM   r1   r1   r2   __del__  s    zEnvironBuilder.__del__c             C   s|   |  j  r d Sy t |  j  } Wn t k
 r: f  } Yn Xx1 | D]) } y | j   WqB t k
 rj YqB XqB Wd |  _  d S)zCloses 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.
        NT)r   r
   r   r   r   r   )rM   r   fr1   r1   r2   r     s    		zEnvironBuilder.closec          #      s    j  }   j }   j }   j } | d k	 rr | j   } | j d d  | j   } | j |  | | } n | d k r t   j   j g  } t	 | d   j
 \ } } } | d | } nW | d k rt   j d   j
 } | j d  } t |  } t |  } n	 t   } i  }	   j r;|	 j   j    f d	 d
   }
 t   j  } |	 j d   j d |
   j  d |
   j  d | d t   j  d t   j  d   j d t   j  d   j d   j d   j d   j d | d   j d   j d   j d   j  i    j! j"   } | d k	 rO| |	 d <| j# d |  | d k	 r{t |  |	 d <| j# d |  x: | j$   D], \ } } | |	 d  | j%   j& d! d"  <qW  j' r|	 j   j'  |	 S)#zReturn the built environ.

        .. versionchanged:: 0.15
            The content type and length headers are set based on
            input stream detection. Previously this only set the WSGI
            keys.
        Nr   r'   zmultipart/form-datar5   z; boundary="%s"z!application/x-www-form-urlencodedasciic                s   t  t |    j    j  S)N)r   r    r5   )x)rM   r1   r2   _path_encode  s    z0EnvironBuilder.get_environ.<locals>._path_encoder   r   r   r   ZREQUEST_URIZRAW_URIZSERVER_NAMEZSERVER_PORTZ	HTTP_HOSTZSERVER_PROTOCOLzwsgi.versionzwsgi.url_schemez
wsgi.inputzwsgi.errorszwsgi.multithreadzwsgi.multiprocesszwsgi.run_onceCONTENT_TYPEzContent-TypeCONTENT_LENGTHzContent-LengthzHTTP_%s-_)(r   r   r   r9   r@   rA   r   r   r   rI   r5   r   r4   r)   r   r}   r   r   rt   rv   r   rq   r   r>   r   r   server_protocolwsgi_versionr   ry   rz   r{   r|   rL   copysetZto_wsgi_listupperreplacer~   )rM   r   r   r   r9   Z	start_posZend_posrB   rD   resultr   r   rL   rE   rF   r1   )rM   r2   get_environ  sp    															
$	zEnvironBuilder.get_environc             C   s%   | d k r |  j  } | |  j    S)zReturns a request with the data.  If the request class is not
        specified :attr:`request_class` is used.

        :param cls: The request wrapper to use.
        N)request_classr   )rM   r   r1   r1   r2   get_request  s    	zEnvironBuilder.get_request)r   r   )%rW   rX   rY   rZ   r   r   r"   r   r   staticmethoddumpsr   rN   classmethodr   r   r   propertyrr   setterr9   r   r   r   r   r   r   r   r   rt   ru   r   r   r   r   r   r   r1   r1   r1   r2   rk      sn   MF	
	
Vrk   c               @   s   e  Z d  Z d Z d S)ClientRedirectErrorzIf a redirect loop is detected when using follow_redirects=True with
    the :cls:`Client`, then this exception is raised.
    N)rW   rX   rY   rZ   r1   r1   r1   r2   r     s   r   c               @   s   e  Z d  Z d Z d d d d d  Z d d d d d d d d d	 d
 d 	 Z d d d d  Z d d d  Z d d d  Z d d   Z	 d d   Z
 d d   Z d d   Z d d   Z d d   Z d d   Z d  d!   Z d" d#   Z d$ d%   Z d S)&Clienta  This class allows you to send requests to a wrapped application.

    The response wrapper can be a class or factory function that takes
    three arguments: app_iter, status and headers.  The default response
    wrapper just returns a tuple.

    Example::

        class ClientResponse(BaseResponse):
            ...

        client = Client(MyApplication(), response_wrapper=ClientResponse)

    The use_cookies parameter indicates whether cookies should be stored and
    sent for subsequent requests. This is True by default, but passing False
    will disable this behaviour.

    If you want to request some subdomain of your application you may set
    `allow_subdomain_redirects` to `True` as if not no external redirects
    are allowed.

    .. versionadded:: 0.5
       `use_cookies` is new in this version.  Older versions did not provide
       builtin cookie support.

    .. versionadded:: 0.14
       The `mimetype` parameter was added.

    .. versionadded:: 0.15
        The ``json`` parameter.
    NTFc             C   s=   | |  _  | |  _ | r' t   |  _ n	 d  |  _ | |  _ d  S)N)applicationresponse_wrapperr]   
cookie_jarallow_subdomain_redirects)rM   r   r   Zuse_cookiesr   r1   r1   r2   rN   !  s    			zClient.__init__r   rl   zutf-8c             C   s   |  j  d k	 s t d   t | | | | | | | |	 | d |
 	} t | d d | } d | f g } |  j  j | |  d S)zSets a cookie in the client's cookie jar.  The server name
        is required and has to match the one that is also passed to
        the open call.
        Nzcookies disabledsamesiterr   zhttp://z
Set-Cookie)r   AssertionErrorr   create_environrg   )rM   r   rE   rF   max_ageexpiresrq   domainsecurehttponlyr   r5   headerrc   rL   r1   r1   r2   
set_cookie0  s    	zClient.set_cookiec             C   s,   |  j  | | d d d d d | d | d S)z$Deletes a cookie in the test client.r   r   r   rq   r   N)r   )rM   r   rE   rq   r   r1   r1   r2   delete_cookieS  s    zClient.delete_cookiec             C   sa   |  j  d k	 r |  j  j |  t |  j | d | } |  j  d k	 r] |  j  j | | d  | S)z5Runs the wrapped WSGI app with the given environment.Nbufferedr'   )r   rd   run_wsgi_appr   rg   )rM   rc   r   rU   r1   r1   r2   r   Y  s    zClient.run_wsgi_appc             C   s  t  |  \ } } } } }	 t j | d | }
 | j d d  d j d  } |
 j j d  } | d g k r | |
 _ | |
 _ n | } | | k r | t |  d  | k r |  j s t	 d   n t	 d	   | j d
  } |
 j
 j d
  } | d t |   | k r4| t |
 j
  d  |
 _ n | |
 _ d |
 _
 t | d j d d  d  } | d k r|
 j d k rd |
 _ d |
 _ d |
 _ d |
 _ |
 j j d d  |  j } d |  _ z |  j |
 d d d | SWd | |  _ Xd S)znPerform a new request to the location given by the redirect
        response to the previous request.
        rt   r   r   r   .r   Nz-Following subdomain redirects is not enabled.z.Following external redirects is not supported.rl   3  4  HEADrm   zTransfer-Encodingas_tupleTr   >   r   r   )r   rk   r   rp   r   r   r   r)   r   RuntimeErrorr   rq   r?   rv   r   r9   r   rL   rb   r   open)rM   responsenew_locationrc   r   r   r   rq   r   r   builderZto_name_partsZfrom_name_parts
path_partsZ
root_partsstatus_codeZold_response_wrapperr1   r1   r2   resolve_redirectb  s@    				 						zClient.resolve_redirectc             O   s  | j  d d  } | j  d d  } | j  d d  } d } | r t |  d k r t | d t  r{ | d j   } n t | d t  r | d } | d k r t | |   } z | j   } Wd | j   X|  j | j   d | } g  }	 x t	 | d j
 d d  d  }
 |
 d k s(| r)P| sDx | d D] } q:W| d d } | |
 f } | |	 k rvt d   |	 j |  |  j | | | d | \ } } q W|  j d k	 r|  j |   } | r| | f S| S)a  Takes the same arguments as the :class:`EnvironBuilder` class with
        some additions:  You can provide a :class:`EnvironBuilder` or a WSGI
        environment as only argument instead of the :class:`EnvironBuilder`
        arguments and two optional keyword arguments (`as_tuple`, `buffered`)
        that change the type of the return value or the way the application is
        executed.

        .. versionchanged:: 0.5
           If a dict is provided as file in the dict for the `data` parameter
           the content type has to be called `content_type` now instead of
           `mimetype`.  This change was made for consistency with
           :class:`werkzeug.FileWrapper`.

            The `follow_redirects` parameter was added to :func:`open`.

        Additional parameters:

        :param as_tuple: Returns a tuple in the form ``(environ, result)``
        :param buffered: Set this to True to buffer the application run.
                         This will automatically close the application for
                         you as well.
        :param follow_redirects: Set this to True if the `Client` should
                                 follow HTTP redirects.
        r   Fr   follow_redirectsNr   r   -  .  /  1  3  4  r'   locationzloop detected>   r   r   r   r   r   r   )rb   r)   r:   rk   r   r   r   r   r   r?   rp   r   rP   r   r   )rM   ru   r   r   r   r   rc   r   r   Zredirect_chainr   r   r   Znew_redirect_entryr1   r1   r2   r     sH    
 
zClient.openc             O   s   d | d <|  j  | |   S)z(Like open but method is enforced to GET.rm   rv   )r   )rM   ru   kwr1   r1   r2   r     s    
z
Client.getc             O   s   d | d <|  j  | |   S)z*Like open but method is enforced to PATCH.PATCHrv   )r   )rM   ru   r   r1   r1   r2   patch  s    
zClient.patchc             O   s   d | d <|  j  | |   S)z)Like open but method is enforced to POST.POSTrv   )r   )rM   ru   r   r1   r1   r2   post  s    
zClient.postc             O   s   d | d <|  j  | |   S)z)Like open but method is enforced to HEAD.r   rv   )r   )rM   ru   r   r1   r1   r2   head  s    
zClient.headc             O   s   d | d <|  j  | |   S)z(Like open but method is enforced to PUT.PUTrv   )r   )rM   ru   r   r1   r1   r2   put  s    
z
Client.putc             O   s   d | d <|  j  | |   S)z+Like open but method is enforced to DELETE.DELETErv   )r   )rM   ru   r   r1   r1   r2   delete  s    
zClient.deletec             O   s   d | d <|  j  | |   S)z,Like open but method is enforced to OPTIONS.OPTIONSrv   )r   )rM   ru   r   r1   r1   r2   options	  s    
zClient.optionsc             O   s   d | d <|  j  | |   S)z*Like open but method is enforced to TRACE.TRACErv   )r   )rM   ru   r   r1   r1   r2   trace  s    
zClient.tracec             C   s   d |  j  j |  j f S)Nz<%s %r>)	__class__rW   r   )rM   r1   r1   r2   __repr__  s    zClient.__repr__)rW   rX   rY   rZ   rN   r   r   r   r   r   r   r   r   r  r  r  r  r	  r  r1   r1   r1   r2   r      s4   	?Jr   c           
   O   s/   t  |  |   } z | j   SWd | j   Xd S)a  Create a new WSGI environ dict based on the values passed.  The first
    parameter should be the path of the request which defaults to '/'.  The
    second one can either be an absolute path (in that case the host is
    localhost:80) or a full path to the request with scheme, netloc port and
    the path to the script.

    This accepts the same arguments as the :class:`EnvironBuilder`
    constructor.

    .. versionchanged:: 0.5
       This function is now a thin wrapper over :class:`EnvironBuilder` which
       was added in 0.5.  The `headers`, `environ_base`, `environ_overrides`
       and `charset` parameters were added.
    N)rk   r   r   )ru   r   r   r1   r1   r2   r     s    r   Fc                s	  t  |  } g   g    d    f d d  } |  | |  } t | d d  } t |  } | r z t |  } Wd | d k	 r |   Xna x" | D] }   j |   r Pq W  r t   |  } | d k	 r | | k	 r t | |  } |  d t  d  f S)a  Return a tuple in the form (app_iter, status, headers) of the
    application output.  This works best if you pass it an application that
    returns an iterator all the time.

    Sometimes applications may use the `write()` callable returned
    by the `start_response` function.  This tries to resolve such edge
    cases automatically.  But if you don't get the expected output you
    should set `buffered` to `True` which enforces buffering.

    If passed an invalid WSGI application the behavior of this function is
    undefined.  Never pass non-conforming WSGI applications to this function.

    :param app: the application to execute.
    :param buffered: set to `True` to enforce buffering.
    :return: tuple in the form ``(app_iter, status, headers)``
    Nc                s3   | d  k	 r t  |   |  | g  d  d   <  j S)N)r   rP   )statusrL   exc_info)bufferr   r1   r2   start_responseB  s    
z$run_wsgi_app.<locals>.start_responser   r   r   )r   r;   iterrh   rP   r   r#   r   )Zapprc   r   r  Zapp_rvZ
close_funcZapp_iteritemr1   )r  r   r2   r   -  s*    r   )ErZ   r<   rw   ior   	itertoolsr   r   tempfiler   r   _compatr   r	   r
   r   r   r   r   r   r   Z	_internalr   Zdatastructuresr   r   r   r   r   r   r   r   r   r   urlsr   r   r   r   r   r    utilsr!   Zwrappersr"   Zwsgir#   r$   urllib.requestr%   rf   ImportErrorurllib2http.cookiejarr&   	cookielibrI   rJ   objectrK   r[   r]   rj   rk   r   r   r   r   r   r1   r1   r1   r2   <module>
   st   K
   