a
    -=ic                  
   @   s  d dl 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-m0Z0 dd$l-m1Z1 dd%l-m2Z2 dd&l-m3Z3 dd'l4m5Z5 dd(l4m6Z6 ddl7mZ dd)l8m9Z9 dd*l:m;Z; dd+l:m<Z< ej=r0d d,l>m?Z? d d-l>m@Z@ dSejAeBejCf eDeEejFeB eBejGejHeI eEeBf d1d2d3ZJdTejAeBejCf ejFeB eBejGeBeIf d4d5d6ZKG d7d8 d8ZLG d9d: d:ZMG d;d< d<e	ZNejAeBejCf ejOejGeBejCf  d=d>d?ZPejQd@e!dAZRG dBdC dCZSG dDdE dEeTZUG dFdG dGZVejCejCdHdIdJdKZWdUdMdHeDejGejXeI eBe f dNdOdPZYG dQdR dRe9ZZdS )V    N)defaultdict)datetime)	timedelta)	CookieJar)BytesIO)chain)random)TemporaryFile)time)Request   )_get_environ)_make_encode_wrapper)_wsgi_decoding_dance)_wsgi_encoding_dance)Authorization)CallbackDict)CombinedMultiDict)EnvironHeaders)FileMultiDict)Headers)	MultiDict)dump_cookie)dump_options_header)parse_options_header)Data)Epilogue)Field)File)MultipartEncoder)Preamble)
iri_to_uri)
url_encode)url_fix)	url_parse)url_unparse)url_unquote)cached_property)get_content_type)Response)ClosingIterator)get_current_url)WSGIApplication)WSGIEnvironmentT  utf-8)datause_tempfile	thresholdboundarycharsetreturnc              	      s  |du rdt   t  }t dd |rHttd fdd}nj}t| }||t	dd	 t
| D ]\}}t|d
d}	|	durJt|dt|dd}
t|dd}|du r|
rt|
d pd}td|fg}|
du r||t||d n||t||
|d |	d}|s.q||t|dd qqvt|ts^t|}||t|t d ||t||dd qv||td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_r   F)sr5   c                    st    r | S t| }| kr. |  n6ttjt td}|   | |  |d |7 |S d S )Nzwb+T)writelentcastIObytesr	   getvalue)r6   length
new_streamZon_diskstreamr2   total_length ^/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/werkzeug/test.pywrite_binaryJ   s    

z-stream_encode_multipart.<locals>.write_binary    )r0   readfilenamenamecontent_typezapplication/octet-streamContent-Type)rI   headers)rI   rH   rL   i @  T)r0   Z	more_data)r
   r   r   r<   intr7   r   encodeZ
send_eventr    
_iter_datagetattr	mimetypes
guess_typer   r   r   r   
isinstancestrr   tellseek)r0   r1   r2   r3   r4   rE   encoderkeyvaluereaderrH   rJ   rL   chunkr>   rC   r@   rD   stream_encode_multipart5   sV    


r\   )valuesr3   r4   r5   c                 C   s"   t | d||d\}}}|| fS )zuLike `stream_encode_multipart` but returns a tuple in the form
    (``boundary``, ``data``) where data is bytes.
    F)r1   r3   r4   )r\   rG   )r]   r3   r4   rA   r>   rC   rC   rD   encode_multipart   s    r^   c                   @   sv   e Zd ZdZejeejeje	e	f  f ddddZ
e	eje	 dddZde	ejeje	  eje	 d	d
dZdS )_TestCookieHeaderszA headers adapter for cookielibNrL   r5   c                 C   s
   || _ d S NrL   selfrL   rC   rC   rD   __init__   s    z_TestCookieHeaders.__init__)rI   r5   c                 C   s6   g }|  }| jD ]\}}|  |kr|| q|S ra   )lowerrL   append)rd   rI   rL   kvrC   rC   rD   
getheaders   s    z_TestCookieHeaders.getheaders)rI   defaultr5   c                 C   s   |  |}|s|S |S ra   )rj   )rd   rI   rk   rL   rC   rC   rD   get_all   s    
z_TestCookieHeaders.get_all)N)__name__
__module____qualname____doc__r9   Unionr   ListTuplerT   re   Iterablerj   Optionalrl   rC   rC   rC   rD   r_      s   *	 r_   c                   @   sH   e Zd ZdZejeejeje	e	f  f ddddZ
ed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.
    Nr`   c                 C   s   t || _d S ra   )r_   rL   rc   rC   rC   rD   re      s    z_TestCookieResponse.__init__r5   c                 C   s   | j S ra   rb   rd   rC   rC   rD   info   s    z_TestCookieResponse.info)rm   rn   ro   rp   r9   rq   r   rr   rs   rT   re   r_   ry   rC   rC   rC   rD   rv      s   *rv   c                   @   sL   e Zd ZdZdddddZdejeejej	e
e
f  f dddd	ZdS )
_TestCookieJarzA cookielib.CookieJar modified to inject and read cookie headers from
    and to wsgi environments, and wsgi application responses.
    r-   N)environr5   c                 C   s2   dd | D }|r"d ||d< n|dd dS )zYInject the cookies as client headers into the server's wsgi
        environment.
        c                 S   s   g | ]}|j  d |j qS )=)rI   rY   ).0crC   rC   rD   
<listcomp>   rF   z._TestCookieJar.inject_wsgi.<locals>.<listcomp>z; ZHTTP_COOKIEN)joinpop)rd   r{   ZcvalsrC   rC   rD   inject_wsgi   s    z_TestCookieJar.inject_wsgi)r{   rL   r5   c                 C   s   |  t|tt| dS )zXExtract the server's set-cookie headers as cookies into the
        cookie jar.
        N)extract_cookiesrv   _UrllibRequestr+   )rd   r{   rL   rC   rC   rD   extract_wsgi   s    
z_TestCookieJar.extract_wsgi)rm   rn   ro   rp   r   r9   rq   r   rr   rs   rT   r   rC   rC   rC   rD   rz      s   rz   )r0   r5   c                 c   s^   t | tr| jddE dH  n<|  D ]2\}}t |trN|D ]}||fV  q<q&||fV  q&dS )zIterate over a mapping that might have a list of values, yielding
    all key, value pairs. Almost like iter_multi_items but only allows
    lists, not tuples, of values so tuples can be used for files.
    T)multiN)rS   r   itemslist)r0   rX   rY   ri   rC   rC   rD   rO      s    

rO   _TAnyMultiDict)boundc                   @   sl  e Zd ZU dZdZdZeZddlZe	ej
Z[eje ed< eje ed< ejeje  ed< eje ed	< eje ed
< dNeeje ejejejeef ef  eejeje  eje eje ejeje  eeeejejeejejeef  f  ejejeje eeejeejf f  ejejeejf  ejejeejf  eeje ejejeejf  ejejeejeef f  ddddZedejd dddZeejeje ejeje ef ejeje eef f ddddZ e	eeeedddZ!e"edddZ#e#j$eje ddd dZ#e"eje dd!d"Z%e%j$eje ddd#d"Z%e"eje dd$d%Z&e&j$eddd&d%Z&e"ejeef dd'd(Z'e"eje dd)d*Z(e(j$eje ddd+d*Z(eej)e* e*d,d-d.Z+eedd/d0d1Z,e"edd2d3Z-e-j$eddd4d3Z-e"edd5d6Z.e.j$eddd7d6Z.e"ejeje  dd8d9Z/e/j$ejeje  ddd:d9Z/e"edd;d<Z0e0j$eje ddd=d<Z0e"edd>d?Z1e1j$eje ddd@d?Z1e"eddAdBZ2e"eddCdDZ3dddEdFZ4dddGdHZ5dddIdJZ6dOejej)e  edKdLdMZ7dS )P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:`Response.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 string data.
    :param auth: An authorization object to use for the
        ``Authorization`` header value. A ``(username, password)`` tuple
        is a shortcut for ``Basic`` authorization.

    .. versionchanged:: 2.1
        ``CONTENT_TYPE`` and ``CONTENT_LENGTH`` are not duplicated as
        header keys in the environ.

    .. versionchanged:: 2.0
        ``REQUEST_URI`` and ``RAW_URI`` is the full raw URI including
        the query string, not only the path.

    .. versionchanged:: 2.0
        The default :attr:`request_class` is ``Request`` instead of
        ``BaseRequest``.

    .. versionadded:: 2.0
       Added the ``auth`` parameter.

    .. 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 percent-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.1)r   r   r   N_args_query_string_input_stream_form_files/GETFr/   )pathbase_urlquery_stringmethodinput_streamrJ   content_lengtherrors_streammultithreadmultiprocessrun_oncerL   r0   environ_baseenviron_overridesr4   mimetypejsonauthr5   c                 C   s  t |}|d ur$|d|v r$tdt|}|d u rF|d|v rF|j}|| _t|j| _|| _|d urvtt|||}|| _	t
|ttfr|| _n(|d u rt }nt
|tst|}|| _|| _|d u rt }nt
|tst|}|| _|d ur|| _|d u rtj}|| _|	| _|
| _|| _|| _|| _|| _|| _d| _|d ur|t
|trjt d|d |d d}| j!d|"  |d ur|d urt#d	| $|}| jd u rd
| _|rv|d urt#dt%|dr|& }t
|tr|'| j}t
|tr&t(|| _| jd u rvt)|| _nPt*|D ]F\}}t
|tt+fsRt%|dr`| ,|| n| j-.|/| q.|d ur|| _0d S )N?z6Query string is defined in the path and as an argumentFbasicr   r   )usernamepasswordr   z can't provide both json and datazapplication/jsonz#can't provide input stream and datarG   )1r   
ValueErrorr$   queryr4   r!   r   request_urir#   r   rS   r<   rT   r   r   argsr   r   rL   rJ   sysstderrr   r   r   r   r   r   r   r   closedtupler   setZ	to_header	TypeError
json_dumpshasattrrG   rN   r   r8   rO   dict_add_file_from_dataformZsetlistdefaultrg   r   )rd   r   r   r   r   r   rJ   r   r   r   r   r   rL   r0   r   r   r4   r   r   r   Zpath_sr   rX   rY   rC   rC   rD   re   g  s    









zEnvironBuilder.__init__r-   )r{   kwargsr5   c                 K   s   t t|}t|d | |d |dt|d t|d |d |d |dd	|d
d	|d |d |d |d |d}|| | f i |S )a-  Turn an environ dict back into a builder. Any extra kwargs
        override the args extracted from the environ.

        .. versionchanged:: 2.0
            Path and query values are passed through the WSGI decoding
            dance to avoid double encoding.

        .. versionadded:: 0.15
        	PATH_INFOwsgi.url_schemeHostSCRIPT_NAMEQUERY_STRINGREQUEST_METHOD
wsgi.inputrK   NContent-Lengthwsgi.errorswsgi.multithreadwsgi.multiprocesswsgi.run_once)r   r   r   r   r   rJ   r   r   r   r   r   rL   )r   r   r   _make_base_urlr   update)clsr{   r   rL   outrC   rC   rD   from_environ  s(    





zEnvironBuilder.from_environ)rX   rY   r5   c                 C   s2   t |tr | jj|g|R   n| j|| dS )z=Called in the EnvironBuilder to add files from the data dict.N)rS   r   filesZadd_file)rd   rX   rY   rC   rC   rD   r     s    
z"EnvironBuilder._add_file_from_data)schemehostscript_rootr5   c                 C   s   t | ||ddfdd S )N r   )r%   rstrip)r   r   r   rC   rC   rD   r     s    zEnvironBuilder._make_base_urlrw   c                 C   s   |  | 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   rx   rC   rC   rD   r     s    zEnvironBuilder.base_url)rY   r5   c                 C   sT   |d u rd}d}d}n"t |\}}}}}|s0|r8td|d| _|| _|| _d S )Nhttp	localhostr   z4base url must not contain a query string or fragmentr   )r$   r   r   r   r   r   )rd   rY   r   netlocr   qsanchorrC   rC   rD   r     s    c                 C   s6   | j d}|du r2| js2| jr$dS | jr.dS d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.
        rK   Nmultipart/form-data!application/x-www-form-urlencoded)rL   getr   r   r   rd   ctrC   rC   rD   rJ     s    zEnvironBuilder.content_typec                 C   s&   |d u r| j dd  n
|| j d< d S NrK   )rL   r   rd   rY   rC   rC   rD   rJ   %  s    c                 C   s    | j }|r|dd  S dS )zYThe mimetype (content type without charset etc.)

        .. versionadded:: 0.14
        ;r   N)rJ   splitstripr   rC   rC   rD   r   ,  s    zEnvironBuilder.mimetypec                 C   s   t || j| _d S ra   )r(   r4   rJ   r   rC   rC   rD   r   5  s    c                    s4   t dd fdd}t jddd }t ||S )zThe 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
        N)dr5   c                    s   t  j|  jd< d S r   )r   r   rL   )r   rx   rC   rD   	on_updateB  s    z1EnvironBuilder.mimetype_params.<locals>.on_updatezcontent-typer   r   )r   r   rL   r   )rd   r   r   rC   rx   rD   mimetype_params9  s    	zEnvironBuilder.mimetype_paramsc                 C   s   | j jdtd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.
        r   )type)rL   r   rM   rx   rC   rC   rD   r   H  s    zEnvironBuilder.content_lengthc                 C   s*   |d u r| j dd  nt|| j d< d S )Nr   )rL   r   rT   r   rC   rC   rD   r   P  s    )rI   storager5   c                 C   s:   | j durtdt| |}|du r6| }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   AttributeErrorrP   setattr)rd   rI   r   rvrC   rC   rD   	_get_formW  s    

zEnvironBuilder._get_form)rI   rY   r5   c                 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   )rd   rI   rY   rC   rC   rD   	_set_formi  s    zEnvironBuilder._set_formc                 C   s   |  dtS )z$A :class:`MultiDict` of form values.r   )r   r   rx   rC   rC   rD   r   s  s    zEnvironBuilder.formc                 C   s   |  d| d S )Nr   r   r   rC   rC   rD   r   x  s    c                 C   s   |  dtS )zrA :class:`FileMultiDict` of uploaded files. Use
        :meth:`~FileMultiDict.add_file` to add new files.
        r   )r   r   rx   rC   rC   rD   r   |  s    zEnvironBuilder.filesc                 C   s   |  d| d S )Nr   r   r   rC   rC   rD   r     s    c                 C   s   | j S )zAn optional input stream. This is mutually exclusive with
        setting :attr:`form` and :attr:`files`, setting it will clear
        those. Do not provide this if the method is not ``POST`` or
        another method that has a body.
        )r   rx   rC   rC   rD   r     s    zEnvironBuilder.input_streamc                 C   s   || _ d | _d | _d S ra   )r   r   r   r   rC   rC   rD   r     s    c                 C   s.   | j du r(| jdur$t| j| jdS dS | j S )ziThe query string.  If you set this to a string
        :attr:`args` will no longer be available.
        Nr4   r   )r   r   r"   r4   rx   rC   rC   rD   r     s
    

zEnvironBuilder.query_stringc                 C   s   || _ d | _d S ra   r   r   r   rC   rC   rD   r     s    c                 C   s*   | j durtd| jdu r$t | _| jS )z(The URL arguments as :class:`MultiDict`.Nza query string is defined)r   r   r   r   rx   rC   rC   rD   r     s
    

zEnvironBuilder.argsc                 C   s   d | _ || _d S ra   r   r   rC   rC   rD   r     s    c                 C   s   | j ddd S )z4The server name (read-only, use :attr:`host` to set):r   r   )r   r   rx   rC   rC   rD   server_name  s    zEnvironBuilder.server_namec                 C   sN   | j dd}t|dkr<zt|d W S  ty:   Y n0 | jdkrJdS dS )z?The server port as integer (read-only, use :attr:`host` to set)r   r      httpsi  P   )r   r   r8   rM   r   r   )rd   piecesrC   rC   rD   server_port  s    
zEnvironBuilder.server_portc                 C   s$   z|    W n ty   Y n0 d S ra   )close	Exceptionrx   rC   rC   rD   __del__  s    zEnvironBuilder.__del__c              	   C   sd   | j r
dS z| j }W n ty.   d}Y n0 |D ]$}z|  W q4 tyV   Y q40 q4d| _ 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.
        NrC   T)r   r   r]   r   r   r   )rd   r   frC   rC   rD   r     s    
zEnvironBuilder.closec                    s   j } j} j} j}|durP| }|dd | }|| || }np|dkrtt j j	g j
d\}}}| d| d}n6|dkrt j j
dd	}t|}t|}nt }i }	 jr|	 j ttd
 fdd}
t j j
}|	 j|
 j|
 jt j j
|| jt j j j j j| j j j  j!d  j"# }|$d |$d |dur||	d< |durt||	d< t%t&}|' D ]*\}}|d|( )dd  *| q|+ D ]\}}d,||	|< q j-r|	 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   r   r   z; boundary=""r   ascii)xr5   c                    s   t t|  j jS ra   )r   r&   r4   )r   rx   rC   rD   _path_encode  s    z0EnvironBuilder.get_environ.<locals>._path_encode)r   r   r   r   ZREQUEST_URIZRAW_URIZSERVER_NAMEZSERVER_PORTZ	HTTP_HOSTZSERVER_PROTOCOLzwsgi.versionr   r   r   r   r   r   rK   r   ZCONTENT_TYPEZCONTENT_LENGTHZHTTP_-_z, ).r   r   r   rJ   rU   rV   r\   r   r   r   r4   r"   rN   r8   r   r   r   rT   r   r   r   r   r   r   r   r   r   server_protocolwsgi_versionr   r   r   r   r   rL   copyremover   r   Zto_wsgi_listupperreplacerg   r   r   r   )rd   r   r   r   rJ   	start_posend_posr3   Zform_encodedresultr   Zraw_urirL   Zcombined_headersrX   rY   r]   rC   rx   rD   get_environ  sx    







$zEnvironBuilder.get_environ)r   r5   c                 C   s   |du r| 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  )rd   r   rC   rC   rD   get_request8  s    zEnvironBuilder.get_request)r   NNr   NNNNFFFNNNNr/   NNN)N)8rm   rn   ro   rp   r   r   r   r  r   staticmethoddumpsr   r9   ru   r   __annotations__rT   r;   r<   r   rq   MappingrM   boolr   rt   rs   Anyr   re   classmethodr   r   r   propertyr   setterrJ   r   r   r   Typer   r   r   r   r   r   r   r   r   r   r   r   r  r  rC   rC   rC   rD   r      s   
a
                   ""f$0

Xr   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)rm   rn   ro   rp   rC   rC   rC   rD   r  D  s   r  c                   @   s  e Zd ZdZd3dejejd  eedddd	Zd4e	e	e	ejej
eef  ejej
e	eeef  e	eje	 eeeje	 e	ddddZd5e	e	e	eje	 eeeje	 ddddZd6deejeje e	ef dddZd7deddddZdddejeeejddddZejejddd d!Zejejddd"d#Zejejddd$d%Zejejddd&d'Zejejddd(d)Zejejddd*d+Zejejddd,d-Zejejddd.d/Z e	d0d1d2Z!dS )8Clienta  This class allows you to send requests to a wrapped application.

    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.

    .. versionchanged:: 2.1
        Removed deprecated behavior of treating the response as a
        tuple. All data is available as properties on the returned
        response object.

    .. versionchanged:: 2.0
        ``response_wrapper`` is always a subclass of
        :class:``TestResponse``.

    .. versionchanged:: 0.5
        Added the ``use_cookies`` parameter.
    NTFr,   r)   )applicationresponse_wrapperuse_cookiesallow_subdomain_redirectsr5   c                 C   sd   || _ |d thv rt}nt|ts2tdt|fi }ttjd || _|rTt	 | _
nd | _
|| _d S )NZWrapperTestResponseTestResponse)r  r)   r  rS   r   r9   r:   r  r  rz   
cookie_jarr  )rd   r  r  r  r  rC   rC   rD   re   b  s    

zClient.__init__r   r   r/   )r   rX   rY   max_ageexpiresr   domainsecurehttponlysamesiter4   r5   c                 C   s\   | j dusJ dt||||||||	||
d
}t|d| d}d|fg}| 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)r  zhttp://)r   z
Set-Cookie)r  r   create_environr   )rd   r   rX   rY   r  r  r   r  r  r  r  r4   headerr{   rL   rC   rC   rD   
set_cookie}  s     
zClient.set_cookie)r   rX   r   r  r  r  r  r5   c                 C   s    | j ||dd|||||d	 dS )z$Deletes a cookie in the test client.r   )r  r  r   r  r  r  r  N)r!  )rd   r   rX   r   r  r  r  r  rC   rC   rD   delete_cookie  s    zClient.delete_cookier-   )r{   bufferedr5   c                 C   sF   | j dur| j | t| j||d}| j durB| j ||d  |S )zVRuns the wrapped WSGI app with the given environment.

        :meta private:
        Nr#  r   )r  r   run_wsgi_appr  r   )rd   r{   r#  r   rC   rC   rD   r%    s    

zClient.run_wsgi_appr  )responser#  r5   c                 C   sJ  t |j\}}}}}tj|jj||d}|ddd d}	|jd}
|	dgkrb||_||_	n|
}	|	|
kr|	t
|
 d |
kr| jstdntd	|d
}|jd
}|dt
| |kr|t
|jd |_n||_d|_|jdvr<|jdkrd|_|jdur"|j  d|_d|_d|_|jdd | j||dS )zPerform a new request to the location given by the redirect
        response to the previous request.

        :meta private:
        )r   r   r   r   r   .r   Nz-Following subdomain redirects is not enabled.z.Following external redirects is not supported.r   >   3  4  HEADr   zTransfer-Encodingr$  )r$   locationr   r   requestr{   r   r   r   r   r8   r  RuntimeErrorr   r   status_coder   r   r   rJ   r   rL   r   open)rd   r&  r#  r   r   r   r   r   builderZto_name_partsZfrom_name_parts
path_partsZ
root_partsrC   rC   rD   resolve_redirect  s>    




zClient.resolve_redirect)r#  follow_redirects)r   r#  r3  r   r5   c                O   sZ  d}|sXt |dkrX|d }t|tr0| }n(t|trJt| }nt|trX|}|du rt|i |}z| }W |  n
|  0 | j|j	|d}| j
|d|i}t }	g }
|s|S |jdv r>|s|  |  |j|jf}||	v rtd|j d|j d	|	| t|
|_|
| | j||d}qt|
|_||jj |S )
aC  Generate an environ dict from the given arguments, make a
        request to the application using it, and return the response.

        :param args: Passed to :class:`EnvironBuilder` to create the
            environ for the request. If a single arg is passed, it can
            be an existing :class:`EnvironBuilder` or an environ dict.
        :param buffered: Convert the iterator returned by the app into
            a list. If the iterator has a ``close()`` method, it is
            called automatically.
        :param follow_redirects: Make additional requests to follow HTTP
            redirects until a non-redirect status is returned.
            :attr:`TestResponse.history` lists the intermediate
            responses.

        .. versionchanged:: 2.1
            Removed the ``as_tuple`` parameter.

        .. versionchanged:: 2.0
            ``as_tuple`` is deprecated and will be removed in Werkzeug
            2.1. Use :attr:`TestResponse.request` and
            ``request.environ`` instead.

        .. versionchanged:: 2.0
            The request input stream is closed when calling
            ``response.close()``. Input streams for redirects are
            automatically closed.

        .. 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``
            instead of ``mimetype``. This change was made for
            consistency with :class:`werkzeug.FileWrapper`.

        .. versionchanged:: 0.5
            Added the ``follow_redirects`` parameter.
        Nr   r   r$  r,  >   i-  i.  i/  i1  r(  r)  zLoop detected: A z redirect to z was already made.)r8   rS   r   r  r   r   r   r   r%  r{   r  r   r.  Zmake_sequencer+  r  addr   historyrg   r2  call_on_closer   )rd   r#  r3  r   r   r,  argr0  r&  Z	redirectsr5  Znew_redirect_entryrC   rC   rD   r/    sL    +











zClient.open)r   kwr5   c                 O   s   d|d< | j |i |S )z1Call :meth:`open` with ``method`` set to ``GET``.r   r   r/  rd   r   r8  rC   rC   rD   r   q  s    z
Client.getc                 O   s   d|d< | j |i |S )z2Call :meth:`open` with ``method`` set to ``POST``.POSTr   r9  r:  rC   rC   rD   postv  s    zClient.postc                 O   s   d|d< | j |i |S )z1Call :meth:`open` with ``method`` set to ``PUT``.PUTr   r9  r:  rC   rC   rD   put{  s    z
Client.putc                 O   s   d|d< | j |i |S )z4Call :meth:`open` with ``method`` set to ``DELETE``.DELETEr   r9  r:  rC   rC   rD   delete  s    zClient.deletec                 O   s   d|d< | j |i |S )z3Call :meth:`open` with ``method`` set to ``PATCH``.PATCHr   r9  r:  rC   rC   rD   patch  s    zClient.patchc                 O   s   d|d< | j |i |S )z5Call :meth:`open` with ``method`` set to ``OPTIONS``.OPTIONSr   r9  r:  rC   rC   rD   options  s    zClient.optionsc                 O   s   d|d< | j |i |S )z2Call :meth:`open` with ``method`` set to ``HEAD``.r*  r   r9  r:  rC   rC   rD   head  s    zClient.headc                 O   s   d|d< | j |i |S )z3Call :meth:`open` with ``method`` set to ``TRACE``.TRACEr   r9  r:  rC   rC   rD   trace  s    zClient.tracerw   c                 C   s   dt | j d| jdS )N< >)r   rm   r  rx   rC   rC   rD   __repr__  s    zClient.__repr__)NTF)	r   NNr   NFFNr/   )r   NFFN)F)F)"rm   rn   ro   rp   r9   ru   r  r  re   rT   rq   r   rM   r   floatr!  r"  rs   rt   r<   r   r%  r2  r  r/  r   r<  r>  r@  rB  rD  rE  rG  rK  rC   rC   rC   rD   r  J  s               '       Bjr  r-   )r   r   r5   c                  O   s0   t | i |}z| W |  S |  0 d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)r   r  r   )r   r   r0  rC   rC   rD   r    s    r  Fr,   )appr{   r#  r5   c           
         s   t | }dg  d fdd	}| ||}t|dd}t|}|rtzt|}W |durr|  q|durp|  0 nH|D ]} | durx qqx rt |}|dur||urt||}\}}	||t|	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                    s4   |r&z|d  |d W d }nd }0 | |f jS )Nr   r   )with_tracebackrg   )statusrL   exc_infobufferr&  rC   rD   start_response  s    z$run_wsgi_app.<locals>.start_responser   )N)	r   r   rP   iterr   rg   r   r*   r   )
rM  r{   r#  rS  Zapp_rvZ
close_funcZapp_iteritemrO  rL   rC   rQ  rD   r%    s0    





r%  c                	       st   e Zd ZU dZdZeed< ejd ed< dZ	dej
e eeeejd  ejdd fd	d
ZeedddZ  ZS )r  a`  :class:`~werkzeug.wrappers.Response` subclass that provides extra
    information about requests made with the test :class:`Client`.

    Test client requests will always return an instance of this class.
    If a custom response class is passed to the client, it is
    subclassed along with this to support test information.

    If the test request included large files, or if the application is
    serving a file, call :meth:`close` to close any open files and
    prevent Python showing a ``ResourceWarning``.

    .. versionchanged:: 2.2
        Set the ``default_mimetype`` to None to prevent a mimetype being
        assumed if missing.

    .. versionchanged:: 2.1
        Removed deprecated behavior for treating the response instance
        as a tuple.

    .. versionadded:: 2.0
        Test client methods always return instances of this class.
    Nr,  )r  .r5  FrC   )r&  rO  rL   r,  r5  r   r5   c                    s4   t  j|||fi | || _|| _|||f| _d S ra   )superre   r,  r5  Z_compat_tuple)rd   r&  rO  rL   r,  r5  r   	__class__rC   rD   re   $  s    	zTestResponse.__init__rw   c                 C   s   | j ddS )z~The response data as text. A shortcut for
        ``response.get_data(as_text=True)``.

        .. versionadded:: 2.1
        T)Zas_text)get_datarx   rC   rC   rD   text2  s    zTestResponse.text)rC   )rm   rn   ro   rp   Zdefault_mimetyper   r	  r9   rs   Z__test__rt   r<   rT   r   r  re   r'   rZ  __classcell__rC   rC   rW  rD   r    s"   
 r  )Tr.   Nr/   )Nr/   )F)[rQ   r   typingr9   collectionsr   r   r   http.cookiejarr   ior   	itertoolsr   r   tempfiler	   r
   Zurllib.requestr   r   	_internalr   r   r   r   Zdatastructuresr   r   r   r   r   r   r   r   r   r   r   Zsansio.multipartr   r   r   r   r   r    urlsr!   r"   r#   r$   r%   r&   utilsr'   r(   Zwrappers.requestZwrappers.responser)   Zwsgir*   r+   TYPE_CHECKINGZ_typeshed.wsgir,   r-   r
  rT   r  r  rM   ru   rs   r;   r<   r\   r^   r_   rv   rz   IteratorrO   TypeVarr   r   r   r  r  r  rt   r%  r  rC   rC   rC   rD   <module>   s       Z  .    W  U H