U
    a                     @   s:  d dl Z d dl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 d dlmZmZmZ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# d dl$m%Z% d dl&m'Z'm(Z( d dl)m*Z* d dl+m,Z, d dl-m.Z. d dl/m0Z0m1Z1 d dl2m3Z3m4Z4m5Z5m6Z6 d dl7m8Z8 d dl9m:Z: d dl;m<Z<m=Z= d dl>m?Z? d dl@mAZAmBZB d dlCmDZDmEZE d dlFmGZGmHZHmIZImJZJmKZK d dlLmMZM d dlNmOZO d dlPmQZQ dZRd d! ZSd"d# ZTG d$d% d%eGZUG d&d' d'ZVG d(d) d)eVZWG d*d+ d+ZXG d,d- d-ZYG d.d/ d/ejZZ[G d0d1 d1Z\G d2d3 d3e[Z]dRd4d5Z^G d6d7 d7e\Z_G d8d9 d9e]ZZG d:d; d;Z`d<d= Zad>d? Zbd@dA ZcdBdC ZdG dDdE dEe1ZeG dFdG dGe'ZfG dHdI dIefZgG dJdK dKefZhG dLdM dMejiZjG dNdO dOe]ZkG dPdQ dQZldS )S    N)Counter)contextmanager)copy)get_close_matches)wraps)	safe_repr)	parse_qslunquote	urlencodeurljoinurlparseurlsplit
urlunparse)url2pathname)apps)settings)mail)ImproperlyConfiguredValidationError)locks)WSGIHandlerget_path_info)call_command)no_style)emit_post_migrate_signal)ThreadedWSGIServerWSGIRequestHandler)DEFAULT_DB_ALIAS
connectionconnectionstransaction)	CharField)	QueryDict)split_domain_portvalidate_host)Client)HTMLParseError
parse_html)setting_changedtemplate_rendered)CaptureQueriesContextContextListcompare_xmlmodify_settingsoverride_settings)classproperty)RemovedInDjango31Warning)serve)TestCaseTransactionTestCaseSimpleTestCaseskipIfDBFeatureskipUnlessDBFeaturec                 C   s"   | dkrg } nt | ts| g} | S )zc
    Put value into a list if it's not already one. Return an empty list if
    value is None.
    N)
isinstancelist)value r:   /home/adriano.carvalho/ftp/files/BrinquedotecaVirtual/brinquedotecavirtual/venv/lib/python3.8/site-packages/django/test/testcases.pyto_list0   s
    
r<   c              
   C   sR   zt |}W n@ tk
rL } z"d||f }| | || W 5 d }~X Y nX |S )Nz%s
%s)r'   r&   fail_formatMessage)selfhtmlZuser_msgmsgdomestandardMsgr:   r:   r;   assert_and_parse_html<   s    $rE   c                       s(   e Zd Z fddZ fddZ  ZS )_AssertNumQueriesContextc                    s   || _ || _t | d S N)	test_casenumsuper__init__)r?   rH   rI   r   	__class__r:   r;   rK   F   s    z!_AssertNumQueriesContext.__init__c                    s`   t  ||| |d k	rd S t| }| j|| jd|| jddd t| jddD f  d S )Nz:%d queries executed, %d expected
Captured queries were:
%s
c                 s   s"   | ]\}}d ||d f V  qdS )z%d. %ssqlNr:   ).0iqueryr:   r:   r;   	<genexpr>T   s    z4_AssertNumQueriesContext.__exit__.<locals>.<genexpr>   )start)	rJ   __exit__lenrH   assertEqualrI   join	enumerateZcaptured_queries)r?   exc_type	exc_value	tracebackZexecutedrL   r:   r;   rV   K   s      
z!_AssertNumQueriesContext.__exit__)__name__
__module____qualname__rK   rV   __classcell__r:   r:   rL   r;   rF   E   s   rF   c                   @   s<   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd ZdS )_AssertTemplateUsedContextc                 C   s$   || _ || _g | _g | _t | _d S rG   )rH   template_namerendered_templatesrendered_template_namesr+   context)r?   rH   rc   r:   r:   r;   rK   \   s
    z#_AssertTemplateUsedContext.__init__c                 K   s.   | j | | j|j | jt| d S rG   )rd   appendre   namerf   r   )r?   sendersignaltemplaterf   kwargsr:   r:   r;   on_template_renderc   s    z-_AssertTemplateUsedContext.on_template_renderc                 C   s   | j | jkS rG   rc   re   r?   r:   r:   r;   testh   s    z_AssertTemplateUsedContext.testc                 C   s
   d| j  S )Nz%s was not rendered.rc   ro   r:   r:   r;   messagek   s    z"_AssertTemplateUsedContext.messagec                 C   s   t | j | S rG   )r)   connectrm   ro   r:   r:   r;   	__enter__n   s    z$_AssertTemplateUsedContext.__enter__c                 C   s\   t | j |d k	rd S |  sX|  }| jrD|dd| j 7 }n|d7 }| j	| d S )Nz& Following templates were rendered: %s, z No template was rendered.)
r)   Z
disconnectrm   rp   rr   rd   rY   re   rH   r=   )r?   r[   r\   r]   rr   r:   r:   r;   rV   r   s    
z#_AssertTemplateUsedContext.__exit__N)	r^   r_   r`   rK   rm   rp   rr   rt   rV   r:   r:   r:   r;   rb   [   s   rb   c                   @   s   e Zd Zdd Zdd ZdS )_AssertTemplateNotUsedContextc                 C   s   | j | jkS rG   rn   ro   r:   r:   r;   rp      s    z"_AssertTemplateNotUsedContext.testc                 C   s
   d| j  S )Nz%s was rendered.rq   ro   r:   r:   r;   rr      s    z%_AssertTemplateNotUsedContext.messageN)r^   r_   r`   rp   rr   r:   r:   r:   r;   rv      s   rv   c                   @   s   e Zd Zdd Zdd ZdS )_DatabaseFailurec                 C   s   || _ || _d S rG   )wrappedrr   )r?   rx   rr   r:   r:   r;   rK      s    z_DatabaseFailure.__init__c                 C   s   t | jd S rG   )AssertionErrorrr   ro   r:   r:   r;   __call__   s    z_DatabaseFailure.__call__N)r^   r_   r`   rK   rz   r:   r:   r:   r;   rw      s   rw   c                   @   s   e Zd ZdZdddZdS )"_SimpleTestCaseDatabasesDescriptorzADescriptor for SimpleTestCase.allow_database_queries deprecation.Nc                 C   sL   z
|j }W n tk
r   Y n(X d|j|jf }t|t |rFthS t S )Nz`SimpleTestCase.allow_database_queries` is deprecated. Restrict the databases available during the execution of %s.%s with the `databases` attribute instead.)	allow_database_queriesAttributeErrorr_   r`   warningswarnr0   r   set)r?   instanceclsr|   rA   r:   r:   r;   __get__   s    

z*_SimpleTestCaseDatabasesDescriptor.__get__)N)r^   r_   r`   __doc__r   r:   r:   r:   r;   r{      s   r{   c                       sx  e Zd ZeZdZdZe ZdZ	ddddgZ
e fddZed	d
 Zedd Zedd Ze fddZdL fdd	Zdd Zdd Zdd Zdd ZdMdd ZdNd!d"Zd#d$ ZdOd&d'ZdPd(d)ZdQd*d+ZdRd,d-Zd.d/ ZdSd0d1ZdTd2d3Ze d4d5 Z!d6d7 Z"d8d9 Z#d:d; Z$dUd<d=Z%dVd>d?Z&dWd@dAZ'dXdBdCZ(dYdDdEZ)dZdFdGZ*d[dHdIZ+d\dJdKZ,  Z-S )]r4   NzDatabase %(operation)s to %(alias)r are not allowed in SimpleTestCase subclasses. Either subclass TestCase or TransactionTestCase to ensure proper test isolation or add %(alias)r to %(test)s.databases to silence this failure.)rs   r   )Ztemporary_connectionr   )cursorqueries)Zchunked_cursorr   c                    sP   t    | jr(tf | j| _| j  | jrDt| j| _| j  | 	  d S rG   )
rJ   
setUpClass_overridden_settingsr.   _cls_overridden_contextenable_modified_settingsr-   _cls_modified_context_add_databases_failuresr   rL   r:   r;   r      s    


zSimpleTestCase.setUpClassc                 C   sl   | j dkrttS | j D ]H}|tkrd| j| j|f }t|tt}|rX|d|d  7 }t|qt| j S )N__all__zH%s.%s.databases refers to %r which is not defined in settings.DATABASES.z Did you mean %r?r   )	databases	frozensetr   r_   r`   r   r8   r   )r   aliasrr   Zclose_matchesr:   r:   r;   _validate_databases   s    


z"SimpleTestCase._validate_databasesc                 C   sv   |   | _tD ]b}|| jkrqt| }| jD ]B\}}| jd| j| jf ||d }t||}t||t	|| q,qd S )Nz%s.%s)rp   r   	operation)
r   r   r   _disallowed_connection_methods_disallowed_database_msgr_   r`   getattrsetattrrw   )r   r   r   rh   r   rr   methodr:   r:   r;   r      s    


z&SimpleTestCase._add_databases_failuresc                 C   sJ   t D ]@}|| jkrqt | }| jD ] \}}t||}t|||j q"qd S rG   )r   r   r   r   r   rx   )r   r   r   rh   _r   r:   r:   r;   _remove_databases_failures   s    

z)SimpleTestCase._remove_databases_failuresc                    sR   |    t| dr&| j  t| d t| drD| j  t| d t   d S )Nr   r   )r   hasattrr   disabledelattrr   rJ   tearDownClassr   rL   r:   r;   r      s    





zSimpleTestCase.tearDownClassc                    s   t | | j}t | jddp$t |dd}|s^z|   W n& tk
r\   || t  Y dS X t 	| |sz| 
  W n& tk
r   || t  Y dS X dS )z
        Wrapper around default __call__ method to perform common Django test
        set up. This means that user-defined Test Cases aren't required to
        include a call to super().setUp().
        __unittest_skip__FN)r   Z_testMethodNamerM   
_pre_setup	ExceptionZaddErrorsysexc_inforJ   rz   _post_teardown)r?   resultZ
testMethodskippedrL   r:   r;   rz      s"    
zSimpleTestCase.__call__c                 C   s   |   | _g t_dS )zo
        Perform pre-test setup:
        * Create a test client.
        * Clear the mail test outbox.
        N)client_classclientr   Zoutboxro   r:   r:   r;   r     s    
zSimpleTestCase._pre_setupc                 C   s   dS )zPerform post-test things.Nr:   ro   r:   r:   r;   r      s    zSimpleTestCase._post_teardownc                 K   s
   t f |S )z
        A context manager that temporarily sets a setting and reverts to the
        original value when exiting the context.
        )r.   r?   rl   r:   r:   r;   r   $  s    zSimpleTestCase.settingsc                 K   s
   t f |S )z
        A context manager that temporarily applies changes a list setting and
        reverts back to the original value when exiting the context.
        )r-   r   r:   r:   r;   r-   +  s    zSimpleTestCase.modify_settings.      Tc              	   C   s  |r|d7 }t |dr| |j|d|j|f   | |jd d ||d|jd d |f   |jd \}}t|\}}	}
}}| |j||d|j|f   n| |j||d|j|f   |j}t|\}}	}
}}|
d	st|j	d
 |}t|j	d
 |
}
|rrt
|	\}}|r8t|tjs8td||f |jj|
t||dkd}| |j||d|
|j|f   | |||d||f   dS )a*  
        Assert that a response redirected to a specific URL and that the
        redirect URL can be loaded.

        Won't work for external links since it uses the test client to do a
        request (use fetch_redirect_response=False to check such links without
        fetching them).
        : redirect_chainzHResponse didn't redirect as expected: Response code was %d (expected %d)r   rT   zPInitial response didn't redirect as expected: Response code was %d (expected %d)zNResponse didn't redirect as expected: Final Response code was %d (expected %d)/Z	PATH_INFOzThe test client is unable to fetch remote URLs (got %s). If the host is served by Django, add '%s' to ALLOWED_HOSTS. Otherwise, use assertRedirects(..., fetch_redirect_response=False).https)securezKCouldn't retrieve redirection page '%s': response code was %d (expected %d)z*Response redirected to '%s', expected '%s'N)r   
assertTruer   status_coderX   r   url
startswithr   requestr#   r$   r   ALLOWED_HOSTS
ValueErrorr   getr"   assertURLEqual)r?   responseZexpected_urlr   Ztarget_status_code
msg_prefixZfetch_redirect_responser   schemenetlocpathrR   fragmentdomainportZredirect_responser:   r:   r;   assertRedirects2  st    
    
 zSimpleTestCase.assertRedirectsc                 C   s.   dd }|  |||||d||f   dS )a  
        Assert that two URLs are the same, ignoring the order of query string
        parameters except for parameters with the same name.

        For example, /path/?x=1&y=2 is equal to /path/?y=2&x=1, but
        /path/?a=1&a=2 isn't equal to /path/?a=2&a=1.
        c                 S   s@   t | } t| \}}}}}}tt|}t||||t||fS )z'Sort the URL's query string parameters.)strr   sortedr   r   r
   )r   r   r   r   paramsrR   r   Zquery_partsr:   r:   r;   	normalize  s    z0SimpleTestCase.assertURLEqual.<locals>.normalizezExpected '%s' to equal '%s'.N)rX   )r?   url1url2r   r   r:   r:   r;   r     s     zSimpleTestCase.assertURLEqualc           	      C   s   t |dr"t|jr"|js"|  |r.|d7 }| |j||d|j|f   |jr`d|j}n|j	}t
|trt|rt|}||j}d| }nt|}|rt| |d d}t| |d d}||}|||fS )Nrenderr   z=Couldn't retrieve content: Response code was %d (expected %d)    z'%s'z%Response's content is not valid HTML:"Second argument is not valid HTML:)r   callabler   Zis_renderedrX   r   Z	streamingrY   Zstreaming_contentcontentr7   bytesr   decodecharsetreprrE   count)	r?   r   textr   r   r@   r   	text_repr
real_countr:   r:   r;   _assert_contains  s0     

zSimpleTestCase._assert_containsFc           	   	   C   sZ   |  |||||\}}}|dk	r>| |||d|||f   n| |dk|d|   dS )ao  
        Assert that a response indicates that some content was retrieved
        successfully, (i.e., the HTTP status code was as expected) and that
        ``text`` occurs ``count`` times in the content of the response.
        If ``count`` is None, the count doesn't matter - the assertion is true
        if the text occurs at least once in the response.
        Nz2Found %d instances of %s in response (expected %d)r   zCouldn't find %s in response)r   rX   r   )	r?   r   r   r   r   r   r@   r   r   r:   r:   r;   assertContains  s        
 zSimpleTestCase.assertContainsc                 C   s2   |  |||||\}}}| |d|d|   dS )z
        Assert that a response indicates that some content was retrieved
        successfully, (i.e., the HTTP status code was as expected) and that
        ``text`` doesn't occurs in the content of the response.
        r   zResponse should not contain %sN)r   rX   )r?   r   r   r   r   r@   r   r   r:   r:   r;   assertNotContains  s        
z SimpleTestCase.assertNotContainsc                 C   s6  |r|d7 }t |j}|s(| |d  t |}d}t|D ]\}}	||	krNq<d}|D ]}
|r||	| jkr|	| j| }| |
|k|d||||
t|f   n@||	| jkr| |d|||f   n| |d|||f   qV|	|  }| |
|k|d|||
|pd	f   qVq<|s2| |d
|   dS )zd
        Assert that a form used to render the response has a specific field
        error.
        r   8Response did not use any contexts to render the responseFTz]The field '%s' on form '%s' in context %d does not contain the error '%s' (actual errors: %s)z<The field '%s' on form '%s' in context %d contains no errorsz;The form '%s' in context %d does not contain the field '%s'zYThe form '%s' in context %d does not contain the non-field error '%s' (actual errors: %s)nonez1The form '%s' was not used to render the responseN)	r<   rf   r=   rZ   errorsr   r   fieldsnon_field_errors)r?   r   formfieldr   r   contextsZ
found_formrQ   rf   errfield_errorsr   r:   r:   r;   assertFormError  sR    
zSimpleTestCase.assertFormErrorc                 C   s  |r|d7 }t |j}|s(| |d  t |}d}t|D ]t\}	}
||
krPq<d}|D ]V}|dk	r||
| j| jkr|
| j| j| }| ||k|d||||	|t|f   nJ||
| j| jkr| |d||||	f   n| |d|||	|f   qX|dk	rf|
| j| 	 }| 
| |d	|||	f   | ||k|d
|||	|t|f   qX|
|  }| 
| |d||	f   | ||k|d||	|t|f   qXq<|s| |d|   dS )a]  
        Assert that a formset used to render the response has a specific error.

        For field errors, specify the ``form_index`` and the ``field``.
        For non-field errors, specify the ``form_index`` and the ``field`` as
        None.
        For non-form errors, specify ``form_index`` as None and the ``field``
        as None.
        r   r   FTNziThe field '%s' on formset '%s', form %d in context %d does not contain the error '%s' (actual errors: %s)zHThe field '%s' on formset '%s', form %d in context %d contains no errorszGThe formset '%s', form %d in context %d does not contain the field '%s'zNThe formset '%s', form %d in context %d does not contain any non-field errors.zeThe formset '%s', form %d in context %d does not contain the non-field error '%s' (actual errors: %s)zDThe formset '%s' in context %d does not contain any non-form errors.z[The formset '%s' in context %d does not contain the non-form error '%s' (actual errors: %s)z4The formset '%s' was not used to render the response)r<   rf   r=   rZ   Zformsr   r   r   r   r   assertFalsenon_form_errors)r?   r   ZformsetZ
form_indexr   r   r   r   Zfound_formsetrQ   rf   r   r   r   r   r:   r:   r;   assertFormsetError
  sz    





z!SimpleTestCase.assertFormsetErrorc                 C   s   |d kr|d krt d|r$|d7 }|d k	rF|d k	rFt|dsFtdt|dr\|d krr|rr|rh|}d }|d |fS dd |jD }d ||fS )Nz7response and/or template_name argument must be providedr   	templateszsassertTemplateUsed() and assertTemplateNotUsed() are only usable on responses fetched using the Django test Client.c                 S   s   g | ]}|j d k	r|j qS rG   )rh   )rP   tr:   r:   r;   
<listcomp>o  s     
 z8SimpleTestCase._assert_template_used.<locals>.<listcomp>)	TypeErrorr   r   r   )r?   r   rc   r   template_namesr:   r:   r;   _assert_template_usedZ  s    
z$SimpleTestCase._assert_template_usedc                 C   s   |  |||\}}}|r"t| |S |s4| |d  | ||k|d|d|f   |dk	r| ||||d||||f   dS )z
        Assert that the template with the provided name was used in rendering
        the response. Also usable as context manager.
        z(No templates used to render the responsezYTemplate '%s' was not a template used to render the response. Actual template(s) used: %sru   NzZTemplate '%s' was expected to be rendered %d time(s) but was actually rendered %d time(s).)r   rb   r=   r   rY   rX   r   )r?   r   rc   r   r   context_mgr_templater   r:   r:   r;   assertTemplateUsedr  s.      

 z!SimpleTestCase.assertTemplateUsedc                 C   s>   |  |||\}}}|r"t| |S | ||k|d|   dS )z
        Assert that the template with the provided name was NOT used in
        rendering the response. Also usable as context manager.
        z=Template '%s' was used unexpectedly in rendering the responseN)r   rv   r   )r?   r   rc   r   r   r   r:   r:   r;   assertTemplateNotUsed  s      


z$SimpleTestCase.assertTemplateNotUsedc              	   c   s4   ||}|V  W 5 Q R X |  |tt|| d S rG   )ZassertInr   r   )r?   funccm_attrexpected_exceptionexpected_messagecmr:   r:   r;   _assert_raises_or_warns_cm  s    
z)SimpleTestCase._assert_raises_or_warns_cmc           	   	   O   sJ   d }|r|^}}|  ||||}|d kr,|S | ||| W 5 Q R X d S rG   )r   )	r?   r   r   r   r   argsrl   Zcallable_objr   r:   r:   r;   _assertFooMessage  s    z SimpleTestCase._assertFooMessagec                 O   s   | j | jd||f||S )ac  
        Assert that expected_message is found in the message of a raised
        exception.

        Args:
            expected_exception: Exception class expected to be raised.
            expected_message: expected error message string value.
            args: Function to be called and extra positional args.
            kwargs: Extra kwargs.
        	exception)r   assertRaises)r?   r   r   r   rl   r:   r:   r;   assertRaisesMessage  s       z"SimpleTestCase.assertRaisesMessagec                 O   s   | j | jd||f||S )zf
        Same as assertRaisesMessage but for assertWarns() instead of
        assertRaises().
        warning)r   ZassertWarns)r?   Zexpected_warningr   r   rl   r:   r:   r;   assertWarnsMessage  s       z!SimpleTestCase.assertWarnsMessagec              
   C   sh  |dkrg }|dkri }|||}|||ddi}|  D ],\}	}
| ||	|
 | ||	|
 q<|  D ]h\}	}| t}||	 W 5 Q R X | |jj| | t}||	 W 5 Q R X | |jj| qr|jd g}|jD ]F}| t}|| W 5 Q R X | |jj| | ||| qt	|t
rd|ddd | |||| dS )aO  
        Assert that a form field behaves correctly with various inputs.

        Args:
            fieldclass: the class of the field to be tested.
            valid: a dictionary mapping valid inputs to their expected
                    cleaned values.
            invalid: a dictionary mapping invalid inputs to one or more
                    raised error messages.
            field_args: the args passed to instantiate the field
            field_kwargs: the kwargs passed to instantiate the field
            empty_value: the expected clean output for inputs in empty_values
        NrequiredF      )Z
min_length
max_length)itemsrX   cleanr   r   r   messagesZerror_messagesZempty_values
issubclassr!   updateZassertIsInstance)r?   Z
fieldclassZvalidinvalidZ
field_argsZfield_kwargsZempty_valuer   optionalinputoutputr   Zcontext_managerZerror_requiredrC   r:   r:   r;   assertFieldOutput  s2    

z SimpleTestCase.assertFieldOutputc                 C   s   t | ||d}t | ||d}||krdt|dt|df }ddtt| t|  }| ||}| | 	|| dS )z
        Assert that two HTML snippets are semantically the same.
        Whitespace in most cases is ignored, and attribute ordering is not
        significant. The arguments must be valid HTML.
        !First argument is not valid HTML:r   %s != %sTrN   N)
rE   r   rY   difflibndiffr   
splitlines_truncateMessager=   r>   )r?   html1html2rA   dom1dom2rD   diffr:   r:   r;   assertHTMLEqual  s     

 
zSimpleTestCase.assertHTMLEqualc                 C   sR   t | ||d}t | ||d}||krNdt|dt|df }| | || dS )z>Assert that two HTML snippets are not semantically equivalent.r  r   %s == %sTN)rE   r   r=   r>   )r?   r  r  rA   r  r  rD   r:   r:   r;   assertHTMLNotEqual  s     z!SimpleTestCase.assertHTMLNotEqualc              	   C   sh   t | |d d}t | |d d}||}|d k	rL| |||d|||f   n| |dk|d|   d S )Nr  r   z4Found %d instances of '%s' in response (expected %d)r   zCouldn't find '%s' in response)rE   r   rX   r   )r?   needleZhaystackr   r   r   r:   r:   r;   assertInHTML  s    
 zSimpleTestCase.assertInHTMLc                 C   s   zt |}W n$ t jk
r2   | d|  Y nX t|trpzt |}W n" tk
rn   | d|  Y nX | j|||d dS )z
        Assert that the JSON fragments raw and expected_data are equal.
        Usual JSON non-significant whitespace rules apply as the heavyweight
        is delegated to the json library.
        $First argument is not valid JSON: %r%Second argument is not valid JSON: %rrA   N)jsonloadsJSONDecodeErrorr=   r7   r   r   rX   r?   rawZexpected_datarA   datar:   r:   r;   assertJSONEqual"  s    
zSimpleTestCase.assertJSONEqualc                 C   s   zt |}W n$ t jk
r2   | d|  Y nX t|trrzt |}W n$ t jk
rp   | d|  Y nX | j|||d dS )z
        Assert that the JSON fragments raw and expected_data are not equal.
        Usual JSON non-significant whitespace rules apply as the heavyweight
        is delegated to the json library.
        r  r  r   N)r!  r"  r#  r=   r7   r   ZassertNotEqualr$  r:   r:   r;   assertJSONNotEqual3  s    
z!SimpleTestCase.assertJSONNotEqualc              
   C   s   zt ||}W n< tk
rJ } zd| }| | || W 5 d}~X Y nZX |sdt|dt|df }ddt| |  }| 	||}| | || dS )z
        Assert that two XML snippets are semantically the same.
        Whitespace in most cases is ignored and attribute ordering is not
        significant. The arguments must be valid XML.
        ,First or second argument is not valid XML
%sNr  TrN   )
r,   r   r=   r>   r   rY   r  r  r  r  )r?   xml1xml2rA   r   rC   rD   r  r:   r:   r;   assertXMLEqualD  s    $zSimpleTestCase.assertXMLEqualc              
   C   s~   zt ||}W n< tk
rJ } zd| }| | || W 5 d}~X Y n0X |rzdt|dt|df }| | || dS )z
        Assert that two XML snippets are not semantically equivalent.
        Whitespace in most cases is ignored and attribute ordering is not
        significant. The arguments must be valid XML.
        r)  Nr  T)r,   r   r=   r>   r   )r?   r*  r+  rA   r   rC   rD   r:   r:   r;   assertXMLNotEqualX  s    $z SimpleTestCase.assertXMLNotEqual)N)r   r   r   T)r   )Nr   r   F)r   r   F)r   )r   )NNr   N)NNr   )NNr   )N)N)Nr   )N)N)N)N).r^   r_   r`   r%   r   r   r   r{   r   r   r   classmethodr   r   r   r   r   rz   r   r   r   r-   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r'  r(  r,  r-  ra   r:   r:   rL   r;   r4      sr   



	
	     
P



8 
P



    
.






r4   c                   @   s   e Zd ZdZdZdddZdS )'_TransactionTestCaseDatabasesDescriptorz8Descriptor for TransactionTestCase.multi_db deprecation.zx`TransactionTestCase.multi_db` is deprecated. Databases available during this test can be defined using %s.%s.databases.Nc                 C   sP   z
|j }W n tk
r   Y n,X | j|j|jf }t|t |rJtt	S t
hS rG   )multi_dbr}   rA   r_   r`   r~   r   r0   r   r   r   )r?   r   r   r0  rA   r:   r:   r;   r   p  s    
z/_TransactionTestCaseDatabasesDescriptor.__get__)N)r^   r_   r`   r   rA   r   r:   r:   r:   r;   r/  i  s   r/  c                       s   e Zd ZdZdZdZe ZdZdZ	 fddZ
edddZd	d
 Zdd Zdd Z fddZdd ZeddfddZdedddZ  ZS )r3   FNzDatabase %(operation)s to %(alias)r are not allowed in this test. Add %(alias)r to %(test)s.databases to ensure proper test isolation and silence this failure.c              	      s   t    | jdk	rXt| j tjtjj	d| jdd | j
ddD ]}tdd|d qDz|   W n@ tk
r   | jdk	rt  tjtjj	dtjdd  Y nX | j
ddD ]}t| j  qdS )	a\  
        Perform pre-test setup:
        * If the class has an 'available_apps' attribute, restrict the app
          registry to these applications, then fire the post_migrate signal --
          it must run with the correct set of applications for the test case.
        * If the class has a 'fixtures' attribute, install those fixtures.
        NINSTALLED_APPSTri   Zsettingr9   ZenterFinclude_mirrorsr   )	verbosityinteractivedb)rJ   r   available_appsr   set_available_appsr(   sendr   _wrappedrM   _databases_namesr   _fixture_setupr   unset_available_appsr1  r   Zqueries_logclearr?   db_namerL   r:   r;   r     s2    


zTransactionTestCase._pre_setupTc                    s    fddt D S )Nc                    s0   g | ](}| j krs(t| jd  d s|qS )ZTESTZMIRROR)r   r   Zsettings_dictrP   r   r   r4  r:   r;   r     s
   
 z8TransactionTestCase._databases_names.<locals>.<listcomp>r   rC  r:   rC  r;   r<    s    z$TransactionTestCase._databases_namesc              
   C   sn   t | }|jjrj|jt |j }|rjtj	|d. |
 }|D ]}|| qFW 5 Q R X W 5 Q R X d S )Nusing)r   featuresZsupports_sequence_resetopsZsequence_reset_by_name_sqlr   ZintrospectionZsequence_listr    atomicr   execute)r?   rA  connZsql_listr   rO   r:   r:   r;   _reset_sequences  s     
z$TransactionTestCase._reset_sequencesc                 C   s   | j ddD ]}| jr | | | jrrtt| drr| jd k	rFt  t| j	
t| j | jd k	rrt| j | jrtd| jd|d qd S )NFr3  _test_serialized_contentsloaddatar   r5  database)rN  )r<  reset_sequencesrL  serialized_rollbackr   r   r8  r   r>  ZcreationZdeserialize_db_from_stringrM  r9  fixturesr   r@  r:   r:   r;   r=    s    




z"TransactionTestCase._fixture_setupc                 C   s   dS )NTr:   ro   r:   r:   r;   _should_reload_connections  s    z.TransactionTestCase._should_reload_connectionsc                    sf   z4| 	  t
   |  r2t D ]}|  q$W 5 | j dk	r`t  tjtjjdtjdd X dS )a  
        Perform post-test things:
        * Flush the contents of the database to leave a clean slate. If the
          class has an 'available_apps' attribute, don't fire post_migrate.
        * Force-close the connection so the next test gets a clean cursor.
        Nr1  Fr2  )r8  r   r>  r(   r:  r   r;  rM   r1  _fixture_teardownrJ   r   rT  r   allclose)r?   rK  rL   r:   r;   r     s    


z"TransactionTestCase._post_teardownc              
   C   sP   | j ddD ]>}| jd k	p,| jo,tt| d}tddd|d| jd k	|d qd S )NFr3  rM  flushr   )r5  r6  rP  rQ  Zallow_cascadeinhibit_post_migrate)r<  r8  rR  r   r   r   )r?   rA  rY  r:   r:   r;   rU    s    
 z%TransactionTestCase._fixture_teardownc                 C   sf   t ||}|s&| jt|t||dS t|}t|dkrRt|drR|jsRtd| jt|||dS )Nr   rT   orderedzKTrying to compare non-ordered queryset against more than one ordered values)maprX   r   r8   rW   r   rZ  r   )r?   qsvaluesZ	transformrZ  rA   r  r:   r:   r;   assertQuerysetEqual  s    
z'TransactionTestCase.assertQuerysetEqualrE  c             	   O   s>   t | }t| ||}|d kr |S | ||| W 5 Q R X d S rG   )r   rF   )r?   rI   r   rF  r   rl   rK  rf   r:   r:   r;   assertNumQueries"  s    z$TransactionTestCase.assertNumQueries)T)N)r^   r_   r`   rQ  r8  rS  r/  r   r   rR  r   r.  r<  rL  r=  rT  r   rU  r   r^  r   r_  ra   r:   r:   rL   r;   r3   }  s"   
%	r3   c                 C   s0   | dkrt  ndd | D }tdd |D S )zX
    Return whether or not all (or specified) connections support
    transactions.
    Nc                 s   s   | ]}t | V  qd S rG   rD  rB  r:   r:   r;   rS   2  s     z3connections_support_transactions.<locals>.<genexpr>c                 s   s   | ]}|j jV  qd S rG   )rG  Zsupports_transactions)rP   rK  r:   r:   r;   rS   3  s     )r   rV  )aliasesZconnsr:   r:   r;    connections_support_transactions-  s    ra  c                   @   s   e Zd ZdZdZdS )_TestCaseDatabasesDescriptorz-Descriptor for TestCase.multi_db deprecation.zm`TestCase.multi_db` is deprecated. Databases available during this test can be defined using %s.%s.databases.N)r^   r_   r`   r   rA   r:   r:   r:   r;   rb  6  s   rb  c                       s   e Zd ZdZe Zedd Zedd Zedd Z	e fdd	Z
e fd
dZedd Z fddZ fddZ fddZdd Z  ZS )r2   a  
    Similar to TransactionTestCase, but use `transaction.atomic()` to achieve
    test isolation.

    In most situations, TestCase should be preferred to TransactionTestCase as
    it allows faster execution. However, there are some situations where using
    TransactionTestCase might be necessary (e.g. testing some transactional
    behavior).

    On database backends with no transaction support, TestCase behaves as
    TransactionTestCase.
    c                 C   s2   i }|   D ] }tj|d||< ||   q|S )z*Open atomic blocks for multiple databases.rE  )r<  r    rI  rt   r   atomicsrA  r:   r:   r;   _enter_atomicsM  s
    zTestCase._enter_atomicsc                 C   s6   t |  D ]$}tjd|d || ddd qdS )z5Rollback atomic blocks opened by the previous method.TrE  N)reversedr<  r    Zset_rollbackrV   rc  r:   r:   r;   _rollback_atomicsV  s    zTestCase._rollback_atomicsc                 C   s
   t | jS rG   )ra  r   r   r:   r:   r;   _databases_support_transactions]  s    z(TestCase._databases_support_transactionsc              	      s   t    |  sd S |  | _| jr~| jddD ]J}ztd| jd|d W q2 tk
rz   | 	| j | 
   Y q2X q2z|   W n* tk
r   | 	| j | 
   Y nX d S )NFr3  rN  r   rO  )rN  )rJ   r   rh  re  cls_atomicsrS  r<  r   r   rg  r   setUpTestData)r   rA  rL   r:   r;   r   a  s$    


zTestCase.setUpClassc                    s8   |   r*| | j t D ]}|  qt   d S rG   )rh  rg  ri  r   rV  rW  rJ   r   r   rK  rL   r:   r;   r   w  s
    
zTestCase.tearDownClassc                 C   s   dS )z#Load initial data for the TestCase.Nr:   r   r:   r:   r;   rj    s    zTestCase.setUpTestDatac                    s   |   rdS t  S )NF)rh  rJ   rT  ro   rL   r:   r;   rT    s    z#TestCase._should_reload_connectionsc                    s6   |   s|   t  S | jr(td|  | _d S )Nz4reset_sequences cannot be used on TestCase instances)rh  rj  rJ   r=  rQ  ry   re  rd  ro   rL   r:   r;   r=    s
    
zTestCase._fixture_setupc              	      sV   |   st  S z0t|  D ]}| t| r t| 	  q W 5 | | j X d S rG   )
rh  rJ   rU  rg  rd  rf  r<  _should_check_constraintsr   Zcheck_constraintsr@  rL   r:   r;   rU    s    
zTestCase._fixture_teardownc                 C   s   |j jo|j o| S rG   )rG  Zcan_defer_constraint_checksZneeds_rollbackZ	is_usable)r?   r   r:   r:   r;   rl    s
    z"TestCase._should_check_constraints)r^   r_   r`   r   rb  r   r.  re  rg  rh  r   r   rj  rT  r=  rU  rl  ra   r:   r:   rL   r;   r2   >  s$   





r2   c                   @   s*   e Zd ZdZdd Zdd Zd	ddZdS )
CheckConditionz1Descriptor class for deferred condition checking.c                 G   s
   || _ d S rG   )
conditions)r?   rn  r:   r:   r;   rK     s    zCheckCondition.__init__c                 C   s   | j | j||ff S rG   )rM   rn  )r?   	conditionreasonr:   r:   r;   add_condition  s    zCheckCondition.add_conditionNc                 C   sD   t dd |jD rdS | jD ] \}}| rd|_||_ dS qdS )Nc                 s   s   | ]}t |d dV  qdS )r   FN)r   )rP   baser:   r:   r;   rS     s     z)CheckCondition.__get__.<locals>.<genexpr>TF)any	__bases__rn  r   Z__unittest_skip_why__)r?   r   r   ro  rp  r:   r:   r;   r     s    zCheckCondition.__get__)N)r^   r_   r`   r   rK   rq  r   r:   r:   r:   r;   rm    s   rm  c                    s    fdd}|S )Nc                    s   t  trt tjs6t  fdd}|nh tdd }|rTtj|krbfdd j	
d}t |tr|_n|dk	rtf_S )Nc                     sf   | rLt | d tjrLtjt| d di krLtd| d | d jjtjf   r\t	| |S )Nr   r   zL%s cannot be used on %s as %s doesn't allow queries against the %r database.)
r7   unittestr2   r   r   r   r   rM   r`   ZSkipTest)r   rl   )ro  rh   rp  	test_funcr:   r;   skip_wrapper  s    
	
z6_deferredSkip.<locals>.decorator.<locals>.skip_wrapperr   c                      s   t d tjf d S )NzN%s cannot be used on %s as it doesn't allow queries against the '%s' database.)r   r   r   r:   )rh   	test_itemr:   r;   ro    s      z3_deferredSkip.<locals>.decorator.<locals>.conditionr   T)r7   typer  ru  r2   r   r   r   r   __dict__r   rm  rq  r   )rv  rw  r   skipro  rh   rp  )rv  rx  r;   	decorator  s     

	
z _deferredSkip.<locals>.decoratorr:   )ro  rp  rh   r}  r:   r|  r;   _deferredSkip  s    *r~  c                     s   t  fdddd  dS )zASkip a test if a database has at least one of the named features.c                      s   t dd  D S )Nc                 s   s   | ]}t tj|d V  qdS FNr   r   rG  rP   featurer:   r:   r;   rS     s     z4skipIfDBFeature.<locals>.<lambda>.<locals>.<genexpr>rs  r:   rG  r:   r;   <lambda>  r   z!skipIfDBFeature.<locals>.<lambda>zDatabase has feature(s) %sru   r5   r~  rY   r  r:   r  r;   r5     s
    
r5   c                     s   t  fdddd  dS )z9Skip a test unless a database has all the named features.c                      s   t dd  D  S )Nc                 s   s   | ]}t tj|d V  qdS r  r  r  r:   r:   r;   rS     s     z8skipUnlessDBFeature.<locals>.<lambda>.<locals>.<genexpr>)rV  r:   r  r:   r;   r    r   z%skipUnlessDBFeature.<locals>.<lambda>z'Database doesn't support feature(s): %sru   r6   r  r  r:   r  r;   r6     s
    
r6   c                     s   t  fdddd  dS )z<Skip a test unless a database has any of the named features.c                      s   t dd  D  S )Nc                 s   s   | ]}t tj|d V  qdS r  r  r  r:   r:   r;   rS     s     z;skipUnlessAnyDBFeature.<locals>.<lambda>.<locals>.<genexpr>r  r:   r  r:   r;   r    r   z(skipUnlessAnyDBFeature.<locals>.<lambda>z2Database doesn't support any of the feature(s): %sru   skipUnlessAnyDBFeaturer  r  r:   r  r;   r    s
    
r  c                   @   s   e Zd ZdZdd ZdS )QuietWSGIRequestHandlerz
    A WSGIRequestHandler that doesn't log to standard output any of the
    requests received, so as to not clutter the test result output.
    c                  G   s   d S rG   r:   )r   r:   r:   r;   log_message  s    z#QuietWSGIRequestHandler.log_messageN)r^   r_   r`   r   r  r:   r:   r:   r;   r    s   r  c                       sP   e Zd ZdZ fddZdd Zdd Z fdd	Zd
d Z fddZ	  Z
S )FSFilesHandlerz
    WSGI middleware that intercepts calls to a directory, as defined by one of
    the *_ROOT settings, and serves those files, publishing them under *_URL.
    c                    s"   || _ t|  | _t   d S rG   )applicationr   get_base_urlbase_urlrJ   rK   )r?   r  rL   r:   r;   rK     s    zFSFilesHandler.__init__c                 C   s   | | jd o| jd  S )z
        Check if the path should be handled. Ignore the path if:
        * the host is provided as part of the base_url
        * the request's path isn't under the media path (or equal)
        r  rT   )r   r  )r?   r   r:   r:   r;   _should_handle  s    zFSFilesHandler._should_handlec                 C   s   |t | jd d }t|S )z?Return the relative path to the file on disk for the given URL.r  N)rW   r  r   )r?   r   Zrelative_urlr:   r:   r;   	file_path  s    zFSFilesHandler.file_pathc                    sF   ddl m} | |jr:z| |W S  |k
r8   Y nX t |S )Nr   )Http404)django.httpr  r  r   r1   rJ   get_response)r?   r   r  rL   r:   r;   r  "  s    zFSFilesHandler.get_responsec                 C   s>   |  |j}tt|}|ddd}t|||  dS )N\r   )Zdocument_root)	r  r   	posixpathnormpathr	   replacelstripr1   get_base_dir)r?   r   Zos_rel_pathZfinal_rel_pathr:   r:   r;   r1   ,  s    zFSFilesHandler.servec                    s(   |  t|s| ||S t ||S rG   )r  r   r  rJ   rz   )r?   environZstart_responserL   r:   r;   rz   5  s    zFSFilesHandler.__call__)r^   r_   r`   r   rK   r  r  r  r1   rz   ra   r:   r:   rL   r;   r    s   
	r  c                   @   s    e Zd ZdZdd Zdd ZdS )_StaticFilesHandlerz
    Handler for serving static files. A private class that is meant to be used
    solely as a convenience by LiveServerThread.
    c                 C   s   t jS rG   )r   ZSTATIC_ROOTro   r:   r:   r;   r  @  s    z _StaticFilesHandler.get_base_dirc                 C   s   t jS rG   )r   Z
STATIC_URLro   r:   r:   r;   r  C  s    z _StaticFilesHandler.get_base_urlNr^   r_   r`   r   r  r  r:   r:   r:   r;   r  ;  s   r  c                   @   s    e Zd ZdZdd Zdd ZdS )_MediaFilesHandlerz
    Handler for serving the media files. A private class that is meant to be
    used solely as a convenience by LiveServerThread.
    c                 C   s   t jS rG   )r   Z
MEDIA_ROOTro   r:   r:   r;   r  L  s    z_MediaFilesHandler.get_base_dirc                 C   s   t jS rG   )r   Z	MEDIA_URLro   r:   r:   r;   r  O  s    z_MediaFilesHandler.get_base_urlNr  r:   r:   r:   r;   r  G  s   r  c                       s:   e Zd ZdZd fdd	Zdd Zdd	 Zd
d Z  ZS )LiveServerThreadzBThread for running a live http server while the tests are running.Nr   c                    s6   || _ || _t | _d | _|| _|| _t 	  d S rG   )
hostr   	threadingEventis_readyerrorstatic_handlerconnections_overriderJ   rK   )r?   r  r  r  r   rL   r:   r;   rK   V  s    
zLiveServerThread.__init__c              
   C   s   | j r"| j  D ]\}}|t|< qzzV| tt }|  | _| j	dkrX| jj
d | _	| j| | j  | j  W n2 tk
r } z|| _| j  W 5 d}~X Y nX W 5 t  X dS )zj
        Set up the live server and databases, and then loop over handling
        HTTP requests.
        r   rT   N)r  r  r   Z	close_allr  r  r   _create_serverhttpdr   server_addressZset_appr  r   serve_foreverr   r  )r?   r   rK  handlerrC   r:   r:   r;   run_  s    



 zLiveServerThread.runc                 C   s   t | j| jftddS )NF)allow_reuse_address)r   r  r   r  ro   r:   r:   r;   r  y  s    zLiveServerThread._create_serverc                 C   s*   t | dr| j  | j  |   d S )Nr  )r   r  shutdownserver_closerY   ro   r:   r:   r;   	terminate|  s    


zLiveServerThread.terminate)Nr   )	r^   r_   r`   r   rK   r  r  r  ra   r:   r:   rL   r;   r  S  s
   	r  c                       st   e Zd ZdZdZdZeZeZ	e
dd Ze
dd Ze fdd	Zed
d Zedd Ze fddZ  ZS )LiveServerTestCasea  
    Do basically the same as TransactionTestCase but also launch a live HTTP
    server in a separate thread so that the tests may use another testing
    framework, such as Selenium for example, instead of the built-in dummy
    client.
    It inherits from TransactionTestCase instead of TestCase because the
    threads don't share the same transactions (unless if using in-memory sqlite)
    and each thread needs to commit all their transactions so that the other
    thread can see the changes.
    	localhostr   c                 C   s   d| j | jjf S )Nzhttp://%s:%s)r  server_threadr   r   r:   r:   r;   live_server_url  s    z"LiveServerTestCase.live_server_urlc                 C   s   | j S rG   )r  r   r:   r:   r;   allowed_host  s    zLiveServerTestCase.allowed_hostc                    s   t    i }t D ](}|jdkr| r|  |||j< qtd| j	id| _
| j
  | || _d| j_| j  | jj  | jjr|   | jjd S )NZsqliterg   )r   T)rJ   r   r   rV  vendorZis_in_memory_dbZinc_thread_sharingr   r-   r  _live_server_modified_settingsr   _create_server_threadr  daemonrU   r  waitr  _tearDownClassInternal)r   r  rK  rL   r:   r;   r     s"    


zLiveServerTestCase.setUpClassc                 C   s   | j | j| j|| jdS )N)r  r   )server_thread_classr  r  r   )r   r  r:   r:   r;   r    s    z(LiveServerTestCase._create_server_threadc                 C   s2   t | dr.| j  | jj D ]}|  q d S )Nr  )r   r  r  r  r]  Zdec_thread_sharingrk  r:   r:   r;   r    s    

z)LiveServerTestCase._tearDownClassInternalc                    s    |    | j  t   d S rG   )r  r  r   rJ   r   r   rL   r:   r;   r     s    
z LiveServerTestCase.tearDownClass)r^   r_   r`   r   r  r   r  r  r  r  r/   r  r  r.  r   r  r  r   ra   r:   r:   rL   r;   r    s"   




r  c                       s8   e Zd ZdZdZe fddZe fddZ  ZS )SerializeMixina  
    Enforce serialization of TestCases that share a common resource.

    Define a common 'lockfile' for each set of TestCases to serialize. This
    file must exist on the filesystem.

    Place it early in the MRO in order to isolate setUpClass()/tearDownClass().
    Nc                    sD   | j d krtd| jt| j | _t| jtj t	 
  d S )NzB{}.lockfile isn't set. Set it to a unique value in the base class.)lockfiler   formatr^   open	_lockfiler   lockZLOCK_EXrJ   r   r   rL   r:   r;   r     s    
zSerializeMixin.setUpClassc                    s   t    | j  d S rG   )rJ   r   r  rW  r   rL   r:   r;   r     s    
zSerializeMixin.tearDownClass)	r^   r_   r`   r   r  r.  r   r   ra   r:   r:   rL   r;   r    s   	r  )N)mr  r!  r  r   r  ru  r~   collectionsr   
contextlibr   r   r   	functoolsr   Zunittest.utilr   urllib.parser   r	   r
   r   r   r   r   urllib.requestr   Zdjango.appsr   Zdjango.confr   Zdjango.corer   Zdjango.core.exceptionsr   r   Zdjango.core.filesr   Zdjango.core.handlers.wsgir   r   Zdjango.core.managementr   Zdjango.core.management.colorr   Zdjango.core.management.sqlr   Zdjango.core.servers.basehttpr   r   Z	django.dbr   r   r   r    Zdjango.forms.fieldsr!   r  r"   Zdjango.http.requestr#   r$   Zdjango.test.clientr%   Zdjango.test.htmlr&   r'   Zdjango.test.signalsr(   r)   Zdjango.test.utilsr*   r+   r,   r-   r.   Zdjango.utils.decoratorsr/   Zdjango.utils.deprecationr0   Zdjango.views.staticr1   r   r<   rE   rF   rb   rv   rw   r{   r2   r4   r/  r3   ra  rb  rm  r~  r5   r6   r  r  r  r  r  Threadr  r  r  r:   r:   r:   r;   <module>   s   $	'	     H 1
	f.				01P