

_VQ                 @   su  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
 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 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' d  d l( m) Z) d  d l* m+ Z+ y d  d l, Z, Wn e- k
 rd Z, Yn XdL Z. e/ e d  Z0 Gd d   d e1  Z2 Gd d   d e3  Z4 d d    Z5 d! d   Z6 d" d   Z7 d d# d  Z8 Gd$ d   d e1  Z9 Gd% d   d e9  Z: d d& d'  Z; d( d)   Z< d* d+   Z= d, d-   Z> Gd. d/   d/ e1  Z? Gd0 d1   d1 e1  Z@ e d2 d3    ZA e e0 d4  ZB e d5 d6    ZC e d7 d    ZD e d8 d9    ZE d: d;   ZF d< d=   ZG d> d?   ZH d@ dA   ZI e dB dC    ZJ dD dE   ZK GdF dG   dG e'  ZL dH dI   ZM GdJ dK   dK e1  ZN d S)M    N)contextmanager)wraps)skipIf
skipUnless)NodeparseString)apps)UserSettingsHoldersettings)mail)request_started)get_script_prefixset_script_prefix)reset_queries)request)Template)setting_changedtemplate_rendered)six)ContextDecorator)	force_str)
deactivateApproximateContextListisolate_lru_cache
get_runnermodify_settingsoverride_settingsrequires_tz_supportsetup_test_environmentteardown_test_environmenttzsetc               @   s7   e  Z d  Z d d d  Z d d   Z d d   Z d S)	r      c             C   s   | |  _  | |  _ d  S)N)valplaces)selfr#   r$    r&   3/tmp/pip-build-ghmbqnp_/Django/django/test/utils.py__init__*   s    	zApproximate.__init__c             C   s   t  |  j  S)N)reprr#   )r%   r&   r&   r'   __repr__.   s    zApproximate.__repr__c             C   s6   |  j  | k r d St t |  j  |  |  j  d k S)NTr   )r#   roundabsr$   )r%   otherr&   r&   r'   __eq__1   s    zApproximate.__eq__N)__name__
__module____qualname__r(   r*   r.   r&   r&   r&   r'   r   )   s   c                   s@   e  Z d  Z d Z   f d d   Z d d   Z d d   Z   S)r   zkA wrapper that provides direct key access to context items contained
    in a list of context objects.
    c                s`   t  | t j  rF x" |  D] } | | k r | | Sq Wt |   n t t |   j |  Sd  S)N)
isinstancer   string_typesKeyErrorsuperr   __getitem__)r%   key
subcontext)	__class__r&   r'   r6   ;   s    zContextList.__getitem__c             C   s)   y |  | Wn t  k
 r$ d SYn Xd S)NFT)r4   )r%   r7   r&   r&   r'   __contains__D   s
    	zContextList.__contains__c             C   sE   t    } x5 |  D]- } x$ | D] } | t  | j    O} q Wq W| S)z0
        Flattened keys of subcontexts.
        )setkeys)r%   r<   r8   dictr&   r&   r'   r<   K   s
    	zContextList.keys)r/   r0   r1   __doc__r6   r:   r<   r&   r&   )r9   r'   r   7   s   	c             C   s,   t  j d |  d |  d |  |  j j |  S)zz
    An instrumented Template render method, providing a signal
    that can be intercepted by the test system Client
    sendertemplatecontext)r   sendnodelistrender)r%   rA   r&   r&   r'   instrumented_test_renderV   s    rE   c               C   sV   t  j t  _ t t  _ t j t _ d t _ t j t	 _
 d g t _ g  t _ t   d S)zPerform any global pre-test setup. This involves:

        - Installing the instrumented test renderer
        - Set the email backend to the locmem email backend.
        - Setting the active locale to match the LANGUAGE_CODE setting.
    z-django.core.mail.backends.locmem.EmailBackend*N)r   _render_original_renderrE   r
   EMAIL_BACKENDr   _original_email_backendALLOWED_HOSTSr   _original_allowed_hostsoutboxr   r&   r&   r&   r'   r   _   s    			c               C   s@   t  j t  _ t  ` t j t _ t ` t j t _	 t ` t `
 d S)zPerform any global post-test teardown. This involves:

        - Restoring the original test renderer
        - Restoring the email sending functions
    N)r   rH   rG   r   rJ   r
   rI   r   rL   rK   rM   r&   r&   r&   r'   r    w   s    c             C   s   | s |  j  } n  | j d  } t |  d k rO d j | d  d   } n d } t | i  i  t | d   } t | | d  } | S)N.   rP   rP   )ZTEST_RUNNERsplitlenjoin
__import__r   getattr)r
   Ztest_runner_classZ	test_pathZtest_module_nameZtest_moduleZtest_runnerr&   r&   r'   r      s    c               @   sj   e  Z d  Z d Z d d   Z d d   Z d d   Z d d	   Z d
 d   Z d d   Z	 d d   Z
 d S)r   a;  
    Acts as either a decorator, or a context manager. If it's a decorator it
    takes a function and returns a wrapped function. If it's a contextmanager
    it's used with the ``with`` statement. In either event entering/exiting
    are called before and after, respectively, the function/block is executed.
    c             K   s   | |  _  d  S)N)options)r%   kwargsr&   r&   r'   r(      s    zoverride_settings.__init__c             C   s   |  j    d  S)N)enable)r%   r&   r&   r'   	__enter__   s    zoverride_settings.__enter__c             C   s   |  j    d  S)N)disable)r%   exc_type	exc_value	tracebackr&   r&   r'   __exit__   s    zoverride_settings.__exit__c                ss   d d l  m } t  t  rN t  |  s= t d   n    j    St      f d d    } | S)Nr   )SimpleTestCasezPOnly subclasses of Django SimpleTestCase can be decorated with override_settingsc           
      s       |  |   SWd  QXd  S)Nr&   )argsrW   )r%   	test_funcr&   r'   inner   s    z)override_settings.__call__.<locals>.inner)Zdjango.testr_   r2   type
issubclass	Exceptionsave_optionsr   )r%   ra   r_   rb   r&   )r%   ra   r'   __call__   s    !zoverride_settings.__call__c             C   s:   | j  d  k r |  j | _  n t | j  |  j  | _  d  S)N)Z_overridden_settingsrV   r=   )r%   ra   r&   r&   r'   rf      s    zoverride_settings.save_optionsc             C   s   d |  j  k rL y t j |  j  d  WqL t k
 rH t j     YqL Xn  t t j  } x- |  j  j   D] \ } } t	 | | |  qk Wt j |  _
 | t _ xE |  j  j   D]4 \ } } t j d t j j d | d | d d  q Wd  S)NINSTALLED_APPSr?   settingvalueenterT)rV   r   Zset_installed_appsre   unset_installed_appsr	   r
   _wrappeditemssetattrwrappedr   rB   r9   )r%   overrider7   	new_valuer&   r&   r'   rX      s    
	zoverride_settings.enablec          
   C   s   d |  j  k r t j   n  |  j t _ |  ` xK |  j  D]@ } t t | d   } t j d t j j	 d | d | d d  q8 Wd  S)Nrh   r?   ri   rj   rk   F)
rV   r   rl   rp   r
   rm   rU   r   rB   r9   )r%   r7   rr   r&   r&   r'   rZ      s    zoverride_settings.disableN)r/   r0   r1   r>   r(   rY   r^   rg   rf   rX   rZ   r&   r&   r&   r'   r      s   c                   s@   e  Z d  Z d Z d d   Z d d   Z   f d d   Z   S)r   z
    Like override_settings, but makes it possible to append, prepend or remove
    items instead of redefining the entire list.
    c             O   sI   | r# | s t   | d |  _ n" | s0 t   t | j    |  _ d  S)Nr   )AssertionError
operationslistrn   )r%   r`   rW   r&   r&   r'   r(      s
    zmodify_settings.__init__c             C   s;   | j  d  k r |  j | _  n t | j   |  j | _  d  S)N)Z_modified_settingsrt   ru   )r%   ra   r&   r&   r'   rf      s    zmodify_settings.save_optionsc                sP  i  |  _  x-|  j D]"\ } } y |  j  |  Wn* t k
 r\ t t t | g     Yn Xx | j   D] \ }   t   t j	  r   g   n  | d k r   f d d     D  qj | d k r  f d d     D   qj | d k r  f d d    D  qj t
 d |   qj W |  j  | <q Wt t |   j   d  S)	Nappendc                s"   g  |  ] } |   k r |  q Sr&   r&   ).0item)rj   r&   r'   
<listcomp>  s   	 z*modify_settings.enable.<locals>.<listcomp>prependc                s"   g  |  ] } |   k r |  q Sr&   r&   )rw   rx   )rj   r&   r'   ry     s   	 removec                s"   g  |  ] } |   k r |  q Sr&   r&   )rw   rx   )rn   r&   r'   ry     s   	 zUnsupported action: %s)rV   rt   r4   ru   rU   r
   rn   r2   r   r3   
ValueErrorr5   r   rX   )r%   namert   action)r9   )rn   rj   r'   rX      s$    	  zmodify_settings.enable)r/   r0   r1   r>   r(   rf   rX   r&   r&   )r9   r'   r      s   	c                s,   d d l  m      f d d   } | S)z Acts as a decorator. Overrides list of registered system checks.
    Useful when you override `INSTALLED_APPS`, e.g. if you exclude `auth` app,
    you also need to exclude its system checks. r   )registryc                s+   t          f d d    } | S)Nc                 s^    j  }   _   j }   d  k	 r3    _ n  z  |  |   SWd  |  _  |  _ Xd  S)N)Zregistered_checksdeployment_checks)r`   rW   Z
old_checksZold_deployment_checks)r   
new_checksr   ra   r&   r'   rb     s    				z4override_system_checks.<locals>.outer.<locals>.inner)r   )ra   rb   )r   r   r   )ra   r'   outer  s    'z%override_system_checks.<locals>.outer)Zdjango.core.checks.registryr   )r   r   r   r&   )r   r   r   r'   override_system_checks  s    r   c                s  t  j d      f d d    d d    d d      f d d	    d
 d        f d d    d d   } t |  |  \ }  } |  j d d  }  | j d d  } |  j d  s d } | |  }  | | } n  | t |    } | t |   }  | |  S)a0  Tries to do a 'xml-comparison' of want and got.  Plain string
    comparison doesn't always work because, for example, attribute
    ordering should not be important. Comment nodes are not considered in the
    comparison.

    Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py
    z[ \t\n][ \t\n]+c                s     j  d |   S)N )sub)v)_norm_whitespace_rer&   r'   norm_whitespace.  s    z$compare_xml.<locals>.norm_whitespacec             S   s   d j  d d   |  j D  S)N c             s   s*   |  ]  } | j  t j k r | j Vq d  S)N)nodeTyper   Z	TEXT_NODEdata)rw   cr&   r&   r'   	<genexpr>2  s    z2compare_xml.<locals>.child_text.<locals>.<genexpr>)rS   
childNodes)elementr&   r&   r'   
child_text1  s    zcompare_xml.<locals>.child_textc             S   s   d d   |  j  D S)Nc             S   s(   g  |  ] } | j  t j k r |  q Sr&   )r   r   ZELEMENT_NODE)rw   r   r&   r&   r'   ry   6  s   	 z1compare_xml.<locals>.children.<locals>.<listcomp>)r   )r   r&   r&   r'   children5  s    zcompare_xml.<locals>.childrenc                s      |    S)Nr&   )r   )r   r   r&   r'   norm_child_text9  s    z$compare_xml.<locals>.norm_child_textc             S   s   t  |  j j    S)N)r=   
attributesrn   )r   r&   r&   r'   
attrs_dict<  s    zcompare_xml.<locals>.attrs_dictc                s   |  j  | j  k r d S |    |  k r2 d S  |     |  k rN d S |   }  |  } t |  t |  k r d Sx0 t | |  D] \ } }  | |  s d Sq Wd S)NFT)ZtagNamerR   zip)Zwant_elementZgot_elementZwant_childrenZgot_childrenwantgot)r   check_elementr   r   r&   r'   r   ?  s    z"compare_xml.<locals>.check_elementc             S   s.   x' |  j  D] } | j t j k r
 | Sq
 Wd  S)N)r   r   r   ZCOMMENT_NODE)documentnoder&   r&   r'   
first_nodeO  s    zcompare_xml.<locals>.first_nodez\n
z<?xmlz<root>%s</root>)recompilestrip_quotesreplace
startswithr   )r   r   r   wrapperZ	want_rootZgot_rootr&   )r   r   r   r   r   r   r   r'   compare_xml$  s$    
r   c             C   s   d d   } d d   } | |   r_ | |  r_ |  j    d d  }  | j    d d  } nG | |   r | |  r |  j    d d	  }  | j    d d
  } n  |  | f S)z
    Strip quotes of doctests output values:

    >>> strip_quotes("'foo'")
    "foo"
    >>> strip_quotes('"foo"')
    "foo"
    c             S   s@   |  j    }  t |   d k o? |  d |  d k o? |  d d k S)N   r   rO   "'rP   )r   r   )striprR   )sr&   r&   r'   is_quoted_stringo  s    z&strip_quotes.<locals>.is_quoted_stringc             S   sP   |  j    }  t |   d k oO |  d d k oO |  d |  d k oO |  d d k S)	N   r   urO   r   r   rP   )r   r   )r   rR   )r   r&   r&   r'   is_quoted_unicodeu  s
    z'strip_quotes.<locals>.is_quoted_unicoderO   r   rP   rP   rP   rP   )r   )r   r   r   r   r&   r&   r'   r   f  s    	r   c             C   s   |  i t  j r d n d d 6S)Nr   r   _)r   PY3)r   r&   r&   r'   
str_prefix  s    r   c               @   sp   e  Z d  Z d Z d d   Z d d   Z d d   Z d d	   Z e d
 d    Z	 d d   Z
 d d   Z d S)CaptureQueriesContextzU
    Context manager that captures queries executed by the specified connection.
    c             C   s   | |  _  d  S)N)
connection)r%   r   r&   r&   r'   r(     s    zCaptureQueriesContext.__init__c             C   s   t  |  j  S)N)itercaptured_queries)r%   r&   r&   r'   __iter__  s    zCaptureQueriesContext.__iter__c             C   s   |  j  | S)N)r   )r%   indexr&   r&   r'   r6     s    z!CaptureQueriesContext.__getitem__c             C   s   t  |  j  S)N)rR   r   )r%   r&   r&   r'   __len__  s    zCaptureQueriesContext.__len__c             C   s   |  j  j |  j |  j  S)N)r   Zqueriesinitial_queriesfinal_queries)r%   r&   r&   r'   r     s    z&CaptureQueriesContext.captured_queriesc             C   sJ   |  j  j |  _ d |  j  _ t |  j  j  |  _ d  |  _ t j t  |  S)NT)	r   force_debug_cursorrR   queries_logr   r   r   Z
disconnectr   )r%   r&   r&   r'   rY     s    	zCaptureQueriesContext.__enter__c             C   sE   |  j  |  j _  t j t  | d  k	 r, d  St |  j j  |  _ d  S)N)r   r   r   connectr   rR   r   r   )r%   r[   r\   r]   r&   r&   r'   r^     s
    zCaptureQueriesContext.__exit__N)r/   r0   r1   r>   r(   r   r6   r   propertyr   rY   r^   r&   r&   r&   r'   r     s   r   c               @   s(   e  Z d  Z d d   Z d d   Z d S)ignore_warningsc             K   sF   | |  _  d |  j  k s' d |  j  k r6 t j |  _ n t j |  _ d  S)Nmessagemodule)ignore_kwargswarningsfilterwarningsfilter_funcsimplefilter)r%   rW   r&   r&   r'   r(     s    	zignore_warnings.__init__c                s   t    t  ra   j    j    f d d   }   f d d   } |   _ |   _   St       f d d    } | Sd  S)Nc                s=   t  j    _  j j    j d  j    |   d  S)Nignore)r   catch_warningsrY   r   r   )
inner_self)saved_setUpr%   r&   r'   setUp  s    z'ignore_warnings.__call__.<locals>.setUpc                s$     |    j  j t j     d  S)N)r   r^   sysexc_info)r   )saved_tearDownr%   r&   r'   tearDown  s    
z*ignore_warnings.__call__.<locals>.tearDownc           
      s7   t  j   %  j d  j    |  |   SWd  QXd  S)Nr   )r   r   r   r   )r`   rW   )	decoratedr%   r&   r'   rb     s    z'ignore_warnings.__call__.<locals>.inner)r2   rc   r   r   r   )r%   r   r   r   rb   r&   )r   r   r   r%   r'   rg     s    				!zignore_warnings.__call__N)r/   r0   r1   r(   rg   r&   r&   r&   r'   r     s   r   c             #   sg   g      f d d   } t  j |   } t | |  } t | | |  z	   VWd t | | |  Xd S)z
    Context manager that takes a named logger and the logging level
    and provides a simple mock-like list of messages received
    c                s     j  |  |  d  S)N)rv   )msgr`   rW   )callsr&   r'   replacement  s    z!patch_logger.<locals>.replacementN)logging	getLoggerrU   ro   )Zlogger_nameZ	log_levelr   loggerorigr&   )r   r'   patch_logger  s    	r   z|This test relies on the ability to run a program in an arbitrary time zone, but your operating system isn't able to do that.c              g   s=   t  j d d  } t  j j |   z	 d VWd | t  _ Xd S)z5Context manager to temporarily add paths to sys.path.N)r   pathextend)pathsZ_orig_sys_pathr&   r&   r'   extend_sys_path  s
    	r   c          
   c   s%   |  j    z	 d VWd |  j    Xd S)z?Clear the cache of an LRU cache object on entering and exiting.N)cache_clear)Zlru_cache_objectr&   r&   r'   r     s    
	c             c   sO   t  t |   } t t |  t j    z t  t |   VWd t t |  |  Xd S)a  Return a context manager used by captured_stdout/stdin/stderr
    that temporarily replaces the sys stream *stream_name* with a StringIO.

    Note: This function and the following ``captured_std*`` are copied
          from CPython's ``test.support`` module.N)rU   r   ro   r   StringIO)stream_nameorig_stdoutr&   r&   r'   captured_output  s
    r   c               C   s
   t  d  S)zCapture the output of sys.stdout:

       with captured_stdout() as stdout:
           print("hello")
       self.assertEqual(stdout.getvalue(), "hello
")
    stdout)r   r&   r&   r&   r'   captured_stdout  s    r   c               C   s
   t  d  S)zCapture the output of sys.stderr:

       with captured_stderr() as stderr:
           print("hello", file=sys.stderr)
       self.assertEqual(stderr.getvalue(), "hello
")
    stderr)r   r&   r&   r&   r'   captured_stderr  s    r   c               C   s
   t  d  S)a  Capture the input to sys.stdin:

       with captured_stdin() as stdin:
           stdin.write('hello
')
           stdin.seek(0)
           # call test code that consumes from sys.stdin
           captured = input()
       self.assertEqual(captured, "hello")
    stdin)r   r&   r&   r&   r'   captured_stdin&  s    
r   c              C   sI   d }  x< t  j j   D]+ } t | |   r t | |   j   q q Wd S)a  
    Clear warning registry for all modules. This is required in some tests
    because of a bug in Python that prevents warnings.simplefilter("always")
    from always making warnings appear: http://bugs.python.org/issue4180

    The bug was fixed in Python 3.4.2.
    __warningregistry__N)r   modulesvalueshasattrrU   clear)r7   modr&   r&   r'   reset_warning_registry3  s    r   c             #   s8   t  j  }   f d d   t  _  z	 d VWd | t  _  Xd S)aM  
    Context manager to temporarily freeze time.time(). This temporarily
    modifies the time function of the time module. Modules which import the
    time function directly (e.g. `from time import time`) won't be affected
    This isn't meant as a public API, but helps reduce some repetitive code in
    Django's test suite.
    c                  s     S)Nr&   r&   )tr&   r'   <lambda>K  s    zfreeze_time.<locals>.<lambda>N)time)r   Z
_real_timer&   )r   r'   freeze_timeA  s
    			r   c             C   sd   t  t d k d  |   }  t d i d d 6d d 6i d d 6d d 6i d d	 6d
 6g  |   }  |  S)z
    Decorator to enable a Jinja2 template engine in addition to the regular
    Django template engine for a test or skip it if Jinja2 isn't available.
    Nzthis test requires jinja2Z	TEMPLATESz/django.template.backends.django.DjangoTemplatesZBACKENDTZAPP_DIRSz&django.template.backends.jinja2.Jinja2Zkeep_trailing_newlineOPTIONS)r   jinja2r   )ra   r&   r&   r'   require_jinja2R  s    		r   c               @   s4   e  Z d  Z d d   Z d d   Z d d   Z d S)ScriptPrefixc             C   s   t  |  j  d  S)N)r   prefix)r%   r&   r&   r'   rY   d  s    zScriptPrefix.__enter__c             C   s   t  |  j  d  S)N)r   
old_prefix)r%   r[   exc_valr]   r&   r&   r'   r^   g  s    zScriptPrefix.__exit__c             C   s   | |  _  t   |  _ d  S)N)r   r   r   )r%   r   r&   r&   r'   r(   j  s    	zScriptPrefix.__init__N)r/   r0   r1   rY   r^   r(   r&   r&   r&   r'   r   c  s   r   c             C   s
   t  |   S)zO
    Decorator or context manager to temporary override the script prefix.
    )r   )r   r&   r&   r'   override_script_prefixo  s    r   c               @   s.   e  Z d  Z d Z d d   Z d d   Z d S)LoggingCaptureMixinzn
    Capture the output from the 'django' logger and store it on the class's
    logger_output attribute.
    c             C   sQ   t  j d  |  _ |  j j d j |  _ t j   |  _ |  j |  j j d _ d  S)NZdjangor   )	r   r   r   handlersstream
old_streamr   r   Zlogger_output)r%   r&   r&   r'   r   {  s    zLoggingCaptureMixin.setUpc             C   s   |  j  |  j j d _ d  S)Nr   )r   r   r   r   )r%   r&   r&   r'   r     s    zLoggingCaptureMixin.tearDownN)r/   r0   r1   r>   r   r   r&   r&   r&   r'   r   v  s   r   )	zApproximatezContextListzisolate_lru_cachez
get_runnerzmodify_settingszoverride_settingszrequires_tz_supportzsetup_test_environmentzteardown_test_environment)Or   r   r   r   r   
contextlibr   	functoolsr   Zunittestr   r   Zxml.dom.minidomr   r   Zdjango.appsr   Zdjango.confr	   r
   Zdjango.corer   Zdjango.core.signalsr   Zdjango.core.urlresolversr   r   Z	django.dbr   Zdjango.httpr   Zdjango.templater   Zdjango.test.signalsr   r   Zdjango.utilsr   Zdjango.utils.decoratorsr   Zdjango.utils.encodingr   Zdjango.utils.translationr   r   ImportError__all__r   Z
TZ_SUPPORTobjectr   ru   r   rE   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&   r&   r'   <module>   sv      	E/B$$	


