o 3aw@sddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlmZddlmZddlmZmZmZddlmZmZdd lmZdd lmZdd lmZmZdd l m!Z!dd l"m#Z#ddl$m%Z%ddl&m'Z'm(Z(m)Z)ddl*m+Z+ddl,m-Z-ddl.m/Z/m0Z0ddl1m2Z2m3Z3ddl4m5Z5zddl6Z6Wn e7ydZ6YnwdZ8e9edZ:GdddZ;Gddde<Z=ddZ>GdddZ?d]dd Z@d!d"ZAdd#d#ddd$d%d&ZBd'd(ZCd]d)d*ZDd^d+d,ZEd]d-d.ZFGd/d0d0ZGGd1d2d2eGZHGd3d4d4eHZIGd5d6d6eGZJd7d8ZKGd9d:d:ZLGd;d<dd?ZOe d@dAZPe dBdCZQdDdEZRdFdGZSdHdIZTe dJdKZUdLdMZVGdNdOdOeGZWGdPdQdQZXGdRdSdSeGZYGdTdUdUZZGdVdWdWZ[dXdYZ\e ddZd[d\Z]dS)_N)contextmanager)wraps)StringIO)chain)SimpleNamespace)TestCaseskipIf skipUnless)Node parseString)apps)Apps)UserSettingsHoldersettings)mail)ImproperlyConfigured)request_started)DEFAULT_DB_ALIAS connections reset_queries)Options)Template)setting_changedtemplate_rendered)get_script_prefixset_script_prefix) deactivate) Approximate ContextListisolate_lru_cache get_runnerCaptureQueriesContextignore_warnings isolate_appsmodify_settingsoverride_settingsoverride_system_checkstagrequires_tz_supportsetup_databasessetup_test_environmentteardown_test_environmenttzsetc@s&eZdZd ddZddZddZdS) rcC||_||_dSN)valplaces)selfr0r1r33/usr/lib/python3/dist-packages/django/test/utils.py__init__1 zApproximate.__init__cC t|jSr/)reprr0r2r3r3r4__repr__5 zApproximate.__repr__cCs$|j|kptt|j||jdkSNr)r0roundabsr1)r2otherr3r3r4__eq__8s$zApproximate.__eq__N)r-)__name__ __module__ __qualname__r5r:r@r3r3r3r4r0s  rcs:eZdZdZfddZd ddZddZd d ZZS) rzp A wrapper that provides direct key access to context items contained in a list of context objects. cs<t|tr|D] }||vr||Sqt|t|Sr/) isinstancestrKeyErrorsuper __getitem__)r2key subcontext __class__r3r4rHAs   zContextList.__getitem__NcCs$z||WSty|YSwr/)rHrF)r2rIdefaultr3r3r4getJs   zContextList.getcCs$z||WdStyYdSw)NFT)rF)r2rIr3r3r4 __contains__Ps   zContextList.__contains__cCsttdd|DS)z0 Flattened keys of subcontexts. css|] }|D]}|VqqdSr/r3).0rJdr3r3r4 [z#ContextList.keys..)setr from_iterabler9r3r3r4keysWszContextList.keysr/) rArBrC__doc__rHrNrOrV __classcell__r3r3rKr4r<s   rcCstj|||d|j|S)zt An instrumented Template render method, providing a signal that can be intercepted by the test Client. )sendertemplatecontext)rsendnodelistrender)r2r[r3r3r4instrumented_test_render^s r_c@s eZdZdS) _TestStateN)rArBrCr3r3r3r4r`gsr`cCs~ttdr td|durtj}t}|t_tj|_gtjdt_tj|_ |t_tj |_ dt_ t j |_tt _ gt_tdS)z Perform global pre-test setup, such as installing the instrumented template renderer and setting the email backend to the locmem email backend. saved_datazxsetup_test_environment() was already called and can't be called again without first calling teardown_test_environment().N testserverz-django.core.mail.backends.locmem.EmailBackend)hasattrr` RuntimeErrorrDEBUGrra ALLOWED_HOSTS allowed_hostsdebug EMAIL_BACKEND email_backendr_rendertemplate_renderr_routboxr)rhrar3r3r4r*ks$  r*cCs2tj}|jt_|jt_|jt_|j t _ t`t ` dS)z Perform any global post-test teardown, such as restoring the original template renderer and restoring the email sending functions. N)r`rargrrfrhrerjrirlrrkrrm)rar3r3r4r+sr+F) time_keeperkeepdb debug_sqlparallelaliasesc Ksr|durt}t|\}} g} |D]\} }d} |D]z} t| }| || | duf| dur| } |d| |jj|| ||jd dddWdn1sUwY|dkrt |D]&}|d| |jj t |d||d Wdn1swYqbqt| j t| jqq| D]\} }t| j t|jq|rtD]} dt| _q| S) zCreate the test databases.Nz Creating '%s'TEST SERIALIZET) verbosity autoclobberro serializez Cloning '%s'suffixruro)NullTimeKeeper get_unique_databases_and_mirrorsvaluesrappendtimedcreationcreate_test_db settings_dictrNrange clone_test_dbrEset_as_test_mirroritemsforce_debug_cursor)ru interactivernrorprqrrkwargstest_databasesmirrored_aliases old_namesdb_name first_aliasalias connectionindex mirror_aliasr3r3r4r)sN     r)cCsg}t}i}|D]&\}\}}t}|D] } ||| gq||s+td||||<q |rjd} g} |D]'\} \} }|| |rV|||| | |ffd} q8| | | |ffq8| sftd| }|s2|S)zp Reorder test_databases into an order that honors the dependencies described in TEST[DEPENDENCIES]. zHCircular dependency: databases %r depend on each other, but are aliases.FTz)Circular dependency in TEST[DEPENDENCIES])rTupdaterN isdisjointrissubsetr~)r dependenciesordered_test_databasesresolved_databasesdependencies_mapsig_rrall_depsrchangeddeferred signaturerr3r3r4dependency_ordereds8   rc Cs|durt}i}i}i}ttj}tD][}t|}|jd}|dr+|d||<q||vrp||j|jdgf}|tkrJ|dd|n|d|d|vr\|d||<q|tkrp|j|krp|dtg||<qt t | |}||fS)a Figure out which databases actually need to be created. Deduplicate entries in DATABASES that correspond the same database or are configured as test mirrors. Return two values: - test_databases: ordered mapping of signatures to (name, list of aliases) where all aliases share the same underlying database. - mirrored_aliases: mapping of mirror aliases to original aliases. NrsMIRRORNAMErxr DEPENDENCIES) rrrtest_db_signaturer setdefaultinsertr~rNdictrr) rrrrr default_sigrr test_settingsitemr3r3r4r|s4   r|cCsX|D]'\}}}|r)|dkr!t|D]}|jjt|d||dq|j|||qdS)z%Destroy all the non-mirror databases.rxryN)rrdestroy_test_dbrE) old_configrurqrorold_namedestroyrr3r3r4teardown_databases.s  rcCsX|p|j}|d}t|dkrd|dd}nd}t|ii|d}t||dS)N.rx) TEST_RUNNERsplitlenjoin __import__getattr)rtest_runner_class test_pathtest_module_name test_moduler3r3r4r <s   r c@sReZdZdZdddZddZddZd d Zd d Zd dZ ddZ ddZ dS)TestContextDecoratora A base class that can either be used as a context manager during tests or as a test function or unittest.TestCase subclass decorator to perform temporary alterations. `attr_name`: attribute assigned the return value of enable() if used as a class decorator. `kwarg_name`: keyword argument passing the return value of enable() if used as a function decorator. NcCr.r/) attr_name kwarg_name)r2rrr3r3r4r5Tr6zTestContextDecorator.__init__cCtr/NotImplementedErrorr9r3r3r4enableXzTestContextDecorator.enablecCrr/rr9r3r3r4disable[rzTestContextDecorator.disablecCs|Sr/)rr9r3r3r4 __enter__^szTestContextDecorator.__enter__cCs |dSr/)rr2exc_type exc_value tracebackr3r3r4__exit__a zTestContextDecorator.__exit__cs0t|tr|jfdd}||_|Std)Ncs4}|jjrt|j||dSr/)r addCleanuprrsetattr) inner_selfr[decorated_setUpr2r3r4setUphs   z2TestContextDecorator.decorate_class..setUpz1Can only decorate subclasses of unittest.TestCase) issubclassrr TypeError)r2clsrr3rr4decorate_classds z#TestContextDecorator.decorate_classcs>trtfdd}|Stfdd}|S)NcsN}jr ||j<|i|IdHWdS1s wYdSr/rargsrr[funcr2r3r4innerws  $z5TestContextDecorator.decorate_callable..innercsF}jr ||j<|i|WdS1swYdSr/rrrr3r4r~s   $)asyncioiscoroutinefunctionr)r2rrr3rr4decorate_callabless  z&TestContextDecorator.decorate_callablecCs6t|tr ||St|r||Stdt|)Nz!Cannot decorate object of type %s)rDtypercallablerr)r2 decoratedr3r3r4__call__s   zTestContextDecorator.__call__)NN) rArBrCrWr5rrrrrrrr3r3r3r4rHs  rcsDeZdZdZdZfddZddZddZd d Zd d Z Z S) r%a4 Act as either a decorator or a context manager. If it's a decorator, take a function and return a wrapped function. If it's a contextmanager, use it with the ``with`` statement. In either event, entering/exiting are called before and after, respectively, the function/block is executed. Nc ||_tdSr/)optionsrGr5r2rrKr3r4r5zoverride_settings.__init__c Csd|jvrz t|jdWn tytwttj}|jD] \}}t |||q&tj|_ |t_|jD]*\}}z t j tjj ||ddWq=tyg}z ||_|WYd}~q=d}~wwdS)NINSTALLED_APPSTrYsettingvalueenter)rr set_installed_apps Exceptionunset_installed_appsrr_wrappedrrwrappedrr\rLenable_exceptionr)r2overriderI new_valueexcr3r3r4rs0    zoverride_settings.enablecCsd|jvr t|jt_|`g}|jD]}tt|d}tjtjj ||dd}| |q|j dur:|j }d|_ ||D] \}}t |t rG|qz*modify_settings.enable..prependcrr3r3rrr3r4rrremovecrr3r3r)rr3r4rrzUnsupported action: %s) rrrFrrrrrDrErrGr)r2nameractionrK)rrr4rs&    zmodify_settings.enable)rArBrCrWr5rrrXr3r3rKr4r$s   r$cs2eZdZdZd fdd ZddZddZZS) r&z Act as a decorator. Override 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. Ncs,ddlm}||_||_||_tdS)Nr)registry)django.core.checks.registryr  new_checksdeployment_checksrGr5)r2rrr rKr3r4r5s zoverride_system_checks.__init__cCs|jj|_t|j_|jD]}|jj|gt|ddRq |jj|_|jdurDt|j_|jD]}|jj|gt|ddRddiq0dSdS)Ntagsr3deployT) r registered_checks old_checksrTrregisterrrold_deployment_checks)r2checkr3r3r4rs       $zoverride_system_checks.enablecCs|j|j_|j|j_dSr/)rr rrrr9r3r3r4r$s zoverride_system_checks.disabler/rArBrCrWr5rrrXr3r3rKr4r& s  r&cstdfddddddfdd d d fd d dd}|dd}|dd}|dsJd}||}||}|t|}|t|}||S)al Try 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. Ignore comment nodes, processing instructions, document type node, and leading and trailing whitespaces. Based on https://github.com/lxml/lxml/blob/master/src/lxml/doctestcompare.py z[ \t\n][ \t\n]+cs d|S)N )sub)v)_norm_whitespace_rer3r4norm_whitespace4rz$compare_xml..norm_whitespacecSsddd|jDS)Ncss"|] }|jtjkr|jVqdSr/)nodeTyper TEXT_NODEdatarPcr3r3r4rR8s  z2compare_xml..child_text..)r childNodeselementr3r3r4 child_text7szcompare_xml..child_textcSsdd|jDS)NcSsg|] }|jtjkr|qSr3)rr ELEMENT_NODEr"r3r3r4r<s z1compare_xml..children..)r$r%r3r3r4children;zcompare_xml..childrencs |Sr/r3r%)r'rr3r4norm_child_text?rz$compare_xml..norm_child_textcSst|jSr/)r attributesrr%r3r3r4 attrs_dictBzcompare_xml..attrs_dictcsx|j|jkrdS||krdS||krdS|}|}t|t|kr.dStfddt||DS)NFc3s|] \}}||VqdSr/r3)rPwantgot) check_elementr3r4rRPrSz5compare_xml..check_element..)tagNamerallzip) want_element got_element want_children got_children)r-r1r)r+r3r4r1Es z"compare_xml..check_elementcSs.|jD]}|jtjtjtjfvr|SqdSr/)r$rr COMMENT_NODEDOCUMENT_TYPE_NODEPROCESSING_INSTRUCTION_NODE)documentnoder3r3r4 first_nodeRs zcompare_xml..first_nodez\n z%s)recompilestripreplace startswithr )r/r0r>wrapper want_rootgot_rootr3)rr-r1r'r)r+rr4 compare_xml)s"       rHc@sLeZdZdZddZddZddZdd Zed d Z d d Z ddZ dS)r!zU Context manager that captures queries executed by the specified connection. cCs ||_dSr/)r)r2rr3r3r4r5pr;zCaptureQueriesContext.__init__cCr7r/)itercaptured_queriesr9r3r3r4__iter__sr;zCaptureQueriesContext.__iter__cCs |j|Sr/)rJ)r2rr3r3r4rHvr;z!CaptureQueriesContext.__getitem__cCr7r/)rrJr9r3r3r4__len__yr;zCaptureQueriesContext.__len__cCs|jj|j|jSr/)rqueriesinitial_queries final_queriesr9r3r3r4rJ|sz&CaptureQueriesContext.captured_queriescCs>|jj|_d|j_|jt|jj|_d|_tt |S)NT) rrensure_connectionr queries_logrNrOr disconnectrr9r3r3r4rs   zCaptureQueriesContext.__enter__cCs2|j|j_tt|durdSt|jj|_dSr/)rrrconnectrrrQrOrr3r3r4rs  zCaptureQueriesContext.__exit__N) rArBrCrWr5rKrHrLpropertyrJrrr3r3r3r4r!ls  r!cs,eZdZfddZddZddZZS)r"c s:||_d|jvs d|jvrtj|_ntj|_tdS)Nmessagemodule) ignore_kwargswarningsfilterwarnings filter_func simplefilterrGr5rrKr3r4r5s  zignore_warnings.__init__cCs*t|_|j|jdi|jdS)Nignore)r\)rXcatch_warningsrrZrWr9r3r3r4rs  zignore_warnings.enablecCs|jjtdSr/)r]rsysexc_infor9r3r3r4rzignore_warnings.disable)rArBrCr5rrrXr3r3rKr4r"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.cgs8tjdd}tj|z dVW|t_dS|t_w)z5Context manager to temporarily add paths to sys.path.N)r^pathr)paths_orig_sys_pathr3r3r4extend_sys_paths  rdccs*|z dVW|dS|w)z?Clear the cache of an LRU cache object on entering and exiting.N) cache_clear)lru_cache_objectr3r3r4rs rc csHtt|}tt|tztt|VWtt||dStt||w)aReturn 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)rr^rr) stream_name orig_stdoutr3r3r4captured_outputs  ricCtdS)zCapture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello ") stdoutrir3r3r3r4captured_stdoutrmcCrj)zCapture the output of sys.stderr: with captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello ") stderrrlr3r3r3r4captured_stderrrnrpcCrj)aCapture 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") stdinrlr3r3r3r4captured_stdins rrc#s2tj}fddt_z dVW|t_dS|t_w)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. csSr/r3r3tr3r4szfreeze_time..N)time)rt _real_timer3rsr4 freeze_times  rxcCs6ttdud|}tdddddddidgd |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. Nzthis test requires jinja2z/django.template.backends.django.DjangoTemplatesT)BACKENDAPP_DIRSz&django.template.backends.jinja2.Jinja2keep_trailing_newline)ryrzOPTIONS) TEMPLATES)rjinja2r%)rr3r3r4require_jinja2src0eZdZdZfddZddZddZZS)override_script_prefixzEDecorator or context manager to temporary override the script prefix.crr/)prefixrGr5)r2rrKr3r4r5rzoverride_script_prefix.__init__cCst|_t|jdSr/)r old_prefixrrr9r3r3r4rszoverride_script_prefix.enablecCst|jdSr/)rrr9r3r3r4r!r.zoverride_script_prefix.disablerr3r3rKr4rs  rc@s eZdZdZddZddZdS)LoggingCaptureMixinzn Capture the output from the 'django' logger and store it on the class's logger_output attribute. cCs8td|_|jjdj|_t|_|j|jjd_dS)Ndjangor)logging getLoggerloggerhandlersstream old_streamr logger_outputr9r3r3r4r*s zLoggingCaptureMixin.setUpcCs|j|jjd_dSr<)rrrrr9r3r3r4tearDown0r`zLoggingCaptureMixin.tearDownN)rArBrCrWrrr3r3r3r4r%s rcr)r#a Act as either a decorator or a context manager to register models defined in its wrapped context to an isolated registry. The list of installed apps the isolated registry should contain must be passed as arguments. Two optional keyword arguments can be specified: `attr_name`: attribute assigned the isolated registry if used as a class decorator. `kwarg_name`: keyword argument passing the isolated registry if used as a function decorator. cs||_tjdi|dS)Nr3)installed_appsrGr5)r2rrrKr3r4r5Dszisolate_apps.__init__cCs"tj|_t|j}ttd||SN default_apps)rrold_appsr rr)r2r r3r3r4rHs  zisolate_apps.enablecCsttd|jdSr)rrrr9r3r3r4rNszisolate_apps.disablerr3r3rKr4r#4s  r#c@s(eZdZddZeddZddZdS) TimeKeepercCstt|_dSr/) collections defaultdictrrecordsr9r3r3r4r5Sr*zTimeKeeper.__init__c cs\|j|t}zdVWt|}|j||dSt|}|j||wr/)rrv perf_counterr~)r2r  start_timeend_timer3r3r4rVs   zTimeKeeper.timedcCs@|jD]\}}|D]}d||f}tj|tjq qdS)Nz %s took %.3fs)rrr^rowriteoslinesep)r2r  end_times record_timerecordr3r3r4 print_results`s  zTimeKeeper.print_resultsN)rArBrCr5rrrr3r3r3r4rRs   rc@s eZdZeddZddZdS)r{ccs dVdSr/r3)r2r r3r3r4rhs zNullTimeKeeper.timedcCsdSr/r3r9r3r3r4rlrzNullTimeKeeper.print_resultsN)rArBrCrrrr3r3r3r4r{gs  r{csfdd}|S)z0Decorator to add tags to a test class or method.cs0t|dr|j|_|St|dt|S)Nr)rcrunionrrT)objrr3r4 decoratorrs ztag..decoratorr3)rrr3rr4r'ps r') lookup_namec gsTz|D]}|||qdVW|D]}|||qdS|D]}|||q w)z Context manager to temporarily register lookups on a model field using lookup_name (or the lookup's lookup_name if not provided). N)register_lookup_unregister_lookup)fieldrlookupslookupr3r3r4r{s rr/)rF)^rrrrr@r^rvrX contextlibr functoolsrior itertoolsrtypesrunittestrrr xml.dom.minidomr r django.appsr django.apps.registryr django.confrr django.corerdjango.core.exceptionsrdjango.core.signalsr django.dbrrrdjango.db.models.optionsrdjango.templaterdjango.test.signalsrr django.urlsrrdjango.utils.translationrr~ ImportError__all__rc TZ_SUPPORTrrrr_r`r*r+r)rr|rr rr%r$r&rHr!r"r(rdrrirmrprrrxrrrr#rr{r'rr3r3r3r4s                 " $ 2 * 3  FN0C'