3
(h                 @   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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 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)m*Z*m+Z+ d dl,m-Z-m.Z.m/Z/m0Z0 d dl1m2Z2 d dl3m4Z4 d dl5m6Z6 d dl7m8Z8m9Z9 d dl:m;Z;m<Z< d dl=m>Z>m?Z?m@Z@mAZAmBZB d dlCmDZD d dlEmFZF d dlGmHZH d dlImJZJ d dlKmLZLmMZMmNZNmOZOmPZP d dlQmRZR d dlSmTZT dLZUd%d& ZVd'd( ZWG d)d* d*e>ZXG d+d, d,eYZZG d-d. d.eZZ[G d/d0 d0eYZ\G d1d" d"e
j]Z^G d2d! d!e^Z_d3d4 Z`G d5d  d e_Z]G d6d7 d7eYZad8d9 Zbd:d# Zcd;d$ Zdd<d= ZeG d>d? d?e*ZfG d@dA dAe!ZgG dBdC dCegZhG dDdE dEegZiG dFdG dGe	jjZkG dHdI dIe_ZlG dJdK dKeYZmdS )M    )unicode_literalsN)Counter)contextmanager)copy)wraps)	safe_repr)apps)settings)mail)ImproperlyConfiguredValidationError)locks)WSGIHandlerget_path_info)call_command)no_style)emit_post_migrate_signal)WSGIRequestHandler
WSGIServer)DEFAULT_DB_ALIAS
connectionconnectionstransaction)	CharField)	QueryDict)Client)HTMLParseError
parse_html)setting_changedtemplate_rendered)CaptureQueriesContextContextListcompare_xmlmodify_settingsoverride_settings)six)classproperty)RemovedInDjango20Warning)
force_text)unquoteurljoinurlparseurlsplit
urlunsplit)url2pathname)serveTestCaseTransactionTestCaseSimpleTestCaseskipIfDBFeatureskipUnlessDBFeaturec             C   s"   | dkrg } nt | ts| g} | S )ze
    Puts value into a list if it's not already one.
    Returns an empty list if value is None.
    N)
isinstancelist)value r8   9/tmp/pip-install-q3hcpn_q/Django/django/test/testcases.pyto_list5   s
    
r:   c             C   sR   yt |}W n@ tk
rL } z$d||f }| j| j|| W Y d d }~X nX |S )Nz%s
%s)r   r   fail_formatMessage)selfhtmlZuser_msgmsgdomestandardMsgr8   r8   r9   assert_and_parse_htmlA   s    $rC   c                   s(   e Zd Z fddZ fddZ  ZS )_AssertNumQueriesContextc                s    || _ || _tt| j| d S )N)	test_casenumsuperrD   __init__)r=   rE   rF   r   )	__class__r8   r9   rH   K   s    z!_AssertNumQueriesContext.__init__c          	      s\   t t| j||| |d k	r d S t| }| jj|| jd|| jdjdd | jD f  d S )Nz:%d queries executed, %d expected
Captured queries were:
%s
c             s   s   | ]}|d  V  qdS )sqlNr8   ).0queryr8   r8   r9   	<genexpr>Z   s    z4_AssertNumQueriesContext.__exit__.<locals>.<genexpr>)	rG   rD   __exit__lenrE   assertEqualrF   joinZcaptured_queries)r=   exc_type	exc_value	tracebackZexecuted)rI   r8   r9   rO   P   s    z!_AssertNumQueriesContext.__exit__)__name__
__module____qualname__rH   rO   __classcell__r8   r8   )rI   r9   rD   J   s   rD   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 )N)rE   template_namerendered_templatesrendered_template_namesr!   context)r=   rE   r[   r8   r8   r9   rH   a   s
    z#_AssertTemplateUsedContext.__init__c             K   s.   | j j| | jj|j | jjt| d S )N)r\   appendr]   namer^   r   )r=   sendersignaltemplater^   kwargsr8   r8   r9   on_template_renderh   s    z-_AssertTemplateUsedContext.on_template_renderc             C   s   | j | jkS )N)r[   r]   )r=   r8   r8   r9   testm   s    z_AssertTemplateUsedContext.testc             C   s
   d| j  S )Nz%s was not rendered.)r[   )r=   r8   r8   r9   messagep   s    z"_AssertTemplateUsedContext.messagec             C   s   t j| j | S )N)r   connectre   )r=   r8   r8   r9   	__enter__s   s    z$_AssertTemplateUsedContext.__enter__c             C   sd   t j| j |d k	rd S | j s`| j }t| jdkr@|d7 }n|ddj| j 7 }| j	j
| d S )Nr   z No template was rendered.z& Following templates were rendered: %sz, )r   Z
disconnectre   rf   rg   rP   r\   rR   r]   rE   r;   )r=   rS   rT   rU   rg   r8   r8   r9   rO   w   s    
z#_AssertTemplateUsedContext.__exit__N)	rV   rW   rX   rH   re   rf   rg   ri   rO   r8   r8   r8   r9   rZ   `   s   rZ   c               @   s   e Zd Zdd Zdd ZdS )_AssertTemplateNotUsedContextc             C   s   | j | jkS )N)r[   r]   )r=   r8   r8   r9   rf      s    z"_AssertTemplateNotUsedContext.testc             C   s
   d| j  S )Nz%s was rendered.)r[   )r=   r8   r8   r9   rg      s    z%_AssertTemplateNotUsedContext.messageN)rV   rW   rX   rf   rg   r8   r8   r8   r9   rj      s   rj   c               @   s   e Zd Zdd Zdd ZdS )_CursorFailurec             C   s   || _ || _d S )N)cls_namewrapped)r=   rl   rm   r8   r8   r9   rH      s    z_CursorFailure.__init__c             C   s   t d| j d S )NzDatabase queries aren't allowed in SimpleTestCase. Either use TestCase or TransactionTestCase to ensure proper test isolation or set %s.allow_database_queries to True to silence this failure.)AssertionErrorrl   )r=   r8   r8   r9   __call__   s    z_CursorFailure.__call__N)rV   rW   rX   rH   ro   r8   r8   r8   r9   rk      s   rk   c                   s(  e Zd ZeZdZdZdZe fddZ	e fddZ
d; fdd	Zd	d
 Zdd Zdd Zdd Zd<ddZdd Zd=ddZd>ddZd?ddZd@dd Zd!d" ZdAd#d$ZdBd%d&Zed'd( Zd)d* ZdCd+d,ZdDd-d.ZdEd/d0ZdFd1d2ZdGd3d4Z dHd5d6Z!dId7d8Z"dJd9d:Z#  Z$S )Kr2   NFc                sx   t t| j  | jr,tf | j| _| jj  | jrHt| j| _	| j	j  | j
stx$tD ]}t| }t| j|j|_qTW d S )N)rG   r2   
setUpClass_overridden_settingsr$   _cls_overridden_contextenable_modified_settingsr#   _cls_modified_contextallow_database_queriesr   rk   rV   cursor)clsaliasr   )rI   r8   r9   rp      s    


zSimpleTestCase.setUpClassc                st   | j s&xtD ]}t| }|jj|_qW t| drD| jj  t| d t| drb| jj  t| d t	t
| j  d S )Nru   rr   )rv   r   rw   rm   hasattrru   disabledelattrrr   rG   r2   tearDownClass)rx   ry   r   )rI   r8   r9   r}      s    






zSimpleTestCase.tearDownClassc                s   t | | j}t | jddp$t |dd}|s\y| j  W n$ tk
rZ   |j| tj  dS X tt	| j
| |sy| j  W n$ tk
r   |j| tj  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)getattrZ_testMethodNamerI   
_pre_setup	ExceptionZaddErrorsysexc_inforG   r2   ro   _post_teardown)r=   resultZ
testMethodZskipped)rI   r8   r9   ro      s     zSimpleTestCase.__call__c             C   s   | j  | _g t_dS )zPerforms any pre-test setup. This includes:

        * Creating a test client.
        * Clearing the mail test outbox.
        N)client_classclientr
   Zoutbox)r=   r8   r8   r9   r      s    
zSimpleTestCase._pre_setupc             C   s   dS )zPerform any post-test things.Nr8   )r=   r8   r8   r9   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=   rd   r8   r8   r9   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=   rd   r8   r8   r9   r#      s    zSimpleTestCase.modify_settings.      Tc             C   s  |dk	rt jdtdd |r$|d7 }t|dr| jt|jdk|d|j|f   | j|jd d	 ||d
|jd d	 |f   |jd \}}t	|\}	}
}}}| j|j||d|j|f   n| j|j||d|j|f   |j
}t	|\}	}
}}}|jds"t|jd |}t|jd |}|rb|jj|t||	dkd}| j|j||d||j|f   ||krt	|\}}}}}tdd|||f}||krt jdtdd |}| j|||d||f   dS )a8  Asserts that a response redirected to a specific URL, and that the
        redirect URL can be loaded.

        Note that assertRedirects won't work for external links since it uses
        TestClient to do a request (use fetch_redirect_response=False to check
        such links without fetching them).
        NzEThe host argument is deprecated and no longer used by assertRedirects   )
stacklevelz: redirect_chainr   zHResponse didn't redirect as expected: Response code was %d (expected %d)   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_INFOhttps)securezKCouldn't retrieve redirection page '%s': response code was %d (expected %d)r   zassertRedirects had to strip the scheme and domain from the expected URL, as it was always added automatically to URLs before Django 1.9. Please update your expected URLs by removing the scheme and domain.z*Response redirected to '%s', expected '%s')warningswarnr'   rz   
assertTruerP   r   status_coderQ   r,   url
startswithr*   requestr   getr   r-   )r=   responseZexpected_urlr   Ztarget_status_codehost
msg_prefixZfetch_redirect_responser   schemenetlocpathrM   fragmentZredirect_responseZe_schemeZe_netlocZe_pathZe_queryZ
e_fragmentrelative_urlr8   r8   r9   assertRedirects   s^    





zSimpleTestCase.assertRedirectsc       	      C   s   t |dr$t|jr$|j r$|j  |r0|d7 }| j|j||d|j|f   |jrbdj|j}n|j	}t
|t sx|rt||jd}|j|j}d| }nt|}|rt| |d d}t| |d d}|j|}|||fS )	Nrenderz: z=Couldn't retrieve content: Response code was %d (expected %d)    )encodingz'%s'z%Response's content is not valid HTML:z"Second argument is not valid HTML:)rz   callabler   Zis_renderedrQ   r   Z	streamingrR   Zstreaming_contentcontentr5   bytesr(   charsetdecodereprrC   count)	r=   r   textr   r   r>   r   	text_repr
real_countr8   r8   r9   _assert_containsN  s*    

zSimpleTestCase._assert_containsc       	      C   sZ   | j |||||\}}}|dk	r>| j|||d|||f   n| j|dk|d|   dS )aq  
        Asserts 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   rQ   r   )	r=   r   r   r   r   r   r>   r   r   r8   r8   r9   assertContainsm  s    zSimpleTestCase.assertContainsc             C   s2   | j |||||\}}}| j|d|d|   dS )z
        Asserts 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   rQ   )r=   r   r   r   r   r>   r   r   r8   r8   r9   assertNotContains  s    z SimpleTestCase.assertNotContainsc             C   s8  |r|d7 }t |j}|s(| j|d  t |}d}xt|D ]\}}	||	krPq>d}x|D ]}
|r||	| jkr|	| j| }| j|
|k|d||||
t|f   n@||	| jkr| j|d|||f   n| j|d|||f   qZ|	| j }| j|
|k|d|||
|f   qZW q>W |s4| j|d	|   d
S )ze
        Asserts that a form used to render the response has a specific field
        error.
        z: z8Response 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)z1The form '%s' was not used to render the responseN)	r:   r^   r;   	enumerateerrorsr   r   fieldsnon_field_errors)r=   r   formfieldr   r   contextsZ
found_formir^   errfield_errorsr   r8   r8   r9   assertFormError  sB    

zSimpleTestCase.assertFormErrorc             C   s  |r|d7 }t |j}|s(| j|d  t |}d}xt|D ]\}	}
||
krTq@d}xl|D ]b}|dk	r||
| j| jkr|
| j| j| }| j||k|d||||	|t|f   nJ||
| j| jkr| j|d||||	f   n| j|d|||	|f   q`|dk	rt|
| j| j	 }| j
t|d	k|d
|||	f   | j||k|d|||	|t|f   q`|
| j }| j
t|d	k|d||	f   | j||k|d||	|t|f   q`W q@W |s| j|d|   dS )a^  
        Asserts 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.
        z: z8Response did not use any contexts to render the responseFTNziThe 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'r   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:   r^   r;   r   Zformsr   r   r   r   r   assertFalserP   non_form_errors)r=   r   ZformsetZ
form_indexr   r   r   r   Zfound_formsetr   r^   r   r   r   r   r8   r8   r9   assertFormsetError  s^    




z!SimpleTestCase.assertFormsetErrorc             C   s   |d kr|d krt d|r$|d7 }|d k	rH|d k	rHt|d rHtdt|d s`|d krv|rv|rl|}d }|d |fS dd |jD }d ||fS )Nz7response and/or template_name argument must be providedz: 	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 )N)r`   )rL   tr8   r8   r9   
<listcomp>'  s    z8SimpleTestCase._assert_template_used.<locals>.<listcomp>)	TypeErrorrz   
ValueErrorr   )r=   r   r[   r   template_namesr8   r8   r9   _assert_template_used  s    
z$SimpleTestCase._assert_template_usedc          	   C   s   | j |||\}}}|r"t| |S |s4| j|d  | j||k|d|dj|f   |dk	r| j|j|||d|||j|f   dS )z
        Asserts 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: %sz, NzZTemplate '%s' was expected to be rendered %d time(s) but was actually rendered %d time(s).)r   rZ   r;   r   rR   rQ   r   )r=   r   r[   r   r   context_mgr_templater   r8   r8   r9   assertTemplateUsed*  s    

z!SimpleTestCase.assertTemplateUsedc             C   s>   | j |||\}}}|r"t| |S | j||k|d|   dS )z
        Asserts 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   rj   r   )r=   r   r[   r   r   r   r8   r8   r9   assertTemplateNotUsedG  s    
z$SimpleTestCase.assertTemplateNotUsedc             c   s2   | j |}|V  W d Q R X | j|t|j d S )N)assertRaisesZassertInstr	exception)r=   expected_exceptionexpected_messagecmr8   r8   r9   _assert_raises_message_cmX  s    z(SimpleTestCase._assert_raises_message_cmc          
   O   sp   |j dd}|rtjdt nt|r:|d }|dd }| j||}|dkrR|S | ||| W dQ R X dS )ah  
        Asserts that expected_message is found in the 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.
        callable_objNzYThe callable_obj kwarg is deprecated. Pass the callable as a positional argument instead.r   r   )popr   r   r'   rP   r   )r=   r   r   argsrd   r   r   r8   r8   r9   assertRaisesMessage^  s    z"SimpleTestCase.assertRaisesMessagec             C   sx  |dkrg }|dkri }|||}||t |dd}x8|j D ],\}	}
| j|j|	|
 | j|j|	|
 q>W xt|j D ]h\}	}| jt}|j|	 W dQ R X | j|jj| | jt}|j|	 W dQ R X | j|jj| qxW t|j	d g}xP|j
D ]F}| jt}|j| W dQ R X | j|jj| | j|j|| qW t|trt|jddd | j|||| dS )aP  
        Asserts 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
        NF)requiredr   r      )Z
min_length
max_length)dictitemsrQ   cleanr   r   r   messagesr(   Z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_requiredrA   r8   r8   r9   assertFieldOutput|  s2    
z SimpleTestCase.assertFieldOutputc             C   s   t | ||d}t | ||d}||krdt|dt|df }ddjtjtj|j tj|j  }| j||}| j	| j
|| dS )z
        Asserts that two HTML snippets are semantically the same.
        Whitespace in most cases is ignored, and attribute ordering is not
        significant. The passed-in arguments must be valid HTML.
        z!First argument is not valid HTML:z"Second argument is not valid HTML:z%s != %sTrJ   N)rC   r   rR   difflibndiffr%   	text_type
splitlines_truncateMessager;   r<   )r=   html1html2r?   dom1dom2rB   diffr8   r8   r9   assertHTMLEqual  s    
zSimpleTestCase.assertHTMLEqualc             C   sR   t | ||d}t | ||d}||krNdt|dt|df }| j| j|| dS )z?Asserts that two HTML snippets are not semantically equivalent.z!First argument is not valid HTML:z"Second argument is not valid HTML:z%s == %sTN)rC   r   r;   r<   )r=   r   r   r?   r   r   rB   r8   r8   r9   assertHTMLNotEqual  s    z!SimpleTestCase.assertHTMLNotEqualc             C   sh   t | |d d}t | |d d}|j|}|d k	rL| j|||d|||f   n| j|dk|d|   d S )Nz!First argument is not valid HTML:z"Second argument is not valid HTML:z4Found %d instances of '%s' in response (expected %d)r   zCouldn't find '%s' in response)rC   r   rQ   r   )r=   ZneedleZhaystackr   r   r   r8   r8   r9   assertInHTML  s    
zSimpleTestCase.assertInHTMLc             C   s   yt j|}W n" tk
r0   | jd|  Y nX t|tjrpyt j|}W n" tk
rn   | jd|  Y nX | j|||d dS )z
        Asserts 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.
        z$First argument is not valid JSON: %rz%Second argument is not valid JSON: %r)r?   N)jsonloadsr   r;   r5   r%   string_typesrQ   )r=   rawexpected_datar?   datar8   r8   r9   assertJSONEqual  s    zSimpleTestCase.assertJSONEqualc             C   s   yt j|}W n" tk
r0   | jd|  Y nX t|tjrpyt j|}W n" tk
rn   | jd|  Y nX | j|||d dS )z
        Asserts 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.
        z$First argument is not valid JSON: %rz%Second argument is not valid JSON: %r)r?   N)r   r   r   r;   r5   r%   r   ZassertNotEqual)r=   r   r   r?   r   r8   r8   r9   assertJSONNotEqual  s    z!SimpleTestCase.assertJSONNotEqualc             C   s   yt ||}W n< tk
rJ } z d| }| j| j|| W Y dd}~X nfX |sdt|dt|df }ddjtjtj	|j
 tj	|j
  }| j||}| j| j|| dS )z
        Asserts that two XML snippets are semantically the same.
        Whitespace in most cases is ignored, and attribute ordering is not
        significant. The passed-in arguments must be valid XML.
        z,First or second argument is not valid XML
%sNz%s != %sTrJ   )r"   r   r;   r<   r   rR   r   r   r%   r   r   r   )r=   xml1xml2r?   r   rA   rB   r   r8   r8   r9   assertXMLEqual  s    $zSimpleTestCase.assertXMLEqualc             C   s~   yt ||}W n< tk
rJ } z d| }| j| j|| W Y dd}~X n0X |rzdt|dt|df }| j| j|| dS )z
        Asserts that two XML snippets are not semantically equivalent.
        Whitespace in most cases is ignored, and attribute ordering is not
        significant. The passed-in arguments must be valid XML.
        z,First or second argument is not valid XML
%sNz%s == %sT)r"   r   r;   r<   r   )r=   r   r   r?   r   rA   rB   r8   r8   r9   assertXMLNotEqual  s    $z SimpleTestCase.assertXMLNotEqual)N)r   r   Nr   T)Nr   r   F)r   r   F)r   )r   )NNr   N)NNr   )NNr   )N)N)Nr   )N)N)N)N)%rV   rW   rX   r   r   rq   rt   rv   classmethodrp   r}   ro   r   r   r	   r#   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rY   r8   r8   )rI   r9   r2      sB   	  
U


8
O

 
-






c                   s   e Zd ZdZdZd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ddZ  ZS )r1   FNTc                s   t t| j  | jdk	r`tj| j tjtj	j
d| jdd x"| jddD ]}tdd|d qJW y| j  W n@ tk
r   | jdk	rtj  tjtj	j
dtjdd  Y nX dS )	ae  Performs any pre-test setup. This includes:

        * If the class has an 'available_apps' attribute, restricting the app
          registry to these applications, then firing post_migrate -- it must
          run with the correct set of applications for the test case.
        * If the class has a 'fixtures' attribute, installing these fixtures.
        NINSTALLED_APPST)ra   settingr7   enterF)include_mirrorsr   )	verbosityinteractivedb)rG   r1   r   available_appsr   set_available_appsr   sendr	   _wrappedrI   _databases_namesr   _fixture_setupr   unset_available_appsr   )r=   db_name)rI   r8   r9   r   3  s*    

zTransactionTestCase._pre_setupc                s(   t | ddr fddtD S tgS d S )NZmulti_dbFc                s(   g | ] } s t | jd  d  r|qS )ZTESTZMIRROR)r   settings_dict)rL   ry   )r  r8   r9   r   Y  s    z8TransactionTestCase._databases_names.<locals>.<listcomp>)r   r   r   )rx   r  r8   )r  r9   r
  S  s    z$TransactionTestCase._databases_namesc          
   C   sf   t | }|jjrb|jjt |jj }|rbtj	|d& |j
 }x|D ]}|j| qFW W d Q R X d S )N)using)r   featuresZsupports_sequence_resetopsZsequence_reset_by_name_sqlr   ZintrospectionZsequence_listr   atomicrw   execute)r=   r  connZsql_listrw   rK   r8   r8   r9   _reset_sequences_  s    
z$TransactionTestCase._reset_sequencesc             C   s   x| j ddD ]}| jr"| j| | jrttt| drt| jd k	rHtj  t| j	j
t| j | jd k	rttj| j | jrtd| jd|d qW d S )NF)r  _test_serialized_contentsloaddatar   )r  database)r  )r
  reset_sequencesr  serialized_rollbackrz   r   r  r   r  ZcreationZdeserialize_db_from_stringr  r  fixturesr   )r=   r  r8   r8   r9   r  j  s    




z"TransactionTestCase._fixture_setupc             C   s   dS )NTr8   )r=   r8   r8   r9   _should_reload_connections  s    z.TransactionTestCase._should_reload_connectionsc                sn   z<| j   tt| j  | j r:xtj D ]}|j  q*W W d| jdk	rht	j
  tjtjjdtjdd X dS )a"  Performs any post-test things. This includes:

        * Flushing the contents of the database, to leave a clean slate. If
          the class has an 'available_apps' attribute, post_migrate isn't fired.
        * Force-closing the connection, so the next test gets a clean cursor.
        Nr   F)ra   r   r7   r  )_fixture_teardownrG   r1   r   r  r   allcloser  r   r  r   r  r	   r	  rI   r   )r=   r  )rI   r8   r9   r     s    

z"TransactionTestCase._post_teardownc          
   C   sT   xN| j ddD ]>}| jd k	p.| jo.tt| d}tddd|d| jd k	|d qW d S )NF)r  r  flushr   )r  r  r  r  Zallow_cascadeinhibit_post_migrate)r
  r  r  rz   r   r   )r=   r  r!  r8   r8   r9   r    s    
z%TransactionTestCase._fixture_teardownc             C   sl   t jj||}|s*| jt|t||dS t|}t|dkrXt|drX|j rXt	d| jt|||dS )N)r?   r   orderedzKTrying to compare non-ordered queryset against more than one ordered values)
r%   movesmaprQ   r   r6   rP   rz   r"  r   )r=   qsvaluesZ	transformr"  r?   r   r8   r8   r9   assertQuerysetEqual  s    z'TransactionTestCase.assertQuerysetEqualc          
   O   sJ   |j dt}t| }t| ||}|d kr,|S | ||| W d Q R X d S )Nr  )r   r   r   rD   )r=   rF   funcr   rd   r  r  r^   r8   r8   r9   assertNumQueries  s    z$TransactionTestCase.assertNumQueries)T)N)rV   rW   rX   r  r  r  r  rv   r   r   r
  r  r  r  r   r  r   r'  r)  rY   r8   r8   )rI   r9   r1     s    c               C   s   t dd tj  D S )z?
    Returns True if all connections support transactions.
    c             s   s   | ]}|j jV  qd S )N)r  Zsupports_transactions)rL   r  r8   r8   r9   rN     s   z3connections_support_transactions.<locals>.<genexpr>)r  r   r8   r8   r8   r9    connections_support_transactions  s    r*  c                   s   e Zd Z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 )r0   a  
    Similar to TransactionTestCase, but uses `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   s6   i }x,| j  D ] }tj|d||< || j  qW |S )z:Helper method to open atomic blocks for multiple databases)r  )r
  r   r  ri   )rx   atomicsr  r8   r8   r9   _enter_atomics  s
    zTestCase._enter_atomicsc             C   s:   x4t | j D ]$}tjd|d || jddd qW dS )z9Rollback atomic blocks opened through the previous methodT)r  N)reversedr
  r   Zset_rollbackrO   )rx   r+  r  r8   r8   r9   _rollback_atomics  s    zTestCase._rollback_atomicsc                s   t t| j  t sd S | j | _| jr~xT| jddD ]D}ytd| jdd|d W q6 t	k
rx   | j
| j  Y q6X q6W y| j  W n" t	k
r   | j
| j  Y nX d S )NF)r  r  r   )r  commitr  )r  )rG   r0   rp   r*  r,  cls_atomicsr  r
  r   r   r.  setUpTestData)rx   r  )rI   r8   r9   rp     s&    

zTestCase.setUpClassc                s>   t  r,| j| j xtj D ]}|j  qW tt| j  d S )N)	r*  r.  r0  r   r  r  rG   r0   r}   )rx   r  )rI   r8   r9   r}     s
    zTestCase.tearDownClassc             C   s   dS )z"Load initial data for the TestCaseNr8   )rx   r8   r8   r9   r1    s    zTestCase.setUpTestDatac                s   t  r
dS tt| j S )NF)r*  rG   r0   r  )r=   )rI   r8   r9   r    s    z#TestCase._should_reload_connectionsc                s:   t  s| j  tt| j S | j s,td| j | _d S )Nz4reset_sequences cannot be used on TestCase instances)	r*  r1  rG   r0   r  r  rn   r,  r+  )r=   )rI   r8   r9   r    s
    zTestCase._fixture_setupc                s\   t  stt| j S z4x.t| j D ]}| jt| r$t| j  q$W W d | j	| j
 X d S )N)r*  rG   r0   r  r-  r
  _should_check_constraintsr   Zcheck_constraintsr.  r+  )r=   r  )rI   r8   r9   r  "  s    zTestCase._fixture_teardownc             C   s   |j jo|j o|j S )N)r  Zcan_defer_constraint_checksZneeds_rollbackZ	is_usable)r=   r   r8   r8   r9   r2  ,  s    z"TestCase._should_check_constraints)rV   rW   rX   __doc__r   r,  r.  rp   r}   r1  r  r  r  r2  rY   r8   r8   )rI   r9   r0     s   	

c               @   s"   e Zd ZdZdd ZdddZdS )CheckConditionz0Descriptor class for deferred condition checkingc             C   s
   || _ d S )N)	cond_func)r=   r5  r8   r8   r9   rH   5  s    zCheckCondition.__init__Nc             C   s   | j  S )N)r5  )r=   instancerx   r8   r8   r9   __get__8  s    zCheckCondition.__get__)N)rV   rW   rX   r3  rH   r7  r8   r8   r8   r9   r4  3  s   r4  c                s    fdd}|S )Nc                sL   t  tot tjs4t  fdd}|}n }t|_|_|S )Nc                 s     rt j| |S )N)unittestZSkipTest)r   rd   )	conditionreason	test_funcr8   r9   skip_wrapper@  s    
z6_deferredSkip.<locals>.decorator.<locals>.skip_wrapper)	r5   typer   r8  r0   r   r4  r~   Z__unittest_skip_why__)r;  r<  Z	test_item)r9  r:  )r;  r9   	decorator=  s    

z _deferredSkip.<locals>.decoratorr8   )r9  r:  r>  r8   )r9  r:  r9   _deferredSkip<  s    r?  c                 s   t  fddddj  S )zK
    Skip 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   r  )rL   featurer8   r8   r9   rN   T  s    z4skipIfDBFeature.<locals>.<lambda>.<locals>.<genexpr>)anyr8   )r  r8   r9   <lambda>T  s    z!skipIfDBFeature.<locals>.<lambda>zDatabase has feature(s) %sz, )r?  rR   )r  r8   )r  r9   r3   O  s    
c                 s   t  fddddj  S )zC
    Skip 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 )FN)r   r   r  )rL   r@  r8   r8   r9   rN   ^  s    z8skipUnlessDBFeature.<locals>.<lambda>.<locals>.<genexpr>)r  r8   )r  r8   r9   rB  ^  s    z%skipUnlessDBFeature.<locals>.<lambda>z'Database doesn't support feature(s): %sz, )r?  rR   )r  r8   )r  r9   r4   Y  s    
c                 s   t  fddddj  S )zF
    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 )FN)r   r   r  )rL   r@  r8   r8   r9   rN   h  s    z;skipUnlessAnyDBFeature.<locals>.<lambda>.<locals>.<genexpr>)rA  r8   )r  r8   r9   rB  h  s    z(skipUnlessAnyDBFeature.<locals>.<lambda>z2Database doesn't support any of the feature(s): %sz, )r?  rR   )r  r8   )r  r9   skipUnlessAnyDBFeaturec  s    
rC  c               @   s   e Zd ZdZdd ZdS )QuietWSGIRequestHandlerz
    Just a regular WSGIRequestHandler except it doesn't log to the standard
    output any of the requests received, so as to not clutter the output for
    the tests' results.
    c              G   s   d S )Nr8   )r   r8   r8   r9   log_messaget  s    z#QuietWSGIRequestHandler.log_messageN)rV   rW   rX   r3  rE  r8   r8   r8   r9   rD  m  s   rD  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| j | _tt| j  d S )N)applicationr+   get_base_urlbase_urlrG   rF  rH   )r=   rG  )rI   r8   r9   rH   }  s    zFSFilesHandler.__init__c             C   s   |j | jd o| jd  S )z
        Checks if the path should be handled. Ignores 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   r   )r   rI  )r=   r   r8   r8   r9   _should_handle  s    zFSFilesHandler._should_handlec             C   s   |t | jd d }t|S )zR
        Returns the relative path to the file on disk for the given URL.
        r   N)rP   rI  r.   )r=   r   r   r8   r8   r9   	file_path  s    zFSFilesHandler.file_pathc                sH   ddl m} | j|jr8y
| j|S  |k
r6   Y nX tt| j|S )Nr   )Http404)django.httprL  rJ  r   r/   rG   rF  get_response)r=   r   rL  )rI   r8   r9   rN    s    
zFSFilesHandler.get_responsec             C   s>   | j |j}tjt|}|jddjd}t||| j dS )N\r   )Zdocument_root)	rK  r   	posixpathnormpathr)   replacelstripr/   get_base_dir)r=   r   Zos_rel_pathZfinal_rel_pathr8   r8   r9   r/     s    zFSFilesHandler.servec                s,   | j t|s| j||S tt| j||S )N)rJ  r   rG  rG   rF  ro   )r=   environZstart_response)rI   r8   r9   ro     s    zFSFilesHandler.__call__)rV   rW   rX   r3  rH   rJ  rK  rN  r/   ro   rY   r8   r8   )rI   r9   rF  x  s   	
	rF  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 )N)r	   ZSTATIC_ROOT)r=   r8   r8   r9   rT    s    z _StaticFilesHandler.get_base_dirc             C   s   t jS )N)r	   Z
STATIC_URL)r=   r8   r8   r9   rH    s    z _StaticFilesHandler.get_base_urlN)rV   rW   rX   r3  rT  rH  r8   r8   r8   r9   rV    s   rV  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 )N)r	   Z
MEDIA_ROOT)r=   r8   r8   r9   rT    s    z_MediaFilesHandler.get_base_dirc             C   s   t jS )N)r	   Z	MEDIA_URL)r=   r8   r8   r9   rH    s    z_MediaFilesHandler.get_base_urlN)rV   rW   rX   r3  rT  rH  r8   r8   r8   r9   rW    s   rW  c                   s:   e Zd ZdZd fdd	Zdd Zdd Zd	d
 Z  ZS )LiveServerThreadzL
    Thread for running a live http server while the tests are running.
    Nc                s@   || _ d | _|| _tj | _d | _|| _|| _t	t
| j  d S )N)r   portpossible_ports	threadingEventis_readyerrorstatic_handlerconnections_overriderG   rX  rH   )r=   r   rZ  r_  r`  )rI   r8   r9   rH     s    
zLiveServerThread.__init__c             C   s  | j r&x| j j D ]\}}|t|< qW y| jtt }xxt| jD ]j\}}y| j|| _	W nH t
jk
r } z*|d t| jk r|jtjkrwDn W Y dd}~X qDX || _P qDW | j	j| | jj  | j	j  W n4 tk
r } z|| _| jj  W Y dd}~X nX dS )zl
        Sets up the live server and databases, and then loops over handling
        http requests.
        r   N)r`  r   r   r_  rW  r   r   rZ  _create_serverhttpdsocketr^  rP   errnoZ
EADDRINUSErY  Zset_appr]  setserve_foreverr   )r=   ry   r  handlerindexrY  rA   r8   r8   r9   run  s*    
zLiveServerThread.runc             C   s   t | j|ftddS )NF)allow_reuse_address)r   r   rD  )r=   rY  r8   r8   r9   ra    s    zLiveServerThread._create_serverc             C   s"   t | dr| jj  | jj  d S )Nrb  )rz   rb  shutdownserver_close)r=   r8   r8   r9   	terminate  s    

zLiveServerThread.terminate)N)	rV   rW   rX   r3  rH   ri  ra  rm  rY   r8   r8   )rI   r9   rX    s
   
*rX  c                   s\   e Zd ZdZe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	  
    Does basically the same as TransactionTestCase but also launches 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.
    Note that it inherits from TransactionTestCase instead of TestCase because
    the threads do not 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.
    c             C   s   d| j j| j jf S )Nzhttp://%s:%s)server_threadr   rY  )rx   r8   r8   r9   live_server_url  s    z"LiveServerTestCase.live_server_urlc                sv  t t| j  i }x:tj D ].}|jdkr|j|jd rd|_|||j	< qW t
jjdd}g }y|jd\}}x||jdD ]n}ttt|jd}t|dkstt|d	kr|j|d  q|x(t|d |d	 d	 D ]}	|j|	 qW q|W W n8 tk
r(   d| }
tjtt|
tj d
  Y nX | j|||| _d| j_| jj  | jjj   | jj!rr| j"  | jj!d S )NsqliteNAMETZDJANGO_LIVE_TEST_SERVER_ADDRESSzlocalhost:8081-8179:,-r   r   r   z'Invalid address ("%s") for live server.)r   r   )#rG   rn  rp   r   r  vendoris_in_memory_dbr  allow_thread_sharingry   osrU  r   splitr6   r$  intrP   rn   r_   ranger   r%   reraiser   r   r   _create_server_threadro  daemonstartr]  waitr^  _tearDownClassInternal)rx   r`  r  Zspecified_addressrZ  r   Zport_rangesZ
port_rangeZextremesrY  r?   )rI   r8   r9   rp     s8     

zLiveServerTestCase.setUpClassc             C   s   t ||| j|dS )N)r`  )rX  r_  )rx   r   rZ  r`  r8   r8   r9   r~  K  s
    z(LiveServerTestCase._create_server_threadc             C   sT   t | dr| jj  | jj  x0tj D ]$}|jdkr(|j|jd r(d|_	q(W d S )Nro  rq  rr  F)
rz   ro  rm  rR   r   r  rv  rw  r  rx  )rx   r  r8   r8   r9   r  T  s    


z)LiveServerTestCase._tearDownClassInternalc                s   | j   tt| j  d S )N)r  rG   rn  r}   )rx   )rI   r8   r9   r}   b  s    z LiveServerTestCase.tearDownClass)rV   rW   rX   r3  rV  r_  r&   rp  r   rp   r~  r  r}   rY   r8   r8   )rI   r9   rn    s   
0	rn  c                   s8   e Zd ZdZdZe fddZe fddZ  ZS )SerializeMixina  
    Mixin to 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                sH   | j d krtdj| jt| j | _tj| jtj t	t
| j  d S )NzB{}.lockfile isn't set. Set it to a unique value in the base class.)lockfiler   formatrV   open	_lockfiler   lockZLOCK_EXrG   r  rp   )rx   )rI   r8   r9   rp   t  s    

zSerializeMixin.setUpClassc                s   t t| j  | jj  d S )N)rG   r  r}   r  r  )rx   )rI   r8   r9   r}   ~  s    zSerializeMixin.tearDownClass)	rV   rW   rX   r3  r  r   rp   r}   rY   r8   r8   )rI   r9   r  h  s   
r  )r0   r1   r2   r3   r4   )n
__future__r   r   rd  r   ry  rP  rc  r   r[  r8  r   collectionsr   
contextlibr   r   	functoolsr   Zunittest.utilr   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   rM  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.utilsr%   Zdjango.utils.decoratorsr&   Zdjango.utils.deprecationr'   Zdjango.utils.encodingr(   Z#django.utils.six.moves.urllib.parser)   r*   r+   r,   r-   Z%django.utils.six.moves.urllib.requestr.   Zdjango.views.staticr/   __all__r:   rC   rD   objectrZ   rj   rk   r0   r2   r1   r*  r4  r?  r3   r4   rC  rD  rF  rV  rW  ThreadrX  rn  r  r8   r8   r8   r9   <module>   s    	&      -b	


3C`