o w[es@sdZddlZddlZddlZddlZddlZddlZddlZddlmZddl m Z m Z m Z ddl mZddlmZmZddlmZGdd d eZd d eeDZd ZeZd dZddZddZddZddZddZ dddZ!ddZ"ddZ#d d!Z$d"d#Z%dd$d%Z&d&d'Z'd(d)Z(d*d+Z)Gd,d-d-e*Z+Gd.d/d/e*Z,e,Z-e-j.Z.e-j/Z0e-j1Z2hd0Z3d1d2Z4Gd3d4d4e5Z6d5d6Z7Gd7d8d8e*Z8Gd9d:d:e*Z9Gd;d<dd>e5Z>d?d@Z?GdAdBdBe9Z@GdCdDdDe@e:ZAdEdFZBdGdHZCdIdJZDGdKdLdLe*ZEdMdNZFe.dddddfddOdPdQZG  ddRdSZHe.dddddfddOdTdUZIGdVdWdWe*ZJdXdYZKdZd[ZLeGeI_*eJeI_MeHeI_NeLeI_Od\eI_Pd]ZQd^ZRd_Sd`daeRTDZUd_SdbdaeRTDZVhdcZWdddeZXdfd d_SeQeReUeVgTDZYhdgZZdhhZ[eZe[BZ\eYeWBZ]e]e\BZ^hdiZ_djdkdldkdmdkdndkdoZ`eaeaeaeadpddddqdrd dpdds ZbdtduZcdvdwZddxdyZedzd{Zfecedeeefd|Zgd}d~ZhGddde9ZiGdddeie:ZjGdddeiZkGdddeieAZlGddde9ZmGddde9ZnGdddenekeAZoGddde*ZpepZqddZrGdddesZtetddZu  dddOddZvddZwGddde*ZxeyeveyeqjzfZ{da|ddZ}dddZ~GdddeAZddZGdddZdS))Mock MagicMockpatchsentinelDEFAULTANYcallcreate_autospec AsyncMock FILTER_DIRNonCallableMockNonCallableMagicMock mock_open PropertyMocksealN)iscoroutinefunction)CodeType ModuleType MethodType) safe_repr)wrapspartial)RLockc@eZdZdZdS)InvalidSpecErrorz8Indicates that an invalid value was used as a mock spec.N__name__ __module__ __qualname____doc__r r $/usr/lib/python3.10/unittest/mock.pyr(rcCsh|] }|ds|qS_ startswith).0namer r r! ,r)TcCs<t|r t|ts dSt|drt|d}t|pt|S)NF__func__)_is_instance_mock isinstancer hasattrgetattrrinspect isawaitableobjr r r! _is_async_obj4s   r4cCst|ddr t|SdS)N__code__F)r/rfuncr r r!_is_async_func<s r8cCstt|tSN) issubclasstyper r2r r r!r,Csr,cCst|tpt|tot|tSr9)r- BaseExceptionr;r:r2r r r! _is_exceptionIs r=cCst|tr t|dr |jS|SNmock)r- FunctionTypesr.r?r2r r r! _extract_mockPsrAcCs~t|tr |s |j}d}nt|ts"z|j}Wn ty!YdSw|r*t|d}n|}z|t|fWSt y>YdSw)z Given an arbitrary, possibly callable object, try to create a suitable signature object. Return a (reduced func, signature) tuple, or None. TN) r-r;__init__r@__call__AttributeErrorrr0 signature ValueError)r7 as_instanceeat_selfsig_funcr r r!_get_signature_objectYs"     rJFcsNt|||dur dS\}fdd}t|||t|_t|_dS)Ncsj|i|dSr9bindselfargskwargssigr r!checksig{z"_check_signature..checksig)rJ_copy_func_detailsr;_mock_check_sig __signature__)r7r? skipfirstinstancerSr rQr!_check_signaturevs    rZc Cs6dD]}z t||t||WqtyYqwdS)N)rr__text_signature__r __defaults____kwdefaults__)setattrr/rD)r7funcopy attributer r r!rUs rUcCs@t|trdSt|tttfrt|jSt|dddurdSdS)NTrCF)r-r; staticmethod classmethodr _callabler+r/r2r r r!rcs  rccCst|ttfvSr9)r;listtupler2r r r!_is_listsrfcCsFt|ts t|ddduS|f|jD] }|jddur dSqdS)ztGiven an object, return True if the object is callable. For classes, return True if instances would be callable.rCNTF)r-r;r/__mro____dict__get)r3baser r r!_instance_callables rkc st|t}t|||}|dur|S|\}fdd}t|||j}|s)d}||d}d|} t| |||} t| || S)Ncsj|i|dSr9rKrOrPrQr r!rSrTz _set_signature..checksigr_) _checksig_r?zYdef %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs))r-r;rJrUr isidentifierexec _setup_func) r?originalrYrXresultr7rSr(contextsrcr_r rQr!_set_signatures$       ruc s_fdd}fdd}fdd}fdd}fd d }fd d }fd d} fdd} d_d_d_t_t_t_j_j _ j _ |_ |_ |_ | _| _|_|_|_|__dS)Ncj|i|Sr9)assert_called_withrlr?r r!rwz'_setup_func..assert_called_withcrvr9) assert_calledrlrxr r!rzryz"_setup_func..assert_calledcrvr9)assert_not_calledrlrxr r!r{ryz&_setup_func..assert_not_calledcrvr9)assert_called_oncerlrxr r!r|ryz'_setup_func..assert_called_oncecrvr9)assert_called_once_withrlrxr r!r}ryz,_setup_func..assert_called_once_withcrvr9)assert_has_callsrlrxr r!r~ryz%_setup_func..assert_has_callscrvr9)assert_any_callrlrxr r!rryz$_setup_func..assert_any_callcsBt_t_j}t|r|ur|dSdSdSr9) _CallList method_calls mock_calls reset_mock return_valuer,)retr_r?r r!rs z_setup_func..reset_mockFr)r?called call_count call_argsrcall_args_listrrr side_effect_mock_childrenrwr}r~rrrzr{r|rW_mock_delegate) r_r?rRrwrzr{r|r}r~rrr rr!rps8        rpcsJtjj_d_d_t_fdd}dD] }t|t||qdS)Nrcstj||i|Sr9)r/r?)attrrOrPrxr r!wrapperz"_setup_async_mock..wrapper)assert_awaitedassert_awaited_onceassert_awaited_withassert_awaited_once_withassert_any_awaitassert_has_awaitsassert_not_awaited) asyncio coroutines _is_coroutine await_count await_argsrawait_args_listr^r)r?rr`r rxr!_setup_async_mocks   rcCsd|dd|kS)N__%s__r r(r r r! _is_magicrTrc@(eZdZdZddZddZddZdS) _SentinelObjectz!A unique, named, sentinel object.cCs ||_dSr9rrNr(r r r!rB z_SentinelObject.__init__cC d|jSNz sentinel.%srrNr r r!__repr__rz_SentinelObject.__repr__cCrrrrr r r! __reduce__!rz_SentinelObject.__reduce__N)rrrrrBrrr r r r!rs  rc@r) _SentinelzAAccess attributes to return a named object, usable as a sentinel.cCs i|_dSr9) _sentinelsrr r r!rB'rz_Sentinel.__init__cCs|dkrt|j|t|S)N __bases__)rDr setdefaultrrr r r! __getattr__*sz_Sentinel.__getattr__cCdS)Nrr rr r r!r0z_Sentinel.__reduce__N)rrrrrBrrr r r r!r%s  r> _mock_namer _mock_parentr_mock_new_name_mock_new_parent_mock_side_effect_mock_return_valuecCs8t|d|}||fdd}||fdd}t||S)N_mock_cSs"|j}|dur t||St||Sr9)rr/)rNr( _the_namerRr r r!_getEs  z"_delegating_property.._getcSs,|j}|dur||j|<dSt|||dSr9)rrhr^)rNvaluer(rrRr r r!_setJsz"_delegating_property.._set)_allowed_namesaddproperty)r(rrrr r r!_delegating_propertyBs  rc@eZdZddZddZdS)rcCslt|ts t||St|}t|}||krdStd||dD]}||||}||kr3dSq"dS)NFrT)r-rd __contains__lenrange)rNr len_valuelen_selfisub_listr r r!rWs  z_CallList.__contains__cCstt|Sr9)pprintpformatrdrr r r!rez_CallList.__repr__N)rrrrrr r r r!rUs rcCst|}t|s dS|js|js|jdus|jdurdS|}|dur/||ur(dS|j}|dus"|r7||_||_|r?||_||_dS)NFT)rAr,rrrr)parentrr(new_name_parentr r r!_check_and_set_parentis(   rc@r) _MockItercCst||_dSr9)iterr3)rNr3r r r!rBrz_MockIter.__init__cCs t|jSr9)nextr3rr r r!__next__rz_MockIter.__next__N)rrrrBrr r r r!rs rc@seZdZeZdZddZdS)BaseNcOdSr9r rMr r r!rBrz Base.__init__)rrrrrrrBr r r r!rs rc@steZdZdZeZddZ   dLddZd d ZdMd d Z  dNd dZ ddZ ddZ dZ ee e e ZeddZedZedZedZedZedZddZddZeeeZdOdddd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Z d.d/Z!d0d1Z"dPd3d4Z#d5d6Z$d7d8Z%d9d:Z&d;d<Z'd=d>Z(d?d@Z)dAdBZ*dMdCdDZ+dEdFZ,dGdHZ-dQdJdKZ.dS)Rr z A non-callable version of `Mock`cOs||f}t|ts*tj|g|Ri|j}|d|d}|dur*t|r*t|f}t|j|d|j i}t t | |}|S)Nspec_setspecr) r:AsyncMockMixin _MOCK_SIG bind_partial argumentsrir4r;rr _safe_superr __new__)clsrOkwbases bound_argsspec_argnewrYr r r!rs zNonCallableMock.__new__NFc Ks|dur|}|j} || d<|| d<|| d<|| d<d| d<|dur%|}d}| dur-|du} |||| | i| d<|| d <d| d <d| d <d| d <d | d<t| d<t| d<t| d<| | d<| rj|jdi| tt|||||||dS)NrrrrF _mock_sealedTr _mock_wrapsr _mock_called_mock_call_argsr_mock_call_count_mock_call_args_list_mock_mock_callsr _mock_unsafer )rh_mock_add_specrconfigure_mockrr rB)rNrrr(rr _spec_state _new_name _new_parent_spec_as_instance _eat_selfunsaferPrhr r r!rBs<     zNonCallableMock.__init__cCs0t|}d|_d|_d|_d|_t|||dS)z Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the `method_calls` and `mock_calls` attributes of this one.Nr)rArrrrr^)rNr?r` inner_mockr r r! attach_mocks zNonCallableMock.attach_mockcCs|||dSzAdd a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.N)rrNrrr r r! mock_add_specszNonCallableMock.mock_add_specc Csd}d}g}t|D]}tt||dr||q |dur>t|s>t|tr*|}nt|}t|||} | o9| d}t|}|j} || d<|| d<|| d<|| d<|| d<dS)Nr _spec_class _spec_set_spec_signature _mock_methods _spec_asyncs) dirrr/appendrfr-r;rJrh) rNrrrrrrrrresrhr r r!rs,     zNonCallableMock._mock_add_speccCs8|j}|jdur |jj}|tur|j|dd}||_|S)N()rr)rrrr_get_child_mock)rNrr r r!__get_return_values z"NonCallableMock.__get_return_valuecCs.|jdur ||j_dS||_t||dddS)Nr)rrrr)rNrr r r!__set_return_values  z"NonCallableMock.__set_return_valuez1The value to be returned when the mock is called.cCs|jdur t|S|jSr9)rr;rr r r! __class__'s zNonCallableMock.__class__rrrrrcCsN|j}|dur |jS|j}|dur%t|s%t|ts%t|s%t|}||_|Sr9)rrrcallabler-rr=)rN delegatedsfr r r!__get_side_effect4sz!NonCallableMock.__get_side_effectcCs*t|}|j}|dur||_dS||_dSr9) _try_iterrrr)rNrr r r r!__set_side_effect?s   z!NonCallableMock.__set_side_effectrrcCs|durg}t||vrdS|t|d|_d|_d|_t|_t|_t|_|r/t |_ |r4d|_ |j D]}t|tsD|turEq9|j|||dq9|j }t|r`||urb||dSdSdS)z-Restore the mock object to its initial state.NFrr)idrrrrrrrrrrrrvaluesr- _SpecState_deletedrr,)rNvisitedrrchildrr r r!rJs. zNonCallableMock.reset_mockcKsXt|dddD]\}}|d}|}|}|D]}t||}qt|||q dS)aZSet attributes on the mock through keyword arguments. Attributes plus return values and side effects can be set on child mocks using standard dot notation and unpacking a dictionary in the method call: >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} >>> mock.configure_mock(**attrs)cSs|ddS)Nr.)count)entryr r r!usz0NonCallableMock.configure_mock..)keyrN)sorteditemssplitpopr/r^)rNrPargvalrOfinalr3rr r r!rhs   zNonCallableMock.configure_mockcCs|dvrt||jdur||jvs|tvrtd|nt|r%t||js?|jr0||jvr?|dr?t|d|dtj|j |}|t urQt||durrd}|j durbt |j |}|j |||||d}||j|<nJt|trzt|j|j|j|j|j}Wn ty|jdp|}td|d |d |d |jd w||j|<Wd|SWd|SWd|S1swY|S) N>rrzMock object has no attribute %r)assertassretasertaseertassrtz6 is not a valid assertion. Use a spec for the mock if z is meant to be an attribute.)rr(rrrrCannot autospec attr from target , as it has already been mocked out. [target=, attr=])rDr _all_magicsrrr&r _lockrrirrr/rr-rrrrrYrr(rrh)rNr(rrr target_namer r r!r~sr              zNonCallableMock.__getattr__cCs|jg}|j}|}d}|dgkrd}|dur0|}||j|d}|jdkr)d}|j}|dustt|}|jp:d}t|dkrK|ddvrK|d7}||d<d|S)Nrrrr?r)rz().r)rrrrdreversedrrjoin)rN _name_listrlastdot_firstr r r!_extract_mock_names*      z"NonCallableMock._extract_mock_namecCs^|}d}|dvrd|}d}|jdur"d}|jrd}||jj}dt|j||t|fS)Nr)r?zmock.z name=%rz spec=%rz spec_set=%rz<%s%s%s id='%s'>)r7rrrr;r)rNr( name_string spec_stringr r r!rs   zNonCallableMock.__repr__cCsvtst|S|jp g}tt|}t|j}dd|j D}dd|D}dd|D}t t ||||S)z8Filter the output of `dir(mock)` to only useful members.cSsg|] \}}|tur|qSr )r)r'm_namem_valuer r r! s z+NonCallableMock.__dir__..cSsg|] }|ds|qSr#r%r'er r r!r<r*cSs"g|] }|dr t|r|qSr#)r&rr=r r r!r<s ) r object__dir__rrr;rdrhrrrset)rNextras from_type from_dictfrom_child_mocksr r r!r@s    zNonCallableMock.__dir__csJ|tvr t||Sjr#jdur#|jvr#|jvr#td||tvr/d|}t||tvrqjdurC|jvrCtd|t |s\t t |t |||fdd}n*t |d|t t |||j|<n|dkrz|_dSt |||r|j|<jrt|sd|}td|t||S)Nz!Mock object has no attribute '%s'z.Attempting to set unsupported magic method %r.csg|Ri|Sr9r rOrrqrNr r!rz-NonCallableMock.__setattr__..r rz Cannot set )rr? __setattr__rrrhrD_unsupported_magicsr.r,r^r; _get_methodrrrrr.r7)rNr(rmsg mock_namer rGr!rIs8      zNonCallableMock.__setattr__cCs|tvr|t|jvrtt||||jvrdS|j|t}||jvr.tt| |n|t ur6t ||tur>|j|=t |j|<dSr9) r.r;rhdelattrrri_missingrr __delattr__rrD)rNr(r3r r r!rPs  zNonCallableMock.__delattr__cCs|jpd}t|||Sr>)r_format_call_signaturerNrOrPr(r r r!_format_mock_call_signature)s  z+NonCallableMock._format_mock_call_signaturercCs.d}|||}|j}|j|}||||fS)Nz.expected %s not found. Expected: %s Actual: %s)rSr)rNrOrPactionmessageexpected_stringr actual_stringr r r!_format_mock_failure_message.s   z,NonCallableMock._format_mock_failure_messagecCsj|s|jSd}|ddd}|j}|D]}||}|dus%t|tr(|St|}|j}|j}q|S)aH * If call objects are asserted against a method/function like obj.meth1 then there could be no name for the call object to lookup. Hence just return the spec_signature of the method/function being asserted against. * If the name is not empty then remove () and split by '.' to get list of names to iterate through the children until a potential match is found. A child mock is created only during attribute access so if we get a _SpecState then no attributes of the spec were accessed and can be safely exited. Nrrr)rreplacerrrir-rrA)rNr(rRnameschildrenrr r r!_get_call_signature_from_name6s   z-NonCallableMock._get_call_signature_from_namec Cst|trt|dkr||d}n|j}|durUt|dkr'd}|\}}n|\}}}z|j|i|}t||j|jWSt yT}z | dWYd}~Sd}~ww|S)a Given a call (or simply an (args, kwargs) tuple), return a comparison key suitable for matching with other calls. This is a best effort method which relies on the spec's signature, if available, or falls back on the arguments themselves. rrNr) r-rerr\rrLrrOrP TypeErrorwith_traceback)rN_callrRr(rOrP bound_callr>r r r! _call_matcherWs    zNonCallableMock._call_matchercCs0|jdkrd|jp d|j|f}t|dS)z/assert that the mock was never called. rz9Expected '%s' to not have been called. Called %s times.%sr?Nrr _calls_reprAssertionErrorrNrLr r r!r{r z!NonCallableMock.assert_not_calledcCs$|jdkrd|jp d}t|dS)z6assert that the mock was called at least once rz"Expected '%s' to have been called.r?N)rrrdrer r r!rz|s zNonCallableMock.assert_calledcCs0|jdksd|jp d|j|f}t|dS)z3assert that the mock was called only once. rz:Expected '%s' to have been called once. Called %s times.%sr?Nrbrer r r!r|rfz"NonCallableMock.assert_called_oncecsjdur}d}d||f}t|fdd}tfdd}j}||krCt|tr;|nd}t||dS)zassert that the last call was made with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.Nz not called.z0expected call not found. Expected: %s Actual: %scs}|Sr9rXrLrOrPrNr r!_error_messages z:NonCallableMock.assert_called_with.._error_messageTtwo)rrSrdra_Callr- Exception)rNrOrPexpectedactual error_messagerjcauser rir!rws    z"NonCallableMock.assert_called_withcOs<|jdksd|jp d|j|f}t||j|i|S)ziassert that the mock was called exactly once and that that call was with the specified arguments.rz3Expected '%s' to be called once. Called %s times.%sr?)rrrcrdrwrNrOrPrLr r r!r}s z'NonCallableMock.assert_called_once_withc sfdd|D}tdd|Dd}tfddjD}|sM||vrK|dur,d}n dd d|D}t|d t|jd d d |dSt|}g}|D]}z||WqUt yl| |YqUw|r~tdj pudt ||f|dS)aassert the mock has been called with the specified calls. The `mock_calls` list is checked for the calls. If `any_order` is False (the default) then the calls must be sequential. There can be extra calls before or after the specified calls. If `any_order` is True then the calls can be in any order, but they must all appear in `mock_calls`.cg|]}|qSr rar'crr r!r<rHz4NonCallableMock.assert_has_calls..cs|] }t|tr|VqdSr9r-rnr=r r r! z3NonCallableMock.assert_has_calls..Nc3|]}|VqdSr9rurvrr r!rzzCalls not found.z+Error processing expected calls. Errors: {}cSg|] }t|tr |ndqSr9ryr=r r r!r< Expected: Actual)prefixrz@%r does not contain all of %r in its call list, found %r insteadr?) rrrformatrdrcrstriprdremoverFrrre) rNcalls any_orderrorr all_callsproblem not_foundkallr rr!r~sV  z NonCallableMock.assert_has_callscjt||fdd}t|tr|nd}fddjD}|s&|t|vr3||}td||dS)zassert the mock has been called with the specified arguments. The assert passes if the mock has *ever* been called, unlike `assert_called_with` and `assert_called_once_with` that only pass if the call is the most recent one.TrkNcrtr rurvrr r!r<rHz3NonCallableMock.assert_any_call..z%s call not found)rarmr-rnr _AnyComparerrSrdrNrOrProrrrprVr rr!rs zNonCallableMock.assert_any_callcKs|jrd|vrd|dnd}||}t||d}||jdvr-tdi|St|}t|tr=|t vr=t}n1t|t rT|t vsN|j rQ||j vrQt}nt}nt|t sit|trat}n t|trht}n|jd}|di|S) aPCreate the child mocks for attributes and return value. By default child mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made. For non-callable mocks the callable variant will be used (rather than any custom subclass).r(rrrrrNr )rr7rDrirhr r;r:r_async_method_magicsr_all_sync_magicsr CallableMixinr r rrg)rNrr`rMr_typeklassr r r!rs2        zNonCallableMock._get_child_mockCallscCs"|jsdSd|dt|jdS)zRenders self.mock_calls as a string. Example: " Calls: [call(1), call(2)]." If self.mock_calls is empty, an empty string is returned. The output will be truncated if very long. r z: r)rr)rNrr r r!rcszNonCallableMock._calls_repr) NNNNNNrNFNFF)FFr9)r)r)/rrrrrr/rrBrrr"_NonCallableMock__get_return_value"_NonCallableMock__set_return_value"_NonCallableMock__return_value_docrrr rrrrrr!_NonCallableMock__get_side_effect!_NonCallableMock__set_side_effectrrrrr7rr@rIrPrSrXr\rar{rzr|rwr}r~rrrcr r r r!r sd -      0' !   -&r c@seZdZdZddZdS)rzA list which checks if it contains a call which may have an argument of ANY, flipping the components of item and self from their traditional locations so that ANY is guaranteed to be on the left.cCs@|D]}t|t|ksJtddt||DrdSqdS)NcSsg|]\}}||kqSr r )r'rorpr r r!r<+sz-_AnyComparer.__contains__..TF)rallzip)rNitemr_r r r!r(sz_AnyComparer.__contains__N)rrrrrr r r r!r#s rcCsF|dur|St|r |St|r|Szt|WSty"|YSwr9)r=rcrr]r2r r r!r3s  rc @sReZdZddedddddddf ddZddZddZd d Zd d Zd dZ dS)rNrc Ks:||jd<tt|j||||||| | fi| ||_dS)Nr)rhrrrBr) rNrrrrr(rrrrrrPr r r!rBDs    zCallableMixin.__init__cOrr9r rMr r r!rVPszCallableMixin._mock_check_sigcOs0|j|i||j|i||j|i|Sr9)rV_increment_mock_call _mock_callrMr r r!rCUszCallableMixin.__call__cOs|j|i|Sr9)_execute_mock_callrMr r r!r]ryzCallableMixin._mock_callc Os d|_|jd7_t||fdd}||_|j||jdu}|j}|j}|dk}|j td||f|j }|dur|rW|j t|||f|jdu}|rW|jd|}t|||f} |j | |jrz|rld} nd} |jdk}|j| |}|j }|dus|j|i|S|jSr9)rr=rcrrrrr)rNrOrPeffectrrr r r!rs"  z CallableMixin._execute_mock_call) rrrrrBrVrCrrrr r r r!rBs   .rc@r)ra Create a new `Mock` object. `Mock` takes several optional arguments that specify the behaviour of the Mock object: * `spec`: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). Accessing any attribute not in this list will raise an `AttributeError`. If `spec` is an object (rather than a list of strings) then `mock.__class__` returns the class of the spec object. This allows mocks to pass `isinstance` tests. * `spec_set`: A stricter variant of `spec`. If used, attempting to *set* or get an attribute on the mock that isn't on the object passed as `spec_set` will raise an `AttributeError`. * `side_effect`: A function to be called whenever the Mock is called. See the `side_effect` attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns `DEFAULT`, the return value of this function is used as the return value. If `side_effect` is an iterable then each call to the mock will return the next value from the iterable. If any of the members of the iterable are exceptions they will be raised instead of returned. * `return_value`: The value returned when the mock is called. By default this is a new Mock (created on first access). See the `return_value` attribute. * `wraps`: Item for the mock object to wrap. If `wraps` is not None then calling the Mock will pass the call through to the wrapped object (returning the real result). Attribute access on the mock will return a Mock object that wraps the corresponding attribute of the wrapped object (so attempting to access an attribute that doesn't exist will raise an `AttributeError`). If the mock has an explicit `return_value` set then calls are not passed to the wrapped object and the `return_value` is returned instead. * `name`: If the mock has a name then it will be used in the repr of the mock. This can be useful for debugging. The name is propagated to child mocks. Mocks can also be called with arbitrary keyword arguments. These will be used to set attributes on the mock after it is created. Nrr r r r!rr"rcCs2zt||WStyt|t||YSwr9)r/rD __import__)thingcomp import_pathr r r! _dot_lookups   rcCsB|d}|d}t|}|D]}|d|7}t|||}q|S)Nrrz.%s)rr rr)target componentsrrrr r r! _importers   rcCs(d}|D] }||vrt|dqdS)N) autospect auto_specset_specz5 might be a typo; use unsafe=True if this is intended) RuntimeError)kwargs_to_checktypostypor r r!_check_spec_arg_typossrc@seZdZdZgZddddZddZdd Zd d Ze j d d Z ddZ ddZ ddZddZddZddZddZdS)_patchNFrc  Cs|dur|tur td|durtd| st| t|r)td|d|dt|r8td|d|d||_||_||_||_||_ ||_ d|_ ||_ ||_ | |_g|_dS)Nz,Cannot use 'new' and 'new_callable' togetherz1Cannot use 'autospec' and 'new_callable' togetherzCannot spec attr z0 as the spec has already been mocked out. [spec=r-z? as the spec_set target has already been mocked out. [spec_set=F)rrFrr,rgetterr`r new_callablercreate has_localrautospecrPadditional_patchers) rNrr`rrrrrrrPrr r r!rBsD z_patch.__init__c CsHt|j|j|j|j|j|j|j|j|j }|j |_ dd|j D|_ |S)NcSsg|]}|qSr )copy)r'pr r r!r<-z_patch.copy..) rrr`rrrrrrrPattribute_namer)rNpatcherr r r!r&s z _patch.copycC2t|tr ||St|r||S||Sr9r-r;decorate_classr0rdecorate_async_callabledecorate_callablerNr7r r r!rC3     z_patch.__call__cCsNt|D] }|tjs qt||}t|dsq|}t||||q|SNrC)rr&r TEST_PREFIXr/r.rr^)rNrr attr_valuerr r r!r;s    z_patch.decorate_classccsg}t4}|jD]}||}|jdur||q |jtur'||q |t |7}||fVWddS1s>wYdSr9) contextlib ExitStack patchings enter_contextrupdaterrrre)rNpatchedrOkeywargs extra_args exit_stackpatchingr!r r r!decoration_helperIs         "z_patch.decoration_helperc>tdr jStfddg_S)NrcsD||\}}|i|WdS1swYdSr9rrOrnewargs newkeywargsr7rrNr r!r^s $z)_patch.decorate_callable..patchedr.rrrrr rr!rX  z_patch.decorate_callablecr)NrcsL||\}}|i|IdHWdS1swYdSr9rrrr r!ros$z/_patch.decorate_async_callable..patchedrrr rr!rirz_patch.decorate_async_callablec Cs|}|j}t}d}z|j|}Wnttfy#t||t}Ynwd}|tvr2t|t r2d|_ |j sA|turAtd||f||fS)NFTz!%s does not have the attribute %r) rr`rrhrDKeyErrorr/ _builtinsr-rr)rNrr(rqlocalr r r! get_originalzs" z_patch.get_originalc Cs|j|j|j}}}|j|j}}|j}||_|dur d}|dur&d}|dur,d}|dur8|dur8td|dus@|durH|dvrHtd| \}}|t ur.|dur.d} |duri|}|durh|}d}n|durv|duru|}d}n|dur||}|dus|dur|t urtdt |t rd} |durt |rt} nt} i} |dur|} n)|dus|dur|} |dur|} t| rd| v} nt|  } t | rt} n| rt} |dur|| d <|dur|| d <t | t rt| tr|jr|j| d <| || di| }| r-t|r-|} |dur|} t| st| st} | d | d|d d | |_nl|dur|t ur.)rsplitr]rFrD)rr`rr rr! _get_targetLs rrc sBttur tdfdd} t| |||||||| |d S)a patch the named member (`attribute`) on an object (`target`) with a mock object. `patch.object` can be used as a decorator, class decorator or a context manager. Arguments `new`, `spec`, `create`, `spec_set`, `autospec` and `new_callable` have the same meaning as for `patch`. Like `patch`, `patch.object` takes arbitrary keyword arguments for configuring the mock object it creates. When used as a class decorator `patch.object` honours `patch.TEST_PREFIX` for choosing which methods to wrap. z3 must be the actual object to be patched, not a strcSr9r r rr r!rlz_patch_object..r)r;strr]r) rr`rrrrrrrrPrr rr! _patch_objectVs    rc sttur fdd}nfdd}|stdt|}|d\} } t|| | |||||i } | | _|ddD]\} } t|| | |||||i } | | _| j| q:| S)aPerform multiple patches in a single call. It takes the object to be patched (either as an object or a string to fetch the object by importing) and keyword arguments for the patches:: with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'): ... Use `DEFAULT` as the value if you want `patch.multiple` to create mocks for you. In this case the created mocks are passed into a decorated function by keyword, and a dictionary is returned when `patch.multiple` is used as a context manager. `patch.multiple` can be used as a decorator, class decorator or a context manager. The arguments `spec`, `spec_set`, `create`, `autospec` and `new_callable` have the same meaning as for `patch`. These arguments will be applied to *all* patches done by `patch.multiple`. When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX` for choosing which methods to wrap. crr9rr rr r!rrz!_patch_multiple..crr9r r rr r!rrz=Must supply at least one keyword argument with patch.multiplerrN) r;rrFrdrrrrr) rrrrrrrPrrr`rr this_patcherr rr!_patch_multipless,      r c Ks(t|\} } t| | ||||||||d S)a: `patch` acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the `target` is patched with a `new` object. When the function/with statement exits the patch is undone. If `new` is omitted, then the target is replaced with an `AsyncMock if the patched object is an async function or a `MagicMock` otherwise. If `patch` is used as a decorator and `new` is omitted, the created mock is passed in as an extra argument to the decorated function. If `patch` is used as a context manager the created mock is returned by the context manager. `target` should be a string in the form `'package.module.ClassName'`. The `target` is imported and the specified object replaced with the `new` object, so the `target` must be importable from the environment you are calling `patch` from. The target is imported when the decorated function is executed, not at decoration time. The `spec` and `spec_set` keyword arguments are passed to the `MagicMock` if patch is creating one for you. In addition you can pass `spec=True` or `spec_set=True`, which causes patch to pass in the object being mocked as the spec/spec_set object. `new_callable` allows you to specify a different class, or callable object, that will be called to create the `new` object. By default `AsyncMock` is used for async functions and `MagicMock` for the rest. A more powerful form of `spec` is `autospec`. If you set `autospec=True` then the mock will be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a `TypeError` if they are called with the wrong signature. For mocks replacing a class, their return value (the 'instance') will have the same spec as the class. Instead of `autospec=True` you can pass `autospec=some_object` to use an arbitrary object as the spec instead of the one being replaced. By default `patch` will fail to replace attributes that don't exist. If you pass in `create=True`, and the attribute doesn't exist, patch will create the attribute for you when the patched function is called, and delete it again afterwards. This is useful for writing tests against attributes that your production code creates at runtime. It is off by default because it can be dangerous. With it switched on you can write passing tests against APIs that don't actually exist! Patch can be used as a `TestCase` class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set. `patch` finds tests by looking for method names that start with `patch.TEST_PREFIX`. By default this is `test`, which matches the way `unittest` finds tests. You can specify an alternative prefix by setting `patch.TEST_PREFIX`. Patch can be used as a context manager, with the with statement. Here the patching applies to the indented block after the with statement. If you use "as" then the patched object will be bound to the name after the "as"; very useful if `patch` is creating a mock object for you. Patch will raise a `RuntimeError` if passed some common misspellings of the arguments autospec and spec_set. Pass the argument `unsafe` with the value True to disable that check. `patch` takes arbitrary keyword arguments. These will be passed to `AsyncMock` if the patched object is asynchronous, to `MagicMock` otherwise or to `new_callable` if specified. `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are available for alternate use-cases. r)rr) rrrrrrrrrPrr`r r r!rs K  rc@sjeZdZdZdddZddZdd Zd d Zd d ZddZ ddZ ddZ ddZ ddZ ddZdS) _patch_dicta# Patch a dictionary, or dictionary like object, and restore the dictionary to its original state after the test. `in_dict` can be a dictionary or a mapping like container. If it is a mapping then it must at least support getting, setting and deleting items plus iterating over keys. `in_dict` can also be a string specifying the name of the dictionary, which will then be fetched by importing it. `values` can be a dictionary of values to set in the dictionary. `values` can also be an iterable of `(key, value)` pairs. If `clear` is True then the dictionary will be cleared before the new values are set. `patch.dict` can also be called with arbitrary keyword arguments to set values in the dictionary:: with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()): ... `patch.dict` can be used as a context manager, decorator or class decorator. When used as a class decorator `patch.dict` honours `patch.TEST_PREFIX` for choosing which methods to wrap. r FcKs,||_t||_|j|||_d|_dSr9)in_dictdictrrclear _original)rNr rrrPr r r!rBs    z_patch_dict.__init__cCrr9r)rNfr r r!rCrz_patch_dict.__call__ctfdd}|S)Ncs,z |i|WSwr9r  _unpatch_dictrFrrNr r!_inner%sz-_patch_dict.decorate_callable.._innerrrNrrr rr!r$z_patch_dict.decorate_callablecr)Ncs4z|i|IdHWSwr9rrFrr r!r1s z3_patch_dict.decorate_async_callable.._innerrrr rr!r0rz#_patch_dict.decorate_async_callablecCsXt|D]%}t||}|tjr)t|dr)t|j|j|j }||}t |||q|Sr) rr/r&rrr.r r rrr^)rNrrr decorator decoratedr r r!r<s    z_patch_dict.decorate_classcCs||jS)zPatch the dict.)r r rr r r!rGsz_patch_dict.__enter__cCs|j}t|jtrt|j|_|j}|j}z|}Wnty1i}|D]}||||<q&Ynw||_|r;t |z| |WdStyX|D]}||||<qLYdSwr9) rr-r rrrrrDr _clear_dictr)rNrr rrqrr r r!r Ms.     z_patch_dict._patch_dictcCsP|j}|j}t|z||WdSty'|D]}||||<qYdSwr9)r rrrrD)rNr rqrr r r!ris z_patch_dict._unpatch_dictcGs|jdur |dS)zUnpatch the dict.NF)rr)rNrOr r r!rvs z_patch_dict.__exit__cCs|}tj||Sr)rrrrrr r r!r}rz_patch_dict.startcCs4ztj|Wn tyYdSw|dddSr)rrrrFrrr r r!rrz_patch_dict.stopN)r F)rrrrrBrCrrrrr rrrrr r r r!r s       r cCs<z|WdStyt|}|D]}||=qYdSwr9)rrDrd)r keysrr r r!rs rcCsttjD]}|qdS)z7Stop all active patches. LIFO to unroll nested patches.N)r1rrr)rr r r!_patch_stopalls rtestzlt le gt ge eq ne getitem setitem delitem len contains iter hash str sizeof enter exit divmod rdivmod neg pos abs invert complex int float index round trunc floor ceil bool next fspath aiter zHadd sub mul matmul div floordiv mod lshift rshift and xor or pow truediv cc|]}d|VqdS)zi%sNr r'nr r r!rzrzccr )zr%sNr r!r r r!rzr#>r@__get____set__r __delete__ __format__r __missing__ __getstate__ __reversed__ __setstate__ __getformat__ __reduce_ex__ __setformat____getnewargs____subclasses____getinitargs____getnewargs_ex__csfdd}||_|S)z:Turns a callable object (like a mock) into a real functioncs|g|Ri|Sr9r rNrOrr6r r!methodrz_get_method..method)r)r(r7r4r r6r!rKs rKcCsh|]}d|qS)rr )r'r4r r r!r)r> __aexit__ __anext__ __aenter__ __aiter__>__del__rrBr __prepare__rI__instancecheck____subclasscheck__cC t|Sr9)r?__hash__rr r r!r rcCr=r9)r?__str__rr r r!rr?cCr=r9)r? __sizeof__rr r r!rr?cCs"t|jd|dt|S)N/)r;rr7rrr r r!rs")r>r@rA __fspath__ry?g?) __lt____gt____le____ge____int__r__len__r __complex__ __float____bool__ __index__r5cfdd}|S)Ncs$jj}|tur |S|urdStSNT)__eq__rrNotImplemented)otherret_valrr r!rPs z_get_eq..__eq__r )rNrPr rr!_get_eq rTcrN)Ncs jjturtS|urdStSNF)__ne__rrrQ)rRrr r!rWs z_get_ne..__ne__r )rNrWr rr!_get_nes rXcrN)Ncs jj}|tur tgSt|Sr9)__iter__rrrrSrr r!rYsz_get_iter..__iter__r )rNrYr rr! _get_iterrUr[crN)Ncs(jj}|turttgStt|Sr9)r8rr_AsyncIteratorrrZrr r!r8s  z"_get_async_iter..__aiter__r )rNr8r rr!_get_async_iters r])rPrWrYr8cCsft|t}|tur||_dSt|}|dur!||}||_dSt|}|dur1|||_dSdSr9)_return_valuesrirr_calculate_return_value_side_effect_methodsr)r?r4r(fixedreturn_calculatorr side_effectorr r r!_set_return_value*s   rdc@r) MagicMixincO*|tt|j|i||dSr9)_mock_set_magicsrrerBr3r r r!rB= zMagicMixin.__init__cCsttB}|}t|dddur,||j}t}||}|D]}|t|jvr+t||q|tt|j}t|}|D] }t ||t ||q;dS)Nr) _magicsrr/ intersectionrrAr;rhrNr^ MagicProxy)rN orig_magics these_magics remove_magicsrrr r r!rgCs  zMagicMixin._mock_set_magicsN)rrrrBrgr r r r!re<s rec@eZdZdZdddZdS)r z-A version of `MagicMock` that isn't callable.FcC||||dSrrrgrr r r!r]  z"NonCallableMagicMock.mock_add_specNrrrrrrr r r r!r [sr c@seZdZddZdS)AsyncMagicMixincOrfr9)rgrrtrBr3r r r!rBhrhzAsyncMagicMixin.__init__NrrrrBr r r r!rtgs rtc@ro)ra MagicMock is a subclass of Mock with default implementations of most of the magic methods. You can use MagicMock without having to configure the magic methods yourself. If you use the `spec` or `spec_set` arguments then *only* magic methods that exist in the spec will be created. Attributes and the return value of a `MagicMock` will also be `MagicMocks`. FcCrprrqrr r r!rxrrzMagicMock.mock_add_specNrrsr r r r!rms rc@s&eZdZddZddZdddZdS) rkcCs||_||_dSr9r(r)rNr(rr r r!rBs zMagicProxy.__init__cCs8|j}|j}|j|||d}t|||t||||S)N)r(rr)r(rrr^rd)rNrrmr r r! create_mocks  zMagicProxy.create_mockNcCs|Sr9)rx)rNr3rr r r!r$szMagicProxy.__get__r9)rrrrBrxr$r r r r!rks rkcseZdZedZedZedZfddZddZdd Z d d Z d d Z ddZ ddZ dddZddZfddZZS)rrrrcstj|i|tjj|jd<d|jd<d|jd<t|jd<ttd}t j |_ ||jd<d|jd <t |jd <i|jd <d|jd <dS) Nrr_mock_await_count_mock_await_args_mock_await_args_listrr5r rr\r]r) superrBrrrrhrr rr0 CO_COROUTINEco_flagsre)rNrOrP code_mockr r r!rBs        zAsyncMockMixin.__init__cs t||fdd}|jd7_||_|j||j}|dur]t|r&|t|sAzt|}Wn t y9t wt|r@|nt |rP||i|IdH}n||i|}|t ur]|S|j t ure|jS|jdurt |jrz|j|i|IdHS|j|i|S|jS)NTrkr)rmrrrrrr=rcr StopIterationStopAsyncIterationrrrrr)rNrOrPr_rrrr r r!rs<      z!AsyncMockMixin._execute_mock_callcCs(|jdkrd|jp dd}t|dS)zA Assert that the mock was awaited at least once. r Expected r?z to have been awaited.Nrrrdrer r r!rs zAsyncMockMixin.assert_awaitedcCs0|jdksd|jp dd|jd}t|dS)z@ Assert that the mock was awaited exactly once. rrr?$ to have been awaited once. Awaited  times.Nrrer r r!r z"AsyncMockMixin.assert_awaited_oncecsjdur}td|dfdd}tfdd}j}||kr?t|tr7|nd}t||dS)zN Assert that the last await was with the specified arguments. NzExpected await: z Not awaitedcsjdd}|S)Nawait)rTrgrhrir r!rjsz:AsyncMockMixin.assert_awaited_with.._error_messageTrk)rrSrdrarmr-rn)rNrOrProrjrprrr rir!rs    z"AsyncMockMixin.assert_awaited_withcOs<|jdksd|jp dd|jd}t||j|i|S)zi Assert that the mock was awaited exactly once and with the specified arguments. rrr?rr)rrrdrrsr r r!rs z'AsyncMockMixin.assert_awaited_once_withcr)zU Assert the mock has ever been awaited with the specified arguments. TrkNcrtr rurvrr r!r< rHz3AsyncMockMixin.assert_any_await..z%s await not found)rarmr-rnrrrSrdrr rr!r s zAsyncMockMixin.assert_any_awaitFc sfdd|D}tdd|Dd}tfddjD}|sH||vrF|dur,d}n dd d|D}t|d t|d j|dSt|}g}|D]}z||WqPtyg||YqPw|rttd t |f|dS) a Assert the mock has been awaited with the specified calls. The :attr:`await_args_list` list is checked for the awaits. If `any_order` is False (the default) then the awaits must be sequential. There can be extra calls before or after the specified awaits. If `any_order` is True then the awaits can be in any order, but they must all appear in :attr:`await_args_list`. crtr rurvrr r!r< rHz4AsyncMockMixin.assert_has_awaits..csrxr9ryr=r r r!rz r{z3AsyncMockMixin.assert_has_awaits..Nc3r|r9rurvrr r!rz r}zAwaits not found.z,Error processing expected awaits. Errors: {}cSr~r9ryr=r r r!r<' rrz Actual: z%r not all found in await list) rrrrrdrdrrFrre) rNrrrorr all_awaitsrrrr rr!r sN   z AsyncMockMixin.assert_has_awaitscCs0|jdkrd|jp dd|jd}t|dS)z9 Assert that the mock was never awaited. rrr?z# to not have been awaited. Awaited rNrrer r r!r= rz!AsyncMockMixin.assert_not_awaitedcs*tj|i|d|_d|_t|_dS)z0 See :func:`.Mock.reset_mock()` rN)r}rrrrrrMrr r!rF s zAsyncMockMixin.reset_mockr)rrrrrrrrBrrrrrrrrr __classcell__r r rr!rs (  , rc@r)r aY Enhance :class:`Mock` with features allowing to mock an async function. The :class:`AsyncMock` object will behave so the object is recognized as an async function, and the result of a call is an awaitable: >>> mock = AsyncMock() >>> iscoroutinefunction(mock) True >>> inspect.isawaitable(mock()) True The result of ``mock()`` is an async function which will have the outcome of ``side_effect`` or ``return_value``: - if ``side_effect`` is a function, the async function will return the result of that function, - if ``side_effect`` is an exception, the async function will raise the exception, - if ``side_effect`` is an iterable, the async function will return the next value of the iterable, however, if the sequence of result is exhausted, ``StopIteration`` is raised immediately, - if ``side_effect`` is not defined, the async function will return the value defined by ``return_value``, hence, by default, the async function returns a new :class:`AsyncMock` object. If the outcome of ``side_effect`` or ``return_value`` is an async function, the mock async function obtained when the mock object is called will be this async function itself (and not an async function returning an async function). The test author can also specify a wrapped object with ``wraps``. In this case, the :class:`Mock` object behavior is the same as with an :class:`.Mock` object: the wrapped object may have methods defined as async function functions. Based on Martin Richard's asynctest project. Nrr r r r!r P r"r c@r) _ANYz2A helper object that compares equal to everything.cCrrOr rNrRr r r!rP~ rz _ANY.__eq__cCrrVr rr r r!rW rz _ANY.__ne__cCr)Nzr rr r r!r rz _ANY.__repr__N)rrrrrPrWrr r r r!r{ s  rcCs`d|}d}ddd|D}ddd|D}|r |}|r,|r(|d7}||7}||S)Nz%s(%%s)rz, cSsg|]}t|qSr )repr)r'r!r r r!r< sz*_format_call_signature..cSsg|] \}}d||fqS)z%s=%rr )r'rrr r r!r< s)r2r)r(rOrPrUformatted_args args_string kwargs_stringr r r!rQ s rQc@seZdZdZ  dddZ  dd d Zd d ZejZd dZ ddZ ddZ ddZ e ddZe ddZddZddZdS)rma A tuple for holding the results of a call to a mock, either in the form `(args, kwargs)` or `(name, args, kwargs)`. If args or kwargs are empty then a call tuple will compare equal to a tuple without those values. This makes comparisons less verbose:: _Call(('name', (), {})) == ('name',) _Call(('name', (1,), {})) == ('name', (1,)) _Call(((), {'a': 'b'})) == ({'a': 'b'},) The `_Call` object provides a useful shortcut for comparing with call:: _Call(((1, 2), {'a': 3})) == call(1, 2, a=3) _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3) If the _Call has no name then it will match any name. r rNFTc Csd}i}t|}|dkr|\}}}n9|dkr2|\} } t| tr,| }t| tr)| }n"| }n| | }}n|dkrK|\}t|trA|}n t|trI|}n|}|rUt|||fSt||||fS)Nr rr)rr-rrer) rrr(rrl from_kallrOrP_lenfirstsecondr r r!r s.      z _Call.__new__cCs||_||_||_dSr9)rr_mock_from_kall)rNrr(rrlrr r r!rB s z_Call.__init__c CsRzt|}Wn tytYSwd}t|dkr|\}}n|\}}}t|ddr8t|ddr8|j|jkr8dSd}|dkrDdi}}nU|dkrN|\}}}nK|dkrq|\} t| tr_| }i}n:t| trl| }di}}n-d}| }n(|dkr|\} } t| tr| }t| tr| i}}nd| }}n| | }}ndS|r||krdS||f||fkS) NrrrFrr rr)rr]rQr/rr-rer) rNrR len_other self_name self_args self_kwargs other_name other_args other_kwargsrrrr r r!rP sN                 z _Call.__eq__cOs<|jdurtd||fddS|jd}t|j||f||dS)NrrrrvrrmrRr r r!rC s  z_Call.__call__cCs2|jdur t|ddSd|j|f}t||ddS)NF)r(rz%s.%s)r(rrr)rNrr(r r r!r s  z_Call.__getattr__cCs|tjvrtt||Sr9)rerhrD__getattribute__)rNrr r r!r s  z_Call.__getattribute__cCs.t|dkr|\}}||fS|\}}}||fS)Nr)rrRr r r!_get_call_arguments$ s  z_Call._get_call_argumentscC |dSNrrrr r r!rO,  z _Call.argscCr)Nrrrr r r!rP0 rz _Call.kwargscCs||js|jpd}|drd|}|St|dkr d}|\}}n|\}}}|s*d}n|ds4d|}nd|}t|||S)Nrrzcall%srzcall.%s)rrr&rrQ)rNr(rOrPr r r!r4 s        z_Call.__repr__cCs:g}|}|dur|jr|||j}|dustt|S)zFor a call object that represents multiple calls, `call_list` returns a list of all the intermediate calls as well as the final call.N)rrrrr1)rNvalsrr r r! call_listI s  z_Call.call_list)r rNFT)r NNFT)rrrrrrBrPr?rWrCrrrrrOrPrrr r r r!rm s(   5   rm)rc Ksht|rt|}t|t}t|rtd|dt|}d|i} |r(d|i} n|dur.i} | r6|r6d| d<|s._readlines_side_effectcrr)readrrlrr r!_read_side_effect3 rz$mock_open.._read_side_effectc?s(EdH dj|i|VqNTr)readlinerl)_iter_side_effectrr r!_readline_side_effect8 s  z(mock_open.._readline_side_effectc3s4jjdur jjVqdD]}|VqdSr)rr)linerr r!r= s   z$mock_open.._iter_side_effectcs jjdur jjStdSr)rrrr rr r!_next_side_effectD s  z$mock_open.._next_side_effectropen)r(r)rrcs6td<jjdkrd<dj_tS)Nrr)rrrrrl)rrrrr r! reset_data` s   zmock_open..reset_data)r file_spec_iordrAr TextIOWrapperunionrrrrrwriterrrrrYr)r?r _read_datarrrrrr )rrrrrr!r  s8 "    r c@s*eZdZdZddZd ddZddZdS) raW A mock intended to be used as a property, or other descriptor, on a class. `PropertyMock` provides `__get__` and `__set__` methods so you can specify a return value when it is fetched. Fetching a `PropertyMock` instance from an object calls the mock, with no args. Setting it calls the mock with the value being set. cKstdi|S)Nr )r)rNrPr r r!rv rzPropertyMock._get_child_mockNcCs|Sr9r )rNr3obj_typer r r!r$y szPropertyMock.__get__cCs ||dSr9r )rNr3r"r r r!r%{ s zPropertyMock.__set__r9)rrrrrr$r%r r r r!rm s   rc Csld|_t|D],}zt||}Wn tyYqwt|ts qt|j|tr*q|j |ur3t |qdS)aDisable the automatic generation of child mocks. Given an input Mock, seals it to ensure no further mocks will be generated when accessing an attribute that was not already defined. The operation recursively seals the mock passed in, meaning that the mock itself, any mocks generated by accessing one of its attributes, and all assigned mocks without a name or spec will be sealed. TN) rrr/rDr-r rrirrr)r?rrwr r r!r s    rc@s eZdZdZddZddZdS)r\z8 Wraps an iterator in an asynchronous iterator. cCs&||_ttd}tj|_||jd<dS)Nr|r5)iteratorr rr0CO_ITERABLE_COROUTINErrh)rNrrr r r!rB s z_AsyncIterator.__init__cs$zt|jWStyYtwr9)rrrrrr r r!r6 s  z_AsyncIterator.__anext__N)rrrrrBr6r r r r!r\ s r\r)NFNNN)FFNN)Nr)__all__rrrr0rrbuiltinsrtypesrrr unittest.utilr functoolsrr threadingrrnrrrr r}rr4r8r,r=rArJrZrUrcrfrkrurprrr?rrrrMISSINGrODELETEDrrrrdrrrrr rErBrrrrrrrrrrrr rr rrr multiplestopallr magic_methodsnumericsr2rinplaceright _non_defaultsrKrir_sync_async_magics _async_magicsrr.rJr_rQr^rTrXr[r]r`rdrer rtrrkrr rrrQrermrrrrr;rPr@rrr rrr\r r r r!sD        1  h4  R   2 R        <+  :   N