U
    a(n                     @   s  d dl Z d dlZ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mZmZ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mZmZ d dlm Z  d dl!m"Z"m#Z#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l1m2Z2 dZ3dZ4de4 Z5e6dZ7e6dZ8G dd de9Z:G dd dZ;dd  Z<d!d" Z=G d#d$ d$eZ>d%d& Z?d'd( Z@d)d* ZAG d+d, d,ZBG d-d. d.eBZCdS )/    N)copy)partial)
HTTPStatus)import_module)BytesIO)unquote_to_bytesurljoinurlparseurlsplit)settings)BaseHandler)WSGIRequest)DjangoJSONEncoder)got_request_exceptionrequest_finishedrequest_started)close_old_connections)HttpRequest	QueryDictSimpleCookie)signals)ContextListresolve)force_bytes)SimpleLazyObject)	urlencode)is_iterable)ClientRedirectCycleErrorRequestFactoryencode_fileencode_multipartZBoUnDaRyStRiNgz multipart/form-data; boundary=%sz.*; charset=([\w\d-]+);?z^application\/(.+\+)?jsonc                       s    e Zd ZdZ fddZ  ZS )r   z9The test client has been asked to follow a redirect loop.c                    s   t  | || _|j| _d S N)super__init__last_responseredirect_chain)selfmessager&   	__class__ /home/adriano.carvalho/ftp/files/BrinquedotecaVirtual/brinquedotecavirtual/venv/lib/python3.8/site-packages/django/test/client.pyr%   *   s    zRedirectCycleError.__init__)__name__
__module____qualname____doc__r%   __classcell__r,   r,   r*   r-   r   (   s   r   c                   @   s4   e Zd ZdZdddZdd ZdddZd	d
 ZdS )FakePayloada  
    A wrapper around BytesIO that restricts what can be read since data from
    the network can't be sought and cannot be read outside of its content
    length. This makes sure that views can't do anything under the test client
    that wouldn't work in real life.
    Nc                 C   s*   t  | _d| _d| _|d k	r&| | d S )Nr   F)r   _FakePayload__content_FakePayload__lenread_startedwriter(   contentr,   r,   r-   r%   7   s
    zFakePayload.__init__c                 C   s   | j S r#   )r5   )r(   r,   r,   r-   __len__>   s    zFakePayload.__len__c                 C   sZ   | j s| jd d| _ |d kr*| jp(d}| j|ks<td| j|}|  j|8  _|S )Nr   TzFCannot read more than the available bytes from the HTTP incoming data.)r6   r4   seekr5   AssertionErrorread)r(   	num_bytesr9   r,   r,   r-   r=   A   s    
zFakePayload.readc                 C   s8   | j rtdt|}| j| |  jt|7  _d S )Nz.Unable to write a payload after it's been read)r6   
ValueErrorr   r4   r7   r5   lenr8   r,   r,   r-   r7   L   s
    zFakePayload.write)N)N)r.   r/   r0   r1   r%   r:   r=   r7   r,   r,   r,   r-   r3   0   s
   

r3   c              	   c   s0   z| E d H  W 5 t t |  t t X d S r#   )r   
disconnectr   connect)iterablecloser,   r,   r-   closing_iterator_wrapperT   s
    
rE   c                 C   sX   d|j   krdk s"n |j dkr6|jr0g |_nd|_| jdkrT|jrNg |_nd|_|S )z
    Simulate the behavior of most Web servers by removing the content of
    responses for HEAD requests, 1xx, 204, and 304 responses. Ensure
    compliance with RFC 7230, section 3.3.3.
    d      )   i0      HEAD)status_code	streamingstreaming_contentr9   method)requestresponser,   r,   r-   conditional_content_removal]   s    "
rQ   c                       s*   e Zd ZdZd fdd	Zdd Z  ZS )ClientHandlerz
    A HTTP Handler that can be used for testing purposes. Use the WSGI
    interface to compose requests, but return the raw HttpResponse object with
    the originating WSGIRequest attached to its ``wsgi_request`` attribute.
    Tc                    s   || _ t j|| d S r#   )enforce_csrf_checksr$   r%   )r(   rS   argskwargsr*   r,   r-   r%   v   s    zClientHandler.__init__c                 C   s   | j d kr|   tt tj| j|d tt t|}| j	 |_
| |}t|| ||_|jrzt|j|j|_ntt |  tt |S )N)senderenviron)Z_middleware_chainZload_middlewarer   rA   r   sendr+   rB   r   rS   Z_dont_enforce_csrf_checksZget_responserQ   Zwsgi_requestrL   rE   rM   rD   r   )r(   rW   rO   rP   r,   r,   r-   __call__z   s&    





 

zClientHandler.__call__)T)r.   r/   r0   r1   r%   rY   r2   r,   r,   r*   r-   rR   p   s   rR   c                 K   s:   |  dg | d| kr$t | d< | d t| dS )z
    Store templates and contexts that are rendered.

    The context is copied so that it is an accurate representation at the time
    of rendering.
    	templatescontextN)
setdefaultappendr   r   )storesignalrV   templater[   rU   r,   r,   r-   store_rendered_templates   s    
ra   c              	      s  g }dd  dd }|  D ]\}}|dkr:td| q||rV|t| || qt|tst|r|D ]H}||r|t| || ql| fddd	|  d
| d|fD  qlq| fddd	|  d
| d|fD  q| d|  dg d|S )a+  
    Encode multipart POST data from a dictionary of form values.

    The key will be used as the form data name; the value will be transmitted
    as content. If the value is a file, the contents of the file will be sent
    as an application/octet-stream; otherwise, str(value) will be sent.
    c                 S   s   t | tjS r#   r   r   DEFAULT_CHARSETsr,   r,   r-   to_bytes   s    z"encode_multipart.<locals>.to_bytesc                 S   s   t | dot| jS )Nr=   )hasattrcallabler=   )thingr,   r,   r-   is_file   s    z!encode_multipart.<locals>.is_fileNzeCannot encode None for key '%s' as POST data. Did you mean to pass an empty string or omit the value?c                 3   s   | ]} |V  qd S r#   r,   .0valrf   r,   r-   	<genexpr>   s     z#encode_multipart.<locals>.<genexpr>--%sz)Content-Disposition: form-data; name="%s" c                 3   s   | ]} |V  qd S r#   r,   rk   rn   r,   r-   ro      s     z--%s--rI   s   
)items	TypeErrorextendr!   
isinstancestrr   join)boundarydatalinesrj   keyvalueitemr,   rn   r-   r"      sB    
r"   c                 C   s   dd }t |dot|jt}|r0tj|jnd}t |drF|j}n|rZt	|d }nd }|d krjd}|pp|}|d|  |d	||f |d
| d||
 gS )Nc                 S   s   t | tjS r#   rb   rd   r,   r,   r-   rf      s    zencode_file.<locals>.to_bytesnamerq   content_typer   application/octet-streamrp   z8Content-Disposition: form-data; name="%s"; filename="%s"zContent-Type: %srI   )rg   ru   r~   rv   ospathbasenamer   	mimetypes
guess_typer=   )rx   r{   filerf   Zfile_has_string_namefilenamer   r,   r,   r-   r!      s&    



r!   c                   @   s   e Zd ZdZedddZdd Zdd Zd	d
 Zdd Z	dd Z
d%ddZdedfddZd&ddZd'ddZd(ddZd)ddZd*dd Zd+d!d"Zd,d#d$ZdS )-r    aV  
    Class that lets you create mock Request objects for use in testing.

    Usage:

    rf = RequestFactory()
    get_request = rf.get('/hello/')
    post_request = rf.post('/submit/', {'foo': 'bar'})

    Once you have a request object you can pass it to any view function,
    just as if that view had been hooked up using a URLconf.
    )json_encoderc                K   s    || _ || _t | _t | _d S r#   )r   defaultsr   cookiesr   errors)r(   r   r   r,   r,   r-   r%     s    zRequestFactory.__init__c                 K   sL   d tdd | j D dddddd	d
ddtd| jdddd| j|S )z5
        The base environment for a request.
        z; c                 s   s   | ]}d |j |jf V  qdS )z%s=%sN)r{   coded_value)rl   morselr,   r,   r-   ro     s   z/RequestFactory._base_environ.<locals>.<genexpr>/z	127.0.0.1GETrq   Z
testserver80zHTTP/1.1)   r   httprI   TF)ZHTTP_COOKIE	PATH_INFOZREMOTE_ADDRREQUEST_METHODZSCRIPT_NAMESERVER_NAMESERVER_PORTZSERVER_PROTOCOLzwsgi.versionwsgi.url_scheme
wsgi.inputzwsgi.errorszwsgi.multiprocesszwsgi.multithreadzwsgi.run_once)rw   sortedr   valuesr3   r   r   r(   rO   r,   r,   r-   _base_environ  s*    	zRequestFactory._base_environc                 K   s   t | jf |S )z#Construct a generic request object.)r   r   r   r,   r,   r-   rO   2  s    zRequestFactory.requestc                 C   sB   |t krtt|S t|}|r,|d}ntj}t||dS d S )Nr   )encoding)	MULTIPART_CONTENTr"   BOUNDARYCONTENT_TYPE_REmatchgroupr   rc   r   )r(   ry   r   r   charsetr,   r,   r-   _encode_data6  s    

zRequestFactory._encode_datac                 C   s2   t |ot|tttf}|r.tj|| jdS |S )zu
        Return encoded JSON if data is a dict, list, or tuple and content_type
        is application/json.
        )cls)	JSON_CONTENT_TYPE_REr   ru   dictlisttuplejsondumpsr   )r(   ry   r   Zshould_encoder,   r,   r-   _encode_jsonB  s    zRequestFactory._encode_jsonc                 C   s,   |j }|jr|d|j 7 }t|}|dS )N;
iso-8859-1)r   paramsr   decode)r(   parsedr   r,   r,   r-   	_get_pathJ  s
    zRequestFactory._get_pathNFc                 K   s8   |dkri n|}| j d|fd|idt|ddi|S )zConstruct a GET request.Nr   secureQUERY_STRINGTdoseqgenericr   r(   r   ry   r   extrar,   r,   r-   getU  s     
zRequestFactory.getc                 K   s@   |  |dkri n||}| ||}| jd|||fd|i|S )zConstruct a POST request.NPOSTr   )r   r   r   )r(   r   ry   r   r   r   Z	post_datar,   r,   r-   post]  s    zRequestFactory.postc                 K   s8   |dkri n|}| j d|fd|idt|ddi|S )zConstruct a HEAD request.NrJ   r   r   Tr   r   r   r,   r,   r-   headf  s     
zRequestFactory.headc                 K   s   | j d|fd|i|S )zConstruct a TRACE request.TRACEr   r   )r(   r   r   r   r,   r,   r-   tracen  s    zRequestFactory.tracerq   r   c                 K   s   | j d|||fd|i|S )zConstruct an OPTIONS request.OPTIONSr   r   r(   r   ry   r   r   r   r,   r,   r-   optionsr  s
    zRequestFactory.optionsc                 K   s(   |  ||}| jd|||fd|i|S )zConstruct a PUT request.PUTr   r   r   r   r,   r,   r-   putx  s    zRequestFactory.putc                 K   s(   |  ||}| jd|||fd|i|S )zConstruct a PATCH request.PATCHr   r   r   r,   r,   r-   patch  s    zRequestFactory.patchc                 K   s(   |  ||}| jd|||fd|i|S )zConstruct a DELETE request.DELETEr   r   r   r,   r,   r-   delete  s    zRequestFactory.deletec           
      K   s   t t|}t|tj}| |||r*dnd|r4dndd}|r^|tt||t|d || |	ds|d 
 d	}	|	|d< | jf |S )
z$Construct an arbitrary HTTP request.443r   httpsr   )r   r   r   r   )CONTENT_LENGTHCONTENT_TYPEr   r      r   )r	   rv   r   r   rc   r   updater@   r3   r   encoder   rO   )
r(   rN   r   ry   r   r   r   r   rZquery_stringr,   r,   r-   r     s$    




zRequestFactory.generic)NF)NF)F)rq   r   F)rq   r   F)rq   r   F)rq   r   F)rq   r   F)r.   r/   r0   r1   r   r%   r   rO   r   r   r   r   r   r   r   r   r   r   r   r   r   r,   r,   r,   r-   r       s:   

	

  
  
  
  
    r    c                       s   e Zd ZdZd+ fdd	Zdd Zedd	 Zd
d Zd, fdd	Z	de
ddf fdd	Zd- fdd	Zd. fdd	Zd/ fdd	Zd0 fdd	Zd1 fdd	Zd2 fdd	Zdd  Zd3d!d"Zd4d#d$Zd%d& Zd'd( Zd5d)d*Z  ZS )6r   a  
    A class that can act as a client for testing purposes.

    It allows the user to compose GET and POST requests, and
    obtain the response that the server gave to those requests.
    The server Response objects are annotated with the details
    of the contexts and templates that were rendered during the
    process of serving the request.

    Client objects are stateful - they will retain cookie (and
    thus session) details for the lifetime of the Client instance.

    This is not intended as a replacement for Twill/Selenium or
    the like - it is here to allow testing against the
    contexts and templates produced by a view, rather than the
    HTML rendered to the end-user.
    FTc                    s(   t  jf | t|| _|| _d | _d S r#   )r$   r%   rR   handlerraise_request_exceptionexc_info)r(   rS   r   r   r*   r,   r-   r%     s    
zClient.__init__c                 K   s   t  | _dS )z3Store exceptions when they are generated by a view.N)sysr   )r(   rU   r,   r,   r-   store_exc_info  s    zClient.store_exc_infoc                 C   sJ   t tj}| jtj}|r(||jS | }|  |j	| jtj< |S )z%Return the current session variables.)
r   r   SESSION_ENGINEr   r   SESSION_COOKIE_NAMESessionStorer|   savesession_key)r(   enginecookiesessionr,   r,   r-   r     s    
zClient.sessionc           
   	      s,  | j f  }i }tt|}dt  }tjj||d dt  }tj| j|d z| 
|}W 5 tjj	|d tj	|d X | j|_| jr| j\}}	}d| _| jr|	| |_ |_|dg |_|d|_t| j||_t fdd|_|jrt|jd	kr|jd
 |_|jr(| j|j |S )a	  
        The master request method. Compose the environment dictionary and pass
        to the handler, return the result of the handler. Assume defaults for
        the query environment, which can be overridden using the arguments to
        the request.
        ztemplate-render-%s)Zdispatch_uidzrequest-exception-%sNrZ   r[   c                      s   t  d S )Nr   r   r,   rO   r,   r-   <lambda>  rI   z Client.request.<locals>.<lambda>r   r   )r   r   ra   idr   Ztemplate_renderedrB   r   r   rA   r   r   r   clientrO   r   rZ   r[   _parse_jsonr   r   Zresolver_matchr@   r   r   )
r(   rO   rW   ry   Zon_template_renderZ
signal_uidZexception_uidrP   _	exc_valuer,   r   r-   rO     s8    
zClient.requestNc                    s8   t  j|f||d|}|r4| j|fd|i|}|S )z-Request a response from the server using GET.ry   r   ry   )r$   r   _handle_redirectsr(   r   ry   followr   r   rP   r*   r,   r-   r     s    z
Client.getc                    s<   t  j|f|||d|}|r8| j|f||d|}|S )z.Request a response from the server using POST.ry   r   r   ry   r   )r$   r   r   r(   r   ry   r   r   r   r   rP   r*   r,   r-   r     s    zClient.postc                    s8   t  j|f||d|}|r4| j|fd|i|}|S )z.Request a response from the server using HEAD.r   ry   )r$   r   r   r   r*   r,   r-   r     s    zClient.headrq   r   c                    s<   t  j|f|||d|}|r8| j|f||d|}|S )z1Request a response from the server using OPTIONS.r   r   )r$   r   r   r   r*   r,   r-   r     s    zClient.optionsc                    s<   t  j|f|||d|}|r8| j|f||d|}|S )z(Send a resource to the server using PUT.r   r   )r$   r   r   r   r*   r,   r-   r   "  s    z
Client.putc                    s<   t  j|f|||d|}|r8| j|f||d|}|S )z*Send a resource to the server using PATCH.r   r   )r$   r   r   r   r*   r,   r-   r   *  s    zClient.patchc                    s<   t  j|f|||d|}|r8| j|f||d|}|S )z$Send a DELETE request to the server.r   r   )r$   r   r   r   r*   r,   r-   r   2  s    zClient.deletec                    s8   t  j|f||d|}|r4| j|fd|i|}|S )z#Send a TRACE request to the server.r   ry   )r$   r   r   r   r*   r,   r-   r   :  s    zClient.tracec                 K   s0   ddl m} |f |}|r(| | dS dS dS )z
        Set the Factory to appear as if it has successfully logged into a site.

        Return True if login is possible; False if the provided credentials
        are incorrect.
        r   )authenticateTFN)django.contrib.authr   _login)r(   credentialsr   userr,   r,   r-   loginA  s    

zClient.loginc                 C   s,   dd }|d kr| }||_ | || d S )Nc                  S   s6   ddl m}  tjD ]}| |}t|dr|  S qd S )Nr   )load_backendget_user)r   r   r   ZAUTHENTICATION_BACKENDSrg   )r   backend_pathbackendr,   r,   r-   get_backendQ  s
    

z'Client.force_login.<locals>.get_backend)r   r   )r(   r   r   r   r,   r,   r-   force_loginP  s
    zClient.force_loginc                 C   s   ddl m} ttj}t }| jr,| j|_n
| |_|||| |j  tj	}|jj
| j|< d dtjtjppd d d}| j| | d S )Nr   )r   r   )zmax-ager   domainr   expires)r   r   r   r   r   r   r   r   r   r   r   r   ZSESSION_COOKIE_DOMAINZSESSION_COOKIE_SECUREr   )r(   r   r   r   r   rO   Zsession_cookieZcookie_datar,   r,   r-   r   \  s"    



zClient._loginc                 C   sX   ddl m}m} t }ttj}| jr:| j|_|||_n
|	 |_|| t
 | _dS )z<Log out the user by removing the cookies and session object.r   )r   logoutN)r   r   r   r   r   r   r   r   r   r   r   r   )r(   r   r   rO   r   r,   r,   r-   r   x  s    

zClient.logoutc                 K   sN   t |dsHt|ds.td|dtj|j	|j
f||_|jS )N_jsonzContent-Typez4Content-Type header is "{0}", not "application/json")rg   r   r   r   r?   formatr   loadsr9   r   r   r   )r(   rP   r   r,   r,   r-   r     s    
zClient._parse_jsonc                 K   s<  g |_ tjtjtjtjtjf}|j|kr8|j}|j }|	||jf t
|}|jr^|j|d< |jrn|j|d< |jrt|j|d< |j}	|	dst|jd |	}	|jtjtjfkrt| |jd  }
n| j}
t|j}d}|
|	f||dd	|}||_ |d
 |dd
 krtd|dt|dkrtd|dq|S )zY
        Follow any redirects by requesting responses from the server using GET.
        r   r   r   r   r   r   NF)ry   r   r   zRedirect loop detected.)r&      zToo many redirects.)r'   r   MOVED_PERMANENTLYFOUND	SEE_OTHERTEMPORARY_REDIRECTPERMANENT_REDIRECTrK   urlr]   r
   schemehostnameportrv   r   
startswithr   rO   getattrlowerr   r   queryr   r@   )r(   rP   ry   r   r   Zredirect_status_codesZresponse_urlr'   r  r   request_methodr,   r,   r-   r     sB    



zClient._handle_redirects)FT)NFF)NFF)rq   r   FF)rq   r   FF)rq   r   FF)rq   r   FF)rq   FF)N)N)rq   rq   )r.   r/   r0   r1   r%   r   propertyr   rO   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r2   r,   r,   r*   r-   r     sF   
3                 


r   )Dr   r   r   rer   r   	functoolsr   r   r   	importlibr   ior   urllib.parser   r   r	   r
   Zdjango.confr   Zdjango.core.handlers.baser   Zdjango.core.handlers.wsgir   Zdjango.core.serializers.jsonr   Zdjango.core.signalsr   r   r   Z	django.dbr   Zdjango.httpr   r   r   Zdjango.testr   Zdjango.test.utilsr   Zdjango.urlsr   Zdjango.utils.encodingr   Zdjango.utils.functionalr   Zdjango.utils.httpr   Zdjango.utils.itercompatr   __all__r   r   compiler   r   	Exceptionr   r3   rE   rQ   rR   ra   r"   r!   r    r   r,   r,   r,   r-   <module>   sP   

$	06 )