3
(hxk                 @   s  d dl mZ 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 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(m)Z)m*Z*m+Z+ d dl,m-Z-m.Z. d dl/m0Z0 d dl1m2Z2 d dl3m4Z4m5Z5m6Z6 d-Z7dZ8de8 Z9ej:dZ;G dd de<Z=G dd  d e>Z?d!d" Z@d#d$ ZAG d%d& d&eZBd'd( ZCd)d ZDd*d ZEG d+d de>ZFG d,d deFZGdS ).    )unicode_literalsN)copy)import_module)BytesIO)settings)BaseHandler)
ISO_8859_1UTF_8WSGIRequest)got_request_exceptionrequest_finishedrequest_started)close_old_connections)HttpRequest	QueryDictSimpleCookie)TemplateDoesNotExist)signals)ContextList)resolve)six)force_bytes	force_str
uri_to_iri)SimpleLazyObjectcurry)	urlencode)is_iterable)urljoinurlparseurlsplitClientRedirectCycleErrorRequestFactoryencode_fileencode_multipartZBoUnDaRyStRiNgz multipart/form-data; boundary=%sz.*; charset=([\w\d-]+);?c                   s    e Zd ZdZ fddZ  ZS )r"   zC
    The test client has been asked to follow a redirect loop.
    c                s"   t t| j| || _|j| _d S )N)superr"   __init__last_responseredirect_chain)selfmessager(   )	__class__ 6/tmp/pip-install-q3hcpn_q/Django/django/test/client.pyr'   +   s    zRedirectCycleError.__init__)__name__
__module____qualname____doc__r'   __classcell__r-   r-   )r,   r.   r"   '   s   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 seeked 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&| j| d S )Nr   F)r   _FakePayload__content_FakePayload__lenread_startedwrite)r*   contentr-   r-   r.   r'   8   s
    zFakePayload.__init__c             C   s   | j S )N)r6   )r*   r-   r-   r.   __len__?   s    zFakePayload.__len__c             C   sZ   | j s| jjd d| _ |d kr*| jp(d}| j|ks<td| jj|}|  j|8  _|S )Nr   TzFCannot read more than the available bytes from the HTTP incoming data.)r7   r5   seekr6   AssertionErrorread)r*   	num_bytesr9   r-   r-   r.   r=   B   s    
zFakePayload.readc             C   s8   | j rtdt|}| jj| |  jt|7  _d S )Nz.Unable to write a payload after he's been read)r7   
ValueErrorr   r5   r8   r6   len)r*   r9   r-   r-   r.   r8   M   s
    zFakePayload.write)N)N)r/   r0   r1   r2   r'   r:   r=   r8   r-   r-   r-   r.   r4   1   s
   

r4   c             c   s:   zx| D ]
}|V  qW W d t jt |  t jt X d S )N)r   
disconnectr   connect)iterablecloseitemr-   r-   r.   closing_iterator_wrapperU   s    

rF   c             C   sb   d|j   kodk n  s$|j d	kr@|jr2g |_nd|_d|d< | jdkr^|jrXg |_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. Ensures
    compliance with RFC 7230, section 3.3.3.
    d         0      0zContent-LengthHEAD)rI   rJ   )status_code	streamingstreaming_contentr9   method)requestresponser-   r-   r.   conditional_content_removal_   s    $
rT   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. Uses the WSGI
    interface to compose requests, but returns the raw HttpResponse object with
    the originating WSGIRequest attached to its ``wsgi_request`` attribute.
    Tc                s   || _ tt| j|| d S )N)enforce_csrf_checksr&   rU   r'   )r*   rV   argskwargs)r,   r-   r.   r'   y   s    zClientHandler.__init__c             C   s   | j d kr| j  tjt tj| j|d tjt t|}| j	 |_
| j|}t|| ||_|jrzt|j|j|_ntjt |j  tjt |S )N)senderenviron)Z_middleware_chainZload_middlewarer   rA   r   sendr,   rB   r
   rV   Z_dont_enforce_csrf_checksZget_responserT   Zwsgi_requestrO   rF   rP   rD   r   )r*   rZ   rR   rS   r-   r-   r.   __call__}   s"    







zClientHandler.__call__)T)r/   r0   r1   r2   r'   r\   r3   r-   r-   )r,   r.   rU   s   s   rU   c             K   s:   | j dg j| d| kr$t | d< | d jt| dS )z
    Stores 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signalrY   templater^   rX   r-   r-   r.   store_rendered_templates   s    
rd   c                s   g }dd  dd }x|j  D ]\}}||rB|jt| || qt|tj rt|rxz|D ]H}||r~|jt| || q^|j fddd|  d| d	|gD  q^W q|j fd
dd|  d| d	|gD  qW |j d|  dg dj|S )a,  
    Encodes 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 )N)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_filec             3   s   | ]} |V  qd S )Nr-   ).0val)rg   r-   r.   	<genexpr>   s    z#encode_multipart.<locals>.<genexpr>z--%sz)Content-Disposition: form-data; name="%s" c             3   s   | ]} |V  qd S )Nr-   )rl   rm   )rg   r-   r.   rn      s    z--%s--rK   s   
)itemsextendr$   
isinstancer   string_typesr   join)boundarydatalinesrk   keyvaluerE   r-   )rg   r.   r%      s0    

c             C   s   dd }t |dr tjj|jnd}t |dr6|j}n|rJtj|d }nd }|d krZd}|sb|}|d|  |d	||f |d
| d||j gS )Nc             S   s   t | tjS )N)r   r   re   )rf   r-   r-   r.   rg      s    zencode_file.<locals>.to_bytesnamero   content_typer   zapplication/octet-streamz--%sz8Content-Disposition: form-data; name="%s"; filename="%s"zContent-Type: %srK   )	rh   ospathbasenamerz   r{   	mimetypes
guess_typer=   )ru   rx   filerg   filenamer{   r-   r-   r.   r$      s"    



c               @   s   e Zd Z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.
    c             K   s   || _ t | _t | _d S )N)defaultsr   cookiesr   errors)r*   r   r-   r-   r.   r'     s    zRequestFactory.__init__c             K   sp   | j jdddtdtdtdtdtdtdtd	dtdtd| jdddd}|j| j |j| |S )z5
        The base environment for a request.
        ro   z; )headersep/z	127.0.0.1GETZ
testserver80zHTTP/1.1   r   httprK   TF)ZHTTP_COOKIE	PATH_INFOZREMOTE_ADDRREQUEST_METHODZSCRIPT_NAMESERVER_NAMESERVER_PORTZSERVER_PROTOCOLzwsgi.versionzwsgi.url_schemez
wsgi.inputzwsgi.errorszwsgi.multiprocesszwsgi.multithreadzwsgi.run_once)r   r   )r   outputstrr4   r   updater   )r*   rR   rZ   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*   rR   r-   r-   r.   rR   *  s    zRequestFactory.requestc             C   sB   |t krtt|S tj|}|r,|jd}ntj}t||dS d S )Nr   )encoding)	MULTIPART_CONTENTr%   BOUNDARYCONTENT_TYPE_REmatchgroupr   re   r   )r*   rv   r{   r   charsetr-   r-   r.   _encode_data.  s    

zRequestFactory._encode_datac             C   sN   t |d }|d r,|tdt |d  7 }t|jt}tjrJ|jtS |S )N      ;)	r   r   r   encoder	   r   PY3decoder   )r*   parsedr}   r-   r-   r.   	_get_path:  s
    zRequestFactory._get_pathNFc             K   sB   |dkri n|}dt |ddi}|j| | jd|fd|i|S )zConstruct a GET request.NQUERY_STRINGT)doseqr   secure)r   r   generic)r*   r}   rv   r   extrarr-   r-   r.   getE  s    
zRequestFactory.getc             K   s8   |dkri n|}| j ||}| jd|||fd|i|S )zConstruct a POST request.NPOSTr   )r   r   )r*   r}   rv   r{   r   r   Z	post_datar-   r-   r.   postO  s    zRequestFactory.postc             K   sB   |dkri n|}dt |ddi}|j| | jd|fd|i|S )zConstruct a HEAD request.Nr   T)r   rM   r   )r   r   r   )r*   r}   rv   r   r   r   r-   r-   r.   headY  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.   tracec  s    zRequestFactory.tracero   application/octet-streamc             K   s   | j d|||fd|i|S )zConstruct an OPTIONS request.OPTIONSr   )r   )r*   r}   rv   r{   r   r   r-   r-   r.   optionsg  s    zRequestFactory.optionsc             K   s   | j d|||fd|i|S )zConstruct a PUT request.PUTr   )r   )r*   r}   rv   r{   r   r   r-   r-   r.   putm  s    zRequestFactory.putc             K   s   | j d|||fd|i|S )zConstruct a PATCH request.PATCHr   )r   )r*   r}   rv   r{   r   r   r-   r-   r.   patchs  s    zRequestFactory.patchc             K   s   | j d|||fd|i|S )zConstruct a DELETE request.DELETEr   )r   )r*   r}   rv   r{   r   r   r-   r-   r.   deletey  s    zRequestFactory.deletec       
      K   s   t t|}t|tj}| j|t||r2tdntd|rDtdntdd}|rr|jt|t|t	|d |j| |j
dst|d }	tjr|	jd	}	|	|d< | jf |S )
z%Constructs an arbitrary HTTP request.443r   httpsr   )r   r   r   zwsgi.url_scheme)CONTENT_LENGTHCONTENT_TYPEz
wsgi.inputr      z
iso-8859-1)r   r   r   r   re   r   r   r   r@   r4   r   r   r   r   rR   )
r*   rQ   r}   rv   r{   r   r   r   r   Zquery_stringr-   r-   r.   r     s$    


zRequestFactory.generic)NF)NF)F)ro   r   F)ro   r   F)ro   r   F)ro   r   F)ro   r   F)r/   r0   r1   r2   r'   r   rR   r   r   r   r   r   r   r   r   r   r   r   r   r-   r-   r-   r.   r#      s*   

	


 
 
 
 
 c                   s   e Zd ZdZd* fdd	Zdd Zdd Zee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d/ fdd	Zd0 fdd	Zd1 fdd	Zdd Zd2d d!Zd3d"d#Zd$d% Zd&d' Zd(d) Z  ZS )4r!   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.
    Fc                s&   t t| jf | t|| _d | _d S )N)r&   r!   r'   rU   handlerexc_info)r*   rV   r   )r,   r-   r.   r'     s    
zClient.__init__c             K   s   t j | _dS )zF
        Stores exceptions when they are generated by a view.
        N)sysr   )r*   rX   r-   r-   r.   store_exc_info  s    zClient.store_exc_infoc             C   sJ   t tj}| jjtj}|r(|j|jS |j }|j  |j	| jtj< |S )z8
        Obtains the current session variables.
        )
r   r   SESSION_ENGINEr   r   SESSION_COOKIE_NAMESessionStorery   savesession_key)r*   enginecookiesessionr-   r-   r.   _session  s    
zClient._sessionc       
         sR  | j f  }i }tt|}dt  }tjj||d dt  }tj| j|d zy| j	|}W n. t
k
r } z|jdkr W Y dd}~X nX | jr| j}	d| _tj|	  | |_ |_|jdg |_|jd|_t| j||_t fdd	|_|jrt|jd
kr|jd |_|jr.| jj|j |S tjj|d tj|d X dS )a  
        The master request method. Composes the environment dictionary
        and passes to the handler, returning the result of the handler.
        Assumes defaults for the query environment, which can be overridden
        using the arguments to the request.
        ztemplate-render-%s)Zdispatch_uidzrequest-exception-%s500.htmlNr]   r^   c                  s   t  d S )Nr   )r   r-   )rR   r-   r.   <lambda>  s    z Client.request.<locals>.<lambda>r   r   )r   )r   r   rd   idr   Ztemplate_renderedrB   r   r   r   r   rW   r   r   reraiseclientrR   r   r]   r^   _parse_jsonjsonr   Zresolver_matchr@   r   r   rA   )
r*   rR   rZ   rv   Zon_template_renderZ
signal_uidZexception_uidrS   er   r-   )rR   r.   rR     s<    


zClient.requestNc                s4   t t| j|f||d|}|r0| j|f|}|S )z@
        Requests a response from the server using GET.
        )rv   r   )r&   r!   r   _handle_redirects)r*   r}   rv   followr   r   rS   )r,   r-   r.   r     s
    z
Client.getc                s6   t t| j|f|||d|}|r2| j|f|}|S )zA
        Requests a response from the server using POST.
        )rv   r{   r   )r&   r!   r   r   )r*   r}   rv   r{   r   r   r   rS   )r,   r-   r.   r     s    zClient.postc                s4   t t| j|f||d|}|r0| j|f|}|S )z@
        Request a response from the server using HEAD.
        )rv   r   )r&   r!   r   r   )r*   r}   rv   r   r   r   rS   )r,   r-   r.   r   "  s
    zClient.headro   application/octet-streamc                s6   t t| j|f|||d|}|r2| j|f|}|S )zC
        Request a response from the server using OPTIONS.
        )rv   r{   r   )r&   r!   r   r   )r*   r}   rv   r{   r   r   r   rS   )r,   r-   r.   r   ,  s    zClient.optionsc                s6   t t| j|f|||d|}|r2| j|f|}|S )z:
        Send a resource to the server using PUT.
        )rv   r{   r   )r&   r!   r   r   )r*   r}   rv   r{   r   r   r   rS   )r,   r-   r.   r   8  s    z
Client.putc                s6   t t| j|f|||d|}|r2| j|f|}|S )z<
        Send a resource to the server using PATCH.
        )rv   r{   r   )r&   r!   r   r   )r*   r}   rv   r{   r   r   r   rS   )r,   r-   r.   r   D  s    zClient.patchc                s6   t t| j|f|||d|}|r2| j|f|}|S )z6
        Send a DELETE request to the server.
        )rv   r{   r   )r&   r!   r   r   )r*   r}   rv   r{   r   r   r   rS   )r,   r-   r.   r   P  s    zClient.deletec                s4   t t| j|f||d|}|r0| j|f|}|S )z5
        Send a TRACE request to the server.
        )rv   r   )r&   r!   r   r   )r*   r}   rv   r   r   r   rS   )r,   r-   r.   r   \  s    zClient.tracec             K   s0   ddl m} |f |}|r(| j| dS dS dS )z
        Sets the Factory to appear as if it has successfully logged into a site.

        Returns True if login is possible; False if the provided credentials
        are incorrect.
        r   )authenticateTFN)django.contrib.authr   _login)r*   credentialsr   userr-   r-   r.   logine  s    

zClient.loginc             C   s(   |d krt jd }||_| j|| d S )Nr   )r   ZAUTHENTICATION_BACKENDSbackendr   )r*   r   r   r-   r-   r.   force_logint  s    
zClient.force_loginc             C   s   ddl m} ttj}t }| jr,| j|_n
|j |_|||| |jj  tj	}|jj
| j|< d dtjtjppd d d}| j| 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   rR   Zsession_cookieZcookie_datar-   r-   r.   r   z  s     



zClient._loginc             C   sX   ddl m}m} t }ttj}| jr:| j|_|||_n
|j	 |_|| t
 | _dS )z
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        r   )get_userlogoutN)r   r   r   r   r   r   r   r   r   r   r   r   )r*   r   r   rR   r   r-   r-   r.   r     s    

zClient.logoutc             K   s6   d|j dkr"tdj|j dtj|jj f|S )Nzapplication/jsonzContent-Typez4Content-Type header is "{0}", not "application/json")r   r?   formatr   loadsr9   r   )r*   rS   r   r-   r-   r.   r     s
    zClient._parse_jsonc             K   s   g |_ x|jdkr|j}|j }|j||jf t|}|jrF|j|d< |jrV|j|d< |jrjt|j|d< |j	}|j
dst|jd	 |}| j|t|jfd
di|}||_ |d |dd krtd|dt|dkrtd|dqW |S )zHFollows any redirects by requesting responses from the server using GET.-  .  /  3  zwsgi.url_schemer   r   r   r   r   Fr   NzRedirect loop detected.)r(      zToo many redirects.)r   r   r   r   r   )r)   rN   urlr`   r    schemehostnameportr   r}   
startswithr   rR   r   r   queryr"   r@   )r*   rS   r   Zresponse_urlr)   r   r}   r-   r-   r.   r     s,    


zClient._handle_redirects)F)NFF)NFF)ro   r   FF)ro   r   FF)ro   r   FF)ro   r   FF)ro   FF)N)N)r/   r0   r1   r2   r'   r   r   propertyr   rR   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r3   r-   r-   )r,   r.   r!     s2   D

    	

)r!   r"   r#   r$   r%   )H
__future__r   r   r   r|   rer   r   	importlibr   ior   Zdjango.confr   Zdjango.core.handlers.baser   Zdjango.core.handlers.wsgir   r	   r
   Zdjango.core.signalsr   r   r   Z	django.dbr   Zdjango.httpr   r   r   Zdjango.templater   Zdjango.testr   Zdjango.test.utilsr   Zdjango.urlsr   Zdjango.utilsr   Zdjango.utils.encodingr   r   r   Zdjango.utils.functionalr   r   Zdjango.utils.httpr   Zdjango.utils.itercompatr   Z#django.utils.six.moves.urllib.parser   r   r    __all__r   r   compiler   	Exceptionr"   objectr4   rF   rT   rU   rd   r%   r$   r#   r!   r-   r-   r-   r.   <module>   sN   

$
11 "