o 3ai@sDddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z m Z ddlmZddlmZddlmZddlmZdd lmZmZmZmZmZmZmZdd lmZdd lm Z dd l!m"Z"dd l#m$Z$ddl%m&Z&ddl'm(Z(m)Z)ddl*m+Z+ddl,m-Z-m.Z.ddl/m0Z0ddl1m2Z2ddl3m4Z4ddl5m6Z6m7Z7ddl8m9Z9m:Z:m;Z;mZ>ddl?m@Z@ddlAmBZBmCZCddlDmEZEmFZFddlGmHZHmIZIddlJmKZKmLZLddlMmNZNmOZOmPZPmQZQmRZRddlSmTZTddlUmVZVdd lWmXZXd!ZYd"d#ZZd$d%Z[Gd&d'd'eNZ\Gd(d)d)Z]Gd*d+d+e]Z^Gd,d-d-Z_Gd.d/d/ej`ZaGd0d1d1eaZbdPd2d3ZcGd4d5d5ZdGd6d7d7ebZ`Gd8d9d9Zed:d;Zfdd?Zhd@dAZiGdBdCdCe7ZjGdDdEdEe-ZkGdFdGdGekZlGdHdIdIekZmGdJdKdKejnZoGdLdMdMebZpGdNdOdOZqdS)QN)Counter)contextmanager)copydeepcopy)get_close_matches)wraps) _DebugResult) safe_repr) parse_qslunquote urlencodeurljoinurlparseurlsplit urlunparse) url2pathname) async_to_sync)apps)settings)mail)ImproperlyConfiguredValidationError)locks) WSGIHandler get_path_info) call_command)no_style)emit_post_migrate_signal)ThreadedWSGIServerWSGIRequestHandler)DEFAULT_DB_ALIAS connection connections transaction) CharField) QueryDict)split_domain_port validate_host) AsyncClientClient)HTMLParseError parse_html)setting_changedtemplate_rendered)CaptureQueriesContext ContextList compare_xmlmodify_settingsoverride_settings)RemovedInDjango41Warning) classproperty)serve)TestCaseTransactionTestCaseSimpleTestCaseskipIfDBFeatureskipUnlessDBFeaturecCs$|durg}|St|ts|g}|S)zc Put value into a list if it's not already one. Return an empty list if value is None. N) isinstancelist)valuer>7/usr/lib/python3/dist-packages/django/test/testcases.pyto_list4s  r@c CsTzt|}W|Sty)}zd||f}||||WYd}~|Sd}~ww)Nz%s %s)r+r*fail_formatMessage)selfhtmluser_msgmsgdome standardMsgr>r>r?assert_and_parse_html@s  rJcs(eZdZfddZfddZZS)_AssertNumQueriesContextcs||_||_t|dSN) test_casenumsuper__init__)rCrMrNr! __class__r>r?rPJsz!_AssertNumQueriesContext.__init__cs`t||||durdSt|}|j||jd||jdddt|jddDfdS)Nz:%d queries executed, %d expected Captured queries were: %s css$|] \}}d||dfVqdS)z%d. %ssqlNr>).0iqueryr>r>r? Xs z4_AssertNumQueriesContext.__exit__..)start) rO__exit__lenrM assertEqualrNjoin enumeratecaptured_queries)rCexc_type exc_value tracebackexecutedrQr>r?r[Os  z!_AssertNumQueriesContext.__exit__)__name__ __module__ __qualname__rPr[ __classcell__r>r>rQr?rKIs rKc@s<eZdZddZddZddZddZd d Zd d Zd S)_AssertTemplateUsedContextcCs$||_||_g|_g|_t|_dSrL)rM template_namerendered_templatesrendered_template_namesr/context)rCrMrjr>r>r?rP`s  z#_AssertTemplateUsedContext.__init__cKs.|j||j|j|jt|dSrL)rkappendrlnamermr)rCsendersignaltemplatermkwargsr>r>r?on_template_rendergs z-_AssertTemplateUsedContext.on_template_rendercCs |j|jvSrLrjrlrCr>r>r?testl z_AssertTemplateUsedContext.testcC d|jS)Nz%s was not rendered.rjrvr>r>r?messageo z"_AssertTemplateUsedContext.messagecCst|j|SrL)r-connectrtrvr>r>r? __enter__rs z$_AssertTemplateUsedContext.__enter__cCs`t|j|dur dS|s.|}|jr"|dd|j7}n|d7}|j |dSdS)Nz& Following templates were rendered: %s, z No template was rendered.) r- disconnectrtrwr{rkr^rlrMrA)rCrarbrcr{r>r>r?r[vs  z#_AssertTemplateUsedContext.__exit__N) rerfrgrPrtrwr{r~r[r>r>r>r?ri_s ric@eZdZddZddZdS)_AssertTemplateNotUsedContextcCs |j|jvSrLrurvr>r>r?rwrxz"_AssertTemplateNotUsedContext.testcCry)Nz%s was rendered.rzrvr>r>r?r{r|z%_AssertTemplateNotUsedContext.messageN)rerfrgrwr{r>r>r>r?rs rc@r)_DatabaseFailurecC||_||_dSrL)wrappedr{)rCrr{r>r>r?rP z_DatabaseFailure.__init__cCs t|jrL)AssertionErrorr{rvr>r>r?__call__r|z_DatabaseFailure.__call__N)rerfrgrPrr>r>r>r?rs rcseZdZeZeZdZdZe Z dZ gdZ e fddZe ddZe dd Ze d d Ze fd d ZdMddZddZdNfdd ZddZddZddZddZ   dOd!d"ZdPd#d$Zd%d&ZdQd'd(ZdRd)d*ZdPd+d,Z dPd-d.Z d/d0Z!dSd1d2Z"dTd3d4Z#e$d5d6Z%d7d8Z&d9d:Z'd;d<Z(  dTd=d>Z)dMd?d@Z*dMdAdBZ+dUdCdDZ,dMdEdFZ-dMdGdHZ.dMdIdJZ/dMdKdLZ0Z1S)Vr8NzDatabase %(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.))r}r")temporary_connectionr")cursorqueries)chunked_cursorrcsTt|jrtdi|j|_|j|jr$t|j|_|j| dS)Nr>) rO setUpClass_overridden_settingsr2_cls_overridden_contextenable_modified_settingsr1_cls_modified_context_add_databases_failuresclsrQr>r?rs     zSimpleTestCase.setUpClasscCsl|jdkr ttS|jD]$}|tvr0d|j|j|f}t|tt}|r,|d|d7}t|q t|jS)N__all__zH%s.%s.databases refers to %r which is not defined in settings.DATABASES.z Did you mean %r?r) databases frozensetr"rfrgrr<r)raliasr{ close_matchesr>r>r?_validate_databasess   z"SimpleTestCase._validate_databasescCsv||_tD]1}||jvrqt|}|jD]!\}}|jd|j|jf||d}t||}t||t ||qqdS)Nz%s.%s)rwr operation) rrr"_disallowed_connection_methods_disallowed_database_msgrfrggetattrsetattrr)rrr!rorr{methodr>r>r?rs   z&SimpleTestCase._add_databases_failurescCsJtD] }||jvr qt|}|jD]\}}t||}t|||jqqdSrL)r"rrrrr)rrr!ro_rr>r>r?_remove_databases_failuress  z)SimpleTestCase._remove_databases_failurescsR|t|dr|jt|dt|dr"|jt|dtdS)Nrr)rhasattrrdisabledelattrrrO tearDownClassrrQr>r?rs      zSimpleTestCase.tearDownClasscCs||dS)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(). N)_setup_and_call)rCresultr>r>r?rszSimpleTestCase.__call__cCst}|j|dddS)z?Perform the same as __call__(), without catching the exception.T)debugN)rr)rC debug_resultr>r>r?rszSimpleTestCase.debugFcst||j}t|jddpt|dd}t|r!t||jt||s?z|Wnty>|r3| |t YdSw|rGt nt ||slz|WdStyk|r`| |t YdSwdS)a Perform the following in order: pre-setup, run test, post-teardown, skipping pre/post hooks if test is set to be skipped. If debug=True, reraise any errors in setup and use super().debug() instead of __call__() to run the test. __unittest_skip__FN)r_testMethodNamerRasyncioiscoroutinefunctionrr _pre_setup ExceptionaddErrorsysexc_inforOrr_post_teardown)rCrr testMethodskippedrQr>r?rs8        zSimpleTestCase._setup_and_callcCs||_||_gt_dS)zo Perform pre-test setup: * Create a test client. * Clear the mail test outbox. N) client_classclientasync_client_class async_clientroutboxrvr>r>r?r#s   zSimpleTestCase._pre_setupcCdS)zPerform post-test things.Nr>rvr>r>r?r-szSimpleTestCase._post_teardowncKtdi|S)z A context manager that temporarily sets a setting and reverts to the original value when exiting the context. Nr>)r2rCrsr>r>r?r1zSimpleTestCase.settingscKr)z A context manager that temporarily applies changes a list setting and reverts back to the original value when exiting the context. Nr>)r1rr>r>r?r18rzSimpleTestCase.modify_settings.Tc Cs|r|d7}t|drG||j|d|j|f||jdd||d|jdd|f|jd\}}||j||d|j|fno||j||d|j|f|j}t|\}} } } } | d swt|j d |}t|j d | } |rt | \} }| rt | t j std || f|jjpi}|jj| t| fd |d ki|}||j||d| |j|f||||d||fdS)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)rrYzPInitial 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)/ 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).securehttpszKCouldn't retrieve redirection page '%s': response code was %d (expected %d)z*Response redirected to '%s', expected '%s'N)r assertTruer status_coder]urlr startswithr requestr&r'r ALLOWED_HOSTS ValueErrorrextragetr%assertURLEqual)rCresponse expected_urlrtarget_status_code msg_prefixfetch_redirect_responserschemenetlocpathrWfragmentdomainportrredirect_responser>r>r?assertRedirects?sx      zSimpleTestCase.assertRedirectscCs.dd}||||||d||fdS)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. cSs@t|}t|\}}}}}}tt|}t||||t||fS)z'Sort the URL's query string parameters.)strrsortedr rr )rrrrparamsrWr query_partsr>r>r? normalizes z0SimpleTestCase.assertURLEqual..normalizezExpected '%s' to equal '%s'.N)r])rCurl1url2rrr>r>r?rs  zSimpleTestCase.assertURLEqualc Cst|drt|jr|js||r|d7}||j||d|j|f|jr0d|j}n|j }t |t r:|rIt |}| |j}d|}nt|}|r]t||dd}t||dd}||}|||fS)Nrenderrz=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:)rcallabler is_renderedr]r streamingr^streaming_contentcontentr;bytesrdecodecharsetreprrJcount) rCrtextrrrDr text_repr real_countr>r>r?_assert_containss.    zSimpleTestCase._assert_containsc Cs\||||||\}}}|dur ||||d|||fdS||dk|d|dS)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)rzCouldn't find %s in response)rr]r) rCrrrrrrDrrr>r>r?assertContainss  zSimpleTestCase.assertContainscCs2||||||\}}}||d|d|dS)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. rzResponse should not contain %sN)rr])rCrrrrrDrrr>r>r?assertNotContainss  z SimpleTestCase.assertNotContainsc Cs6|r|d7}t|j}|s||dt|}d}t|D]m\}} || vr'qd}|D]_} |rr|| |jvrQ| |j|} || | v|d|||| t| fq+|| |jvre||d|||fq+||d|||fq+| |} || | v|d||| | pd fq+q|s||d |d Sd S) zd Assert that a form used to render the response has a specific field error. r8Response 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)zr>r?assertFormErrorsV  zSimpleTestCase.assertFormErrorcCs|r|d7}t|j}|s||dt|}d}t|D]\} } || vr'qd}|D]} |dur|| |j|jvrZ| |j|j|} || | v|d|||| | t| fq+|| |j|jvrr||d|||| fq+||d||| |fq+|dur| |j| } | | |d ||| f|| | v|d ||| | t| fq+| | }| | |d || f|| |v|d || | t|fq+q|s||d |dSdS)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. rrFTNziThe 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@rmrAr_formsrrrrr assertFalsenon_form_errors)rCrformset form_indexrrrr found_formsetrVrmrrrr r>r>r?assertFormsetErrors~     /z!SimpleTestCase.assertFormsetErrorcCs|dur |dur td|r|d7}|dur#|dur#t|ds#tdt|dr.|dur9|r9|r4|}d}|d|fSdd|jD}d||fS)Nz7response and/or template_name argument must be providedr templateszsassertTemplateUsed() and assertTemplateNotUsed() are only usable on responses fetched using the Django test Client.cSsg|] }|jdur|jqSrL)ro)rUtr>r>r? sz8SimpleTestCase._assert_template_used..) TypeErrorrrr)rCrrjrtemplate_namesr>r>r?_assert_template_usedks  z$SimpleTestCase._assert_template_usedc Cs||||\}}}|rt||S|s||d|||v|d|d|f|durE|||||d||||fdSdS)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: %srNzZTemplate '%s' was expected to be rendered %d time(s) but was actually rendered %d time(s).)rrirArr^r]r)rCrrjrrcontext_mgr_templaterr>r>r?assertTemplateUseds*    z!SimpleTestCase.assertTemplateUsedcCs>||||\}}}|rt||S|||v|d|dS)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)rrr )rCrrjrrrr>r>r?assertTemplateNotUseds   z$SimpleTestCase.assertTemplateNotUsedccsJ|| }|VWdn1swY||tt||dSrL)assertInrr)rCfunccm_attrexpected_exceptionexpected_messagecmr>r>r?_assert_raises_or_warns_cms  z)SimpleTestCase._assert_raises_or_warns_cmc Osdd}|r|^}}|||||}|dur|S|||i|WddS1s+wYdSrL)r) rCrrrrargsrs callable_objrr>r>r?_assertFooMessages"z SimpleTestCase._assertFooMessagecO |j|jd||g|Ri|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)rCrrrrsr>r>r?assertRaisesMessages z"SimpleTestCase.assertRaisesMessagecOr")zf Same as assertRaisesMessage but for assertWarns() instead of assertRaises(). warning)r! assertWarns)rCexpected_warningrrrsr>r>r?assertWarnsMessages z!SimpleTestCase.assertWarnsMessagec Cs|durg}|dur i}||i|}||ii|ddi}|D]\} } ||| | ||| | q$|D]H\} } |t } || Wdn1sXwY|| jj| |t } || Wdn1szwY|| jj| q?|jdg} |jD]-}|t } ||Wdn1swY|| jj| ||||qt |t r| ddd| ||i||dSdS)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 NrequiredF) min_length max_length) itemsr]cleanr$rr#messageserror_messages empty_values issubclassr$updateassertIsInstance)rC fieldclassvalidinvalid field_args field_kwargs empty_valuer*optionalinputoutputrcontext_managererror_requiredrHr>r>r?assertFieldOutputs:         z SimpleTestCase.assertFieldOutputcCst|||d}t|||d}||krBdt|dt|df}ddtt|t|}|||}|| ||dSdS)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 != %sTrSN) rJr r^difflibndiffr splitlines_truncateMessagerArB)rChtml1html2rFdom1dom2rIdiffr>r>r?assertHTMLEqual s  zSimpleTestCase.assertHTMLEqualcCsVt|||d}t|||d}||kr)dt|dt|df}||||dSdS)z>Assert that two HTML snippets are not semantically equivalent.rCr%s == %sTN)rJr rArB)rCrIrJrFrKrLrIr>r>r?assertHTMLNotEqualsz!SimpleTestCase.assertHTMLNotEqualc Csjt||dd}t||dd}||}|dur'||||d|||fdS||dk|d|dS)NrCrz4Found %d instances of '%s' in response (expected %d)rzCouldn't find '%s' in response)rJrr]r)rCneedlehaystackrrrr>r>r? assertInHTML's zSimpleTestCase.assertInHTMLcCszt|}Wntjy|d|Ynwt|tr6zt|}Wnty5|d|Ynw|j|||ddS)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: %rrFN)jsonloadsJSONDecodeErrorrAr;rrr]rCraw expected_datarFdatar>r>r?assertJSONEqual3s  zSimpleTestCase.assertJSONEqualcCszt|}Wntjy|d|Ynwt|tr7zt|}Wntjy6|d|Ynw|j|||ddS)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. rTrUrVN)rWrXrYrAr;rassertNotEqualrZr>r>r?assertJSONNotEqualDs z!SimpleTestCase.assertJSONNotEqualc Cszt||}Wn ty'}zd|}||||WYd}~dSd}~ww|sVdt|dt|df}ddt||}| ||}||||dSdS)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 %sNrDTrS) r0rrArBr r^rErFrGrH)rCxml1xml2rFrrHrIrMr>r>r?assertXMLEqualUs  zSimpleTestCase.assertXMLEqualc Cszt||}Wn ty'}zd|}||||WYd}~dSd}~ww|rAdt|dt|df}||||dSdS)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. raNrOT)r0rrArBr )rCrbrcrFrrHrIr>r>r?assertXMLNotEqualis z SimpleTestCase.assertXMLNotEqualrL)F)rrrT)r)NrrF)rrF)NNrN)NNr)Nr)2rerfrgr)rr(rrrsetrrr classmethodrrrrrrrrrrrr1rrrrrrrrrrrrr!r%r)rBrNrPrSr^r`rdrerhr>r>rQr?r8sn     '  T   8 P      .   r8cseZdZdZdZdZehZdZdZ fddZ e dddZ d d Z d d Zd dZfddZddZdddZdedddZZS)r7FNzDatabase %(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 st|jdur,t|jtjtjj d|jdd|j ddD] }t dd|dq"z| Wnt yO|jdurNttjtjj dtjddw|j ddD] }t|jqVdS) 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. NINSTALLED_APPSTrpsettingr=enterFinclude_mirrorsr) verbosity interactivedb)rOravailable_appsrset_available_appsr,sendr_wrappedrR_databases_namesr_fixture_setuprunset_available_appsrhr" queries_logclearrCdb_namerQr>r?rs6       zTransactionTestCase._pre_setupTcsfddtDS)Ncs0g|]}|jvrst|jdds|qS)TESTMIRROR)rr" settings_dictrUrrrmr>r?rs z8TransactionTestCase._databases_names..r"rr>rr?rus z$TransactionTestCase._databases_namesc Cst|}|jjrT|jt|j}|rVtj |d/| }|D]}| |q#Wdn1s5wYWddSWddS1sMwYdSdSdS)Nusing) r"featuressupports_sequence_resetopssequence_reset_by_name_sqlr introspection sequence_listr#atomicrexecute)rCr{connsql_listrrTr>r>r?_reset_sequencess"   "z$TransactionTestCase._reset_sequencescCs|jddD]E}|jr|||jr9tt|dr9|jdur#tt|j t|j |jdur9t |j|j rKtdg|j Rid|dqdS)NFrl_test_serialized_contentsloaddatarrndatabase)rureset_sequencesrserialized_rollbackrr"rqrrwcreationdeserialize_db_from_stringrrrfixturesrrzr>r>r?rvs"     z"TransactionTestCase._fixture_setupcCrNTr>rvr>r>r?_should_reload_connectionsz.TransactionTestCase._should_reload_connectionsc sz2|t|rtD]}|qW|jdur1t t j t j jdt jdddSdS|jdurIt t j t j jdt jddww)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. NrhFri)_fixture_teardownrOrrr"allcloserqrrwr,rsrrtrRrh)rCrrQr>r?rs,       z"TransactionTestCase._post_teardownc CsP|jddD]}|jdup|jott|d}tddd|d|jdu|dqdS)NFrlrflushr)rnrorr allow_cascadeinhibit_post_migrate)rurqrrr"r)rCr{rr>r>r?rs  z%TransactionTestCase._fixture_teardowncCst|}|dur$|r$t|dtr$|r$t|dts$tjdtddt}|}|dur/t||}|s=|jt |t ||dSt |dkrOt |drO|j sOt d|jt|||dS) NrzIn Django 4.1, repr() will not be called automatically on a queryset when compared to string values. Set an explicit 'transform' to silence this warning.r+category stacklevelrVrYorderedzKTrying to compare non-ordered queryset against more than one ordered values)r<r;rwarningswarnr3rmapr]rr\rrr)rCqsvalues transformrrFr/r>r>r?assertQuerysetEquals0   z'TransactionTestCase.assertQuerysetEqualrcOsXt|}t|||}|dur|S|||i|WddS1s%wYdSrL)r"rK)rCrNrrrrsrrmr>r>r?assertNumQueries2s "z$TransactionTestCase.assertNumQueries)T)NTNrL)rerfrgrrqrr rrrrrgrurrvrrrrrrhr>r>rQr?r7zs$ %     r7cCs0|durtndd|D}tdd|DS)zX Return whether or not all (or specified) connections support transactions. Ncss|]}t|VqdSrLrrr>r>r?rXBz3connections_support_transactions..css|]}|jjVqdSrL)rsupports_transactions)rUrr>r>r?rXCr)r"r)aliasesconnsr>r>r? connections_support_transactions=src@s4eZdZdZdZddZddZddZd d Zd S) TestDataa Descriptor to provide TestCase instance isolation for attributes assigned during the setUpTestData() phase. Allow safe alteration of objects assigned in setUpTestData() by test methods by exposing deep copies instead of the original objects. Objects are deep copied using a memo kept on the test case instance in order to maintain their original relationships. _testdata_memocCrrLror])rCror]r>r>r?rPSrzTestData.__init__cCs:z t||j}W|Styi}t||j|Y|SwrL)r memo_attrAttributeErrorr)rCtestcasememor>r>r?get_memoWs zTestData.get_memocCs||dur|jS||}zt|j|}Wn ty4d|j|j|j|jf}tj|t dd|j}Ynwt ||j||S)NzAssigning objects which don't support copy.deepcopy() during setUpTestData() is deprecated. Either assign the %s attribute during setUpClass() or setUp(), or add support for deepcopy() to %s.%s.%s.r+r) r]rrrrorfrgrrr3r)rCinstanceownerrr]rFr>r>r?__get___s$   zTestData.__get__cCsd|j|jfS)Nzrrvr>r>r?__repr__wszTestData.__repr__N) rerfrg__doc__rrPrrrr>r>r>r?rFs  rcseZdZdZeddZeddZeddZefdd Zefd d Z ed d Z fddZ fddZ fddZ ddZeeeddddZZS)r6a 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. cCs2i}|D]}tj|d||<||q|S)z*Open atomic blocks for multiple databases.r)rur#rr~ratomicsr{r>r>r?_enter_atomicss  zTestCase._enter_atomicscCs6t|D]}tjd|d||dddqdS)z5Rollback atomic blocks opened by the previous method.TrN)reversedrur# set_rollbackr[rr>r>r?_rollback_atomicsszTestCase._rollback_atomicscCs t|jSrL)rrrr>r>r?_databases_support_transactionss z(TestCase._databases_support_transactionsc st|s dSdtj_zo||_|jrD|j ddD]%}zt dg|jRid|dWqt yC| |j| w|j}z|Wnt ya| |j| w|jD]\}}|||ur{t||t||qgWdSt ydtj_w)NFrlrrrT)rOrrr#Atomic_ensure_durabilityr cls_atomicsrrurrrr__dict__r setUpTestDatar/rrr)rr{ pre_attrsror=rQr>r?rs@  "       zTestCase.setUpClasscs@dtj_|r||jtD]}|qt dSr) r#rrrrrr"rrrOrrrrQr>r?rs    zTestCase.tearDownClasscCr)z#Load initial data for the TestCase.Nr>rr>r>r?rszTestCase.setUpTestDatacs|rdStS)NF)rrOrrvrQr>r?rs z#TestCase._should_reload_connectionscs6|s |tS|jrJd||_dS)Nz4reset_sequences cannot be used on TestCase instances)rrrOrvrrrrvrQr>r?rvs  zTestCase._fixture_setupc s`|s tSzt|D]}|t|rt|qW||j dS||j wrL) rrOrrru_should_check_constraintsr"check_constraintsrrrzrQr>r?rs  zTestCase._fixture_teardowncCs|jjo |j o |SrL)rcan_defer_constraint_checksneeds_rollback is_usable)rCr!r>r>r?rs z"TestCase._should_check_constraintsF)rrc csg}tt|j}z&|VWt|j|d}dd|D|dd<|r-|D]}|q'dSdSt|j|d}dd|D|dd<|rO|D]}|qIww)z=Context manager to capture transaction.on_commit() callbacks.NcSsg|]\}}|qSr>r>)rUsidsrr>r>r?rz5TestCase.captureOnCommitCallbacks..)r\r" run_on_commit)rrr callbacks start_countrcallbackr>r>r?captureOnCommitCallbackss&z!TestCase.captureOnCommitCallbacks)rerfrgrrgrrrrrrrrvrrrr rrhr>r>rQr?r6{s*         r6c@s*eZdZdZddZddZd ddZdS) CheckConditionz1Descriptor class for deferred condition checking.cGs ||_dSrL) conditions)rCrr>r>r?rPr|zCheckCondition.__init__cCs|jg|j||fRSrL)rRr)rC conditionreasonr>r>r? add_conditionszCheckCondition.add_conditionNcCsDtdd|jDr dS|jD]\}}|rd|_||_dSqdS)Ncss|] }t|ddVqdS)rFN)r)rUbaser>r>r?rXsz)CheckCondition.__get__..TF)any __bases__rr__unittest_skip_why__)rCrrrrr>r>r?rszCheckCondition.__get__rL)rerfrgrrPrrr>r>r>r?rs rcsfdd}|S)Ncsttr ttjstfdd}|Stdd}|r+tj|vr2fddj d}t|t rF| _ S|durQt f_ S)Ncsj|r&t|dtjr&tjt|ddivr&td|d|djjtjfr.t |i|S)NrrzL%s cannot be used on %s as %s doesn't allow queries against the %r database.) r;unittestr6r!rrrrRrgSkipTest)rrs)rror test_funcr>r? skip_wrappers  z6_deferredSkip..decorator..skip_wrapperrcstdtjf)NzN%s cannot be used on %s as it doesn't allow queries against the '%s' database.)rr!rr>)ro test_itemr>r?r+s z3_deferredSkip..decorator..conditionrT)r;typer4rr6rrr!rrrrrr)rrrskiprror)rrr? decorators$    z _deferredSkip..decoratorr>)rrrorr>rr? _deferredSkips*rctfdddddS)zASkip a test if a database has at least one of the named features.cstddDS)Ncs|] }ttj|dVqdSFNrr!rrUfeaturer>r>r?rX@z4skipIfDBFeature....rr>rr>r?@sz!skipIfDBFeature..zDatabase has feature(s) %srr9rr^rr>rr?r9=   r9cr)z9Skip a test unless a database has all the named features.ctddD S)Ncsrrrrr>r>r?rXIrz8skipUnlessDBFeature....)rr>rr>r?rIrz%skipUnlessDBFeature..z'Database doesn't support feature(s): %srr:rrr>rr?r:Frr:cr)zr>r?rXRrz;skipUnlessAnyDBFeature....rr>rr>r?rRrz(skipUnlessAnyDBFeature..z2Database doesn't support any of the feature(s): %srskipUnlessAnyDBFeaturerrr>rr?rOrrc@seZdZdZddZdS)QuietWSGIRequestHandlerz A WSGIRequestHandler that doesn't log to standard output any of the requests received, so as to not clutter the test result output. cGsdSrLr>)rr>r>r? log_message]rz#QuietWSGIRequestHandler.log_messageN)rerfrgrrr>r>r>r?rXs rcsPeZdZdZfddZddZddZfdd Zd d Zfd 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. cs"||_t||_tdSrL) applicationr get_base_urlbase_urlrOrP)rCrrQr>r?rPfszFSFilesHandler.__init__cCs||jdo |jd 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+rY)rr)rCrr>r>r?_should_handlekszFSFilesHandler._should_handlecCs|t|jdd}t|S)z?Return the relative path to the file on disk for the given URL.r+N)r\rr)rCr relative_urlr>r>r? file_pathsszFSFilesHandler.file_pathcsDddlm}||jrz||WS|yYnwt|S)Nr)Http404) django.httprrrr5rO get_response)rCrrrQr>r?rxs     zFSFilesHandler.get_responsecCs>||j}tt|}|ddd}t|||dS)N\r) document_root) rr posixpathnormpathr replacelstripr5 get_base_dir)rCr os_rel_pathfinal_rel_pathr>r>r?r5s zFSFilesHandler.servecs(|t|s |||St||SrL)rrrrOr)rCenvironstart_responserQr>r?rs zFSFilesHandler.__call__) rerfrgrrPrrrr5rrhr>r>rQr?ras    rc@ eZdZdZddZddZdS)_StaticFilesHandlerz Handler for serving static files. A private class that is meant to be used solely as a convenience by LiveServerThread. cCtjSrL)r STATIC_ROOTrvr>r>r?r z _StaticFilesHandler.get_base_dircCrrL)r STATIC_URLrvr>r>r?rrz _StaticFilesHandler.get_base_urlNrerfrgrr rr>r>r>r?r rc@r)_MediaFilesHandlerz Handler for serving the media files. A private class that is meant to be used solely as a convenience by LiveServerThread. cCrrL)r MEDIA_ROOTrvr>r>r?r rz_MediaFilesHandler.get_base_dircCrrL)r MEDIA_URLrvr>r>r?rrz_MediaFilesHandler.get_base_urlNrr>r>r>r?rrrcs:eZdZdZd fdd ZddZdd Zd d ZZS) LiveServerThreadzBThread for running a live http server while the tests are running.Nrcs6||_||_t|_d|_||_||_t dSrL) hostr threadingEventis_readyerrorstatic_handlerconnections_overriderOrP)rCrr"r#rrQr>r?rPs zLiveServerThread.__init__c Cs|jr|jD]\}}|t|<qzTz+|tt}||_|jdkr,|jj d|_|j ||j |j WntyW}z||_|j WYd}~n d}~wwWtdSWtdStw)zj Set up the live server and databases, and then loop over handling HTTP requests. rrYN)r#r/r"r"rr_create_serverhttpdrserver_addressset_appr rf serve_foreverrr! close_all)rCrrhandlerrHr>r>r?runs(      zLiveServerThread.runcCst|j|jftddS)NF)allow_reuse_address)rrrrrvr>r>r?r$szLiveServerThread._create_servercCs*t|dr|j|j|dS)Nr%)rr%shutdown server_closer^rvr>r>r? terminates    zLiveServerThread.terminate)Nr) rerfrgrrPr+r$r/rhr>r>rQr?rs  rcsteZdZdZdZdZeZeZ e ddZ e ddZ e fdd Ze d d Ze fd d Ze ddZZS)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. localhostrcCsd|j|jjfS)Nz http://%s:%s)r server_threadrrr>r>r?live_server_urlsz"LiveServerTestCase.live_server_urlcCs|jSrL)rrr>r>r? allowed_hostszLiveServerTestCase.allowed_hostcsti}tD]}|jdkr|r||||j<q td|j id|_ |j | ||_ d|j _|j |j j|j jrO||j jdS)Nsqlitern)rT)rOrr"rvendoris_in_memory_dbinc_thread_sharingrr1r4_live_server_modified_settingsr_create_server_threadr2daemonrZr waitr!_tearDownClassInternal)rr#rrQr>r?rs&       zLiveServerTestCase.setUpClasscCs|j|j|j||jdS)N)r#r)server_thread_classrr"r)rr#r>r>r?r:s z(LiveServerTestCase._create_server_threadcsJt|dr#|j|jjD]}|q|jt dSdS)Nr2) rr2r/r#rdec_thread_sharingr9rrOrrrQr>r?r=s    z)LiveServerTestCase._tearDownClassInternalcCs |dSrL)r=rr>r>r?r&s z LiveServerTestCase.tearDownClass)rerfrgrrrrr>rr"r4r3r4rgrr:r=rrhr>r>rQr?r0s$    r0cs8eZdZdZdZefddZefddZZS)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(). NcsD|jdur td|jt|j|_t|jtjt dS)NzB{}.lockfile isn't set. Set it to a unique value in the base class.) lockfilerformatreopen _lockfilerlockLOCK_EXrOrrrQr>r?r6s  zSerializeMixin.setUpClasscst|jdSrL)rOrrDrrrQr>r?r@s zSerializeMixin.tearDownClass) rerfrgrrArgrrrhr>r>rQr?r@+s r@rL)rrrErWrrrrr collectionsr contextlibrrrr functoolsrunittest.suiter unittest.utilr urllib.parser r r r rrrurllib.requestr asgiref.syncr django.appsr django.confr django.corerdjango.core.exceptionsrrdjango.core.filesrdjango.core.handlers.wsgirrdjango.core.managementrdjango.core.management.colorrdjango.core.management.sqlrdjango.core.servers.basehttprr django.dbr r!r"r#django.forms.fieldsr$rr%django.http.requestr&r'django.test.clientr(r)django.test.htmlr*r+django.test.signalsr,r-django.test.utilsr.r/r0r1r2django.utils.deprecationr3django.utils.functionalr4django.views.staticr5rr@rJrKrirrr6r8r7rrrrr9r:rrrrrThreadrr0r@r>r>r>r?s      $                ' h D 5.    0  1Q