o ?Ogs@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 4/opt/alt/python310/lib64/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 hasattrgetattrrinspectZ isawaitableobjr r r! _is_async_obj4s   r3cCst|ddr t|SdS)N__code__F)r/rfuncr r r!_is_async_func<s r7cCstt|tSN) issubclasstyper r1r r r!r,Csr,cCst|tpt|tot|tSr8)r- BaseExceptionr:r9r1r r r! _is_exceptionIs r<cCst|tr t|dr |jS|SNmock)r- FunctionTypesr.r>r1r r r! _extract_mockPsr@cCs~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)r6Z as_instanceZeat_selfZsig_funcr r r!_get_signature_objectYs"     rFFcsNt|||dur dS\}fdd}t|||t|_t|_dS)Ncsj|i|dSr8bindselfargskwargssigr r!checksig{z"_check_signature..checksig)rF_copy_func_detailsr:_mock_check_sig __signature__)r6r> skipfirstinstancerOr rMr!_check_signaturevs    rVc Cs6dD]}z t||t||WqtyYqwdS)N)rr__text_signature__r __defaults____kwdefaults__)setattrr/rC)r6funcopy attributer r r!rQs rQcCs@t|trdSt|tttfrt|jSt|dddurdSdS)NTrBF)r-r: staticmethod classmethodr _callabler+r/r1r r r!r_s  r_cCst|ttfvSr8)r:listtupler1r r r!_is_listsrbcCsFt|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.rBNTF)r-r:r/__mro____dict__get)r2baser r r!_instance_callables rgc st|t}t|||}|dur|S|\}fdd}t|||j}|s)d}||d}d|} t| |||} t| || S)Ncsj|i|dSr8rGrKrLrMr r!rOrPz _set_signature..checksigr[)Z _checksig_r>zYdef %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs))r-r:rFrQr isidentifierexec _setup_func) r>originalrUrTresultr6rOr(contextsrcr[r rMr!_set_signatures$       rpc s_fdd}fdd}fdd}fdd}fd d }fd d }fd d} fdd} d_d_d_t_t_t_j_j _ j _ |_ |_ |_ | _| _|_|_|_|__dS)Ncj|i|Sr8)assert_called_withrhr>r r!rrz'_setup_func..assert_called_withcrqr8) assert_calledrhrsr r!rurtz"_setup_func..assert_calledcrqr8)assert_not_calledrhrsr r!rvrtz&_setup_func..assert_not_calledcrqr8)assert_called_oncerhrsr r!rwrtz'_setup_func..assert_called_oncecrqr8)assert_called_once_withrhrsr r!rxrtz,_setup_func..assert_called_once_withcrqr8)assert_has_callsrhrsr r!ryrtz%_setup_func..assert_has_callscrqr8)assert_any_callrhrsr r!rzrtz$_setup_func..assert_any_callcsBt_t_j}t|r|ur|dSdSdSr8) _CallList method_calls mock_calls reset_mock return_valuer,)retr[r>r r!r~s z_setup_func..reset_mockFr)r>called call_count call_argsr{call_args_listr|r}r side_effect_mock_childrenrrrxryrzr~rurvrwrS_mock_delegate) r[r>rNrrrurvrwrxryrzr~r rr!rks8        rkcsJtjj_d_d_t_fdd}dD] }t|t||qdS)Nrcstj||i|Sr8)r/r>)attrrKrLrsr 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_argsr{await_args_listrZr)r>rr\r rsr!_setup_async_mocks   rcCsd|dd|kS)N__%s__r r(r r r! _is_magicrPrc@(eZdZdZddZddZddZdS) _SentinelObjectz!A unique, named, sentinel object.cCs ||_dSr8rrJr(r r r!rA z_SentinelObject.__init__cC d|jSNz sentinel.%srrJr r r!__repr__rz_SentinelObject.__repr__cCrrrrr r r! __reduce__!rz_SentinelObject.__reduce__N)rrrrrArrr r r r!rs  rc@r) _SentinelzAAccess attributes to return a named object, usable as a sentinel.cCs i|_dSr8) _sentinelsrr r r!rA'rz_Sentinel.__init__cCs|dkrt|j|t|S)N __bases__)rCr setdefaultrrr r r! __getattr__*sz_Sentinel.__getattr__cCdS)Nrr rr r r!r0z_Sentinel.__reduce__N)rrrrrArrr r r r!r%s  r>r_mock_new_name _mock_parent _mock_name_mock_new_parent_mock_return_valuer_mock_side_effectcCs8t|d|}||fdd}||fdd}t||S)NZ_mock_cSs"|j}|dur t||St||Sr8)rr/)rJr( _the_namerNr r r!_getEs  z"_delegating_property.._getcSs,|j}|dur||j|<dSt|||dSr8)rrdrZ)rJvaluer(rrNr r r!_setJsz"_delegating_property.._set)_allowed_namesaddproperty)r(rrrr r r!_delegating_propertyBs  rc@eZdZddZddZdS)r{cCslt|ts t||St|}t|}||krdStd||dD]}||||}||kr3dSq"dS)NFrT)r-r` __contains__lenrange)rJrZ len_valueZlen_selfiZsub_listr r r!rWs  z_CallList.__contains__cCstt|Sr8)pprintZpformatr`rr r r!rez_CallList.__repr__N)rrrrrr r r r!r{Us r{cCst|}t|s dS|js|js|jdus|jdurdS|}|dur/||ur(dS|j}|dus"|r7||_||_|r?||_||_dS)NFT)r@r,rrrr)parentrr(new_name_parentr r r!_check_and_set_parentis(   rc@r) _MockItercCst||_dSr8)iterr2)rJr2r r r!rArz_MockIter.__init__cCs t|jSr8)nextr2rr r r!__next__rz_MockIter.__next__N)rrrrArr r r r!rs rc@seZdZeZdZddZdS)BaseNcOdSr8r rIr r r!rArz Base.__init__)rrrrrrrAr 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) r9AsyncMockMixin _MOCK_SIGZ bind_partialZ argumentsrer3r:rr _safe_superr __new__)clsrKkwbasesZ bound_argsZspec_argnewrUr 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_wrapsrZ _mock_calledZ_mock_call_argsrZ_mock_call_countZ_mock_call_args_listZ_mock_mock_callsr| _mock_unsafer )rd_mock_add_specr{configure_mockrr rA)rJrrr(rr _spec_state _new_name _new_parent_spec_as_instance _eat_selfunsaferLrdr r r!rAs<     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)r@rrrrrZ)rJr>r\Z 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)rrJrrr 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/appendrbr-r:rFrd) rJrrrrrrrrresrdr r r!rs,     zNonCallableMock._mock_add_speccCs8|j}|jdur |jj}|tur|j|dd}||_|S)N()rr)rrrr_get_child_mock)rJrr r r!Z__get_return_values z"NonCallableMock.__get_return_valuecCs.|jdur ||j_dS||_t||dddS)Nr)rrrr)rJrr r r!Z__set_return_values  z"NonCallableMock.__set_return_valuez1The value to be returned when the mock is called.cCs|jdur t|S|jSr8)rr:rr r r! __class__'s zNonCallableMock.__class__rrrrr}cCsN|j}|dur |jS|j}|dur%t|s%t|ts%t|s%t|}||_|Sr8)rrrcallabler-rr<)rJ delegatedZsfr r r!Z__get_side_effect4sz!NonCallableMock.__get_side_effectcCs*t|}|j}|dur||_dS||_dSr8) _try_iterrrr)rJrrr r r!Z__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)idrrrrr{r}rr|rrrrvaluesr- _SpecState_deletedr~r,)rJZvisitedrrchildrr r r!r~Js. 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/rZ)rJrLargvalrKfinalr2rr 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)assertZassretZasertZaseertZassrtz6 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=])rCr _all_magicsrrr&r _lockrrerrr/rr-rrrrrUrr(rrd)rJr(rmr 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)rrrr`reversedrrjoin)rJZ _name_listrZlastdotZ_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'>)rrrrr:r)rJr(Z name_stringZ 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'Zm_nameZm_valuer r r! s z+NonCallableMock.__dir__..cSsg|] }|ds|qSr#r%r'er r r!rr*cSs"g|] }|dr t|r|qSr#)r&rrr r r!rs ) r object__dir__rrr:r`rdrrrset)rJZextrasZ from_typeZ from_dictZfrom_child_mocksr r r!rs    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|Sr8r rKrrlrJr r!rz-NonCallableMock.__setattr__..rrz Cannot set )rr __setattr__rrrdrC_unsupported_magicsrr,rZr: _get_methodrrrrr.r)rJr(rmsg mock_namer rr!r s8      zNonCallableMock.__setattr__cCs|tvr|t|jvrtt||||jvrdS|j|t}||jvr.tt| |n|t ur6t ||tur>|j|=t |j|<dSr8) rr:rddelattrrre_missingrr __delattr__rrC)rJr(r2r r r!r's  zNonCallableMock.__delattr__cCs|jpd}t|||Sr=)r_format_call_signaturerJrKrLr(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)r*r)rJrKrLactionmessageexpected_stringrZ 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)rreplacerrrer-rr@)rJr(rNnameschildrenrr 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-rarr2rrHrrKrL TypeErrorwith_traceback)rJ_callrNr(rKrLZ bound_callrr 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_reprAssertionErrorrJr#r r r!rvr 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)rrr9r:r r r!ru|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>Nr7r:r r r!rwr;z"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}|Sr8r.r#rKrLrJr r!_error_messages z:NonCallableMock.assert_called_with.._error_messageTtwo)rr*r9r6_Callr- Exception)rJrKrLexpectedactualZ error_messager?causer r>r!rrs    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>)rrr8r9rrrJrKrLr#r r r!rxs 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 r6r'crr r!rrz4NonCallableMock.assert_has_calls..cs|] }t|tr|VqdSr8r-rCrr r r! z3NonCallableMock.assert_has_calls..Nc3|]}|VqdSr8rIrJrr r!rNzCalls not found.z+Error processing expected calls. Errors: {}cSg|] }t|tr |ndqSr8rMrr r r!r Expected: ZActual)prefixrz@%r does not contain all of %r in its call list, found %r insteadr>) rr{r}formatr9r8rstripr`removerErrra) rJcalls any_orderrDrFZ all_callsproblem not_foundkallr rr!rysV  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.Tr@NcrHr rIrJrr r!rrz3NonCallableMock.assert_any_call..z%s call not found)r6rBr-rCr _AnyComparerr*r9rJrKrLrDrFrEr-r rr!rzs 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 )rrrCrerdr r:r9r_async_method_magicsr_all_sync_magicsr CallableMixinr r rrc)rJrr\r$r_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)r}r)rJrUr r r!r8szNonCallableMock._calls_repr) NNNNNNrNFNFF)FFr8)r)rf)/rrrrrrrrArrrZ"_NonCallableMock__get_return_valueZ"_NonCallableMock__set_return_valueZ"_NonCallableMock__return_value_docrrrrrrrrr}Z!_NonCallableMock__get_side_effectZ!_NonCallableMock__set_side_effectrr~rrrrrr r'r*r.r2r6rvrurwrrrxryrzrr8r r r r!r sd -      0' !   -&r c@seZdZdZddZdS)r_zA 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]}tddt||DrdSqdS)NcSsg|]\}}||kqSr r )r'rDrEr r r!r+sz-_AnyComparer.__contains__..TF)allzip)rJitemr5r r r!r(sz_AnyComparer.__contains__N)rrrrrr r r r!r_#s r_cCsF|dur|St|r |St|r|Szt|WSty"|YSwr8)r<r_rr3r1r r r!r3s  rc @sReZdZddedddddddf ddZddZddZd d Zd d Zd dZ dS)rcNrc Ks:||jd<tt|j||||||| | fi| ||_dS)Nr)rdrrcrAr) rJrrrrr(rrrrrrLr r r!rADs    zCallableMixin.__init__cOrr8r rIr r r!rRPszCallableMixin._mock_check_sigcOs0|j|i||j|i||j|i|Sr8)rR_increment_mock_call _mock_callrIr r r!rBUszCallableMixin.__call__cOs|j|i|Sr8)_execute_mock_callrIr r r!rm]rtzCallableMixin._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|jSr8)rr<r_rrrrr)rJrKrLeffectrmr r r!rns"  z CallableMixin._execute_mock_call) rrrrrArRrBrmrlrnr r r r!rcBs   .rcc@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||YSwr8)r/rC __import__)thingcomp import_pathr r r! _dot_lookups   rtcCsB|d}|d}t|}|D]}|d|7}t|||}q|S)Nrrz.%s)rrrprt)targetZ componentsrsrqrrr r r! _importers   rvcCs(d}|D] }||vrt|dqdS)N)Z autospectZ auto_specZset_specz5 might be a typo; use unsafe=True if this is intended) RuntimeError)Zkwargs_to_checkZtyposZtypor r r!_check_spec_arg_typossrxc@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=rz? as the spec_set target has already been mocked out. [spec_set=F)rrErxr,rgetterr\r new_callablercreateZ has_localrautospecrLadditional_patchers) rJr{r\rrr}rr~r|rLrr r r!rAsD 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..) ryr{r\rrr}rr~r|rLattribute_namer)rJpatcherr r r!r&s z _patch.copycC2t|tr ||St|r||S||Sr8r-r:decorate_classr0rdecorate_async_callabledecorate_callablerJr6r r r!rB3     z_patch.__call__cCsNt|D] }|tjs qt||}t|dsq|}t||||q|SNrB)rr&r TEST_PREFIXr/r.rrZ)rJrer attr_valuerr r r!r;s    z_patch.decorate_classccsg}t4}|jD]}||}|jdur||q |jtur'||q |t |7}||fVWddS1s>wYdSr8) contextlib ExitStack patchings enter_contextrupdaterrrra)rJpatchedrKkeywargs extra_args exit_stackpatchingrr r r!decoration_helperIs         "z_patch.decoration_helperc>tdr jStfddg_S)NrcsD||\}}|i|WdS1swYdSr8rrKrZnewargsZ newkeywargsr6rrJr r!r^s $z)_patch.decorate_callable..patchedr.rrrrr rr!rX  z_patch.decorate_callablecr)NrcsL||\}}|i|IdHWdS1swYdSr8rrrr 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) r{r\rrdrCKeyErrorr/ _builtinsr-rr})rJrur(rllocalr 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.)rsplitr3rErC)rur\r{r rr! _get_targetLs rrzc 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 strcSr8r r rr r!rlz_patch_object..rz)r:strr3ry) rur\rrr}rr~r|rrLr{r 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. crr8rr rr r!rrz!_patch_multiple..crr8r r rr r!rrz=Must supply at least one keyword argument with patch.multiplerrN) r:rrEr`rryrrr) rurr}rr~r|rLr{rr\rrZ this_patcherr rr!_patch_multipless,      rc 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. rz)rry) rurrr}rr~r|rrLr{r\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|_dSr8)in_dictdictrrclear _original)rJrrrrLr r r!rAs    z_patch_dict.__init__cCrr8r)rJfr r r!rBrz_patch_dict.__call__ctfdd}|S)Ncs,z |i|WSwr8r _unpatch_dictrrrJr r!_inner%sz-_patch_dict.decorate_callable.._innerrrJrrr rr!r$z_patch_dict.decorate_callablecr)Ncs4z|i|IdHWSwr8rrrr 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.rrrrrZ)rJrerrZ decoratorZ decoratedr r r!r<s    z_patch_dict.decorate_classcCs||jS)zPatch the dict.)rrrr r r!rGsz_patch_dict.__enter__cCs|j}t|jtrt|j|_|j}|j}z|}Wnty1i}|D]}||||<q&Ynw||_|r;t |z| |WdStyX|D]}||||<qLYdSwr8) rr-rrrvrrrCr _clear_dictr)rJrrrrlrr r r!rMs.     z_patch_dict._patch_dictcCsP|j}|j}t|z||WdSty'|D]}||||<qYdSwr8)rrrrrC)rJrrlrr r r!ris z_patch_dict._unpatch_dictcGs|jdur |dS)zUnpatch the dict.NF)rr)rJrKr r r!rvs z_patch_dict.__exit__cCs|}tj||Sr)rryrrrr r r!r}rz_patch_dict.startcCs4ztj|Wn tyYdSw|dddSr)ryrrXrErrr r r!rrz_patch_dict.stopN)r F)rrrrrArBrrrrrrrrrr r r r!rs       rcCs<z|WdStyt|}|D]}||=qYdSwr8)rrCr`)rkeysrr r r!rs rcCsttjD]}|qdS)z7Stop all active patches. LIFO to unroll nested patches.N)rryrr)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!rNrNccr)zr%sNr rr r r!rNr>r __reversed____subclasses__Z__getinitargs__ __missing__ __reduce_ex__ __delete__ __setstate__ __getstate__r__getnewargs_ex____get__ __getformat____set__ __setformat__r__getnewargs__ __format__csfdd}||_|S)z:Turns a callable object (like a mock) into a real functioncs|g|Ri|Sr8r rJrKrr5r r!methodrz_get_method..method)r)r(r6rr r5r!r"s r"cCsh|]}d|qS)rr )r'rr r r!r)r> __aexit__ __aenter__ __anext__ __aiter__> __prepare__r__subclasscheck__r rrA__del____instancecheck__cC t|Sr8)r__hash__rr r r!r rcCrr8)r__str__rr r r!rrcCrr8)r __sizeof__rr r r!rrcCs"t|jd|dt|S)N/)r:rrrrr r r!rs")rrr __fspath__ry?g?) __lt____gt____le____ge____int__r__len__r __complex__ __float____bool__ __index__rcfdd}|S)Ncs$jj}|tur |S|urdStSNT)__eq__rrNotImplemented)otherret_valrr r!rs z_get_eq..__eq__r )rJrr rr!_get_eq r cr)Ncs jjturtS|urdStSNF)__ne__rrr)rrr r!r s z_get_ne..__ne__r )rJr r rr!_get_nes rcr)Ncs jj}|tur tgSt|Sr8)__iter__rrrr rr r!rsz_get_iter..__iter__r )rJrr rr! _get_iterr rcr)Ncs(jj}|turttgStt|Sr8)rrr_AsyncIteratorrrrr r!rs  z"_get_async_iter..__aiter__r )rJrr rr!_get_async_iters r)rr rrcCsft|t}|tur||_dSt|}|dur!||}||_dSt|}|dur1|||_dSdSr8)_return_valuesrerr_calculate_return_value_side_effect_methodsr)r>rr(ZfixedZreturn_calculatorrZ side_effectorr r r!_set_return_value*s   rc@r) MagicMixincO*|tt|j|i||dSr8)_mock_set_magicsrrrArr r r!rA= zMagicMixin.__init__cCsttB}|}t|dddur,||j}t}||}|D]}|t|jvr+t||q|tt|j}t|}|D] }t ||t ||q;dS)Nr) _magicsrar/ intersectionrrr:rdr%rZ MagicProxy)rJZ orig_magicsZ these_magicsZ remove_magicsrrdr r r!rCs  zMagicMixin._mock_set_magicsN)rrrrArr r r r!r<s rc@eZdZdZdddZdS)r z-A version of `MagicMock` that isn't callable.FcC||||dSrrrrr r r!r]  z"NonCallableMagicMock.mock_add_specNrhrrrrrr r r r!r [sr c@seZdZddZdS)AsyncMagicMixincOrr8)rrr$rArr r r!rAhrzAsyncMagicMixin.__init__NrrrrAr r r r!r$gs r$c@r)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`. FcCr rr!rr r r!rxr"zMagicMock.mock_add_specNrhr#r r r r!rms rc@s&eZdZddZddZdddZdS) rcCs||_||_dSr8r(r)rJr(rr r r!rAs zMagicProxy.__init__cCs8|j}|j}|j|||d}t|||t||||S)N)r(rr)r(rrrZr)rJrrmr r r! create_mocks  zMagicProxy.create_mockNcCs|Sr8)r()rJr2rdr r r!rszMagicProxy.__get__r8)rrrrAr(rr r r r!rs rcseZdZedZedZedZfddZddZdd 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) NrrZ_mock_await_countZ_mock_await_argsZ_mock_await_args_listrr4r rrXrYr) superrArrrrdr{r rr0Z CO_COROUTINEco_flagsra)rJrKrL code_mockrr r!rAs        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)NTr@r)rBrrrrrr<r_r StopIterationStopAsyncIterationrrrrr)rJrKrLr5rormr r r!rns<      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.Nrrr9r:r r r!rs zAsyncMockMixin.assert_awaitedcCs0|jdksd|jp dd|jd}t|dS)z@ Assert that the mock was awaited exactly once. rr0r>$ to have been awaited once. Awaited  times.Nr1r:r 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)r+r<r=r>r r!r?sz:AsyncMockMixin.assert_awaited_with.._error_messageTr@)rr*r9r6rBr-rC)rJrKrLrDr?rErFr r>r!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. rr0r>r2r3)rrr9rrGr r r!rs z'AsyncMockMixin.assert_awaited_once_withcr^)zU Assert the mock has ever been awaited with the specified arguments. Tr@NcrHr rIrJrr r!r rz3AsyncMockMixin.assert_any_await..z%s await not found)r6rBr-rCrr_r*r9r`r 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`. crHr rIrJrr r!r rz4AsyncMockMixin.assert_has_awaits..csrLr8rMrr r r!rN rOz3AsyncMockMixin.assert_has_awaits..Nc3rPr8rIrJrr r!rN rQzAwaits not found.z,Error processing expected awaits. Errors: {}cSrRr8rMrr r r!r' rSrTz Actual: z%r not all found in await list) rr{rrVr9r`rXrErra) rJrYrZrDrFZ all_awaitsr[r\r]r rr!r sN   z AsyncMockMixin.assert_has_awaitscCs0|jdkrd|jp dd|jd}t|dS)z9 Assert that the mock was never awaited. rr0r>z# to not have been awaited. Awaited r3Nr1r:r r r!r= r4z!AsyncMockMixin.assert_not_awaitedcs*tj|i|d|_d|_t|_dS)z0 See :func:`.Mock.reset_mock()` rN)r*r~rrr{rrIr-r r!r~F s zAsyncMockMixin.reset_mockrh)rrrrrrrrArnrrrrrrrr~ __classcell__r r r-r!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.cCrrr rJrr r r!r~ rz _ANY.__eq__cCrr r r8r r r!r  rz _ANY.__ne__cCr)Nzr rr r r!r rz _ANY.__repr__N)rrrrrr rr r r r!r7{ s  r7cCs`d|}d}ddd|D}ddd|D}|r |}|r,|r(|d7}||7}||S)Nz%s(%%s)rz, cSsg|]}t|qSr )repr)r'rr r r!r sz*_format_call_signature..cSsg|] \}}d||fqS)z%s=%rr )r'rrr r r!r s)rr)r(rKrLr,Zformatted_argsZ args_stringZ kwargs_stringr r r!r( s r(c@seZdZdZ  dddZ  dd d Zd d ZejZd dZ ddZ ddZ ddZ e ddZe ddZddZddZdS)rBa 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-rrar) rrr(rrA from_kallrKrL_lenfirstsecondr r r!r s.      z _Call.__new__cCs||_||_||_dSr8)rr_mock_from_kall)rJrr(rrAr;r r r!rA 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 r:r)rr3rr/rr-rar) rJrZ len_otherZ self_nameZ self_argsZ self_kwargsZ other_nameZ other_argsZ other_kwargsrr=r>r r r!r sN                 z _Call.__eq__cOs<|jdurtd||fddS|jd}t|j||f||dS)Nrrrr&rrBr)r r r!rB s  z_Call.__call__cCs2|jdur t|ddSd|j|f}t||ddS)NF)r(r;z%s.%s)r(rr;r@)rJrr(r r r!r s  z_Call.__getattr__cCs|tjvrtt||Sr8)rardrC__getattribute__)rJrr r r!rA s  z_Call.__getattribute__cCs.t|dkr|\}}||fS|\}}}||fS)Nr)rr)r r r!_get_call_arguments$ s  z_Call._get_call_argumentscC |dSNrrBrr r r!rK,  z _Call.argscCrC)NrrErr r r!rL0 rFz _Call.kwargscCs||js|jpd}|drd|}|St|dkr d}|\}}n|\}}}|s*d}n|ds4d|}nd|}t|||S)Nrrzcall%srzcall.%s)r?rr&rr()rJr(rKrLr 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)r?rrr{r)rJZvalsrqr r r! call_listI s  z_Call.call_list)r rNFT)r NNFT)rrrrrrArrr rBrrArBrrKrLrrGr r r r!rB s(   5   rB)r;c Ksht|rt|}t|t}t|rtd|dt|}d|i} |r(d|i} n|dur.i} | r6|r6d| d<|s _must_skiprrZ)rrrUrrrrLis_typeZ is_async_funcrrrr>rrlrrrTZ child_klassr r r!rY s                       rcCsvt|ts|t|divrdS|j}|jD]#}|j|t}|tur#qt|tt fr-dSt|t r6|SdS|S)z[ Return whether we should skip the first argument on spec's `entry` attribute. rdF) r-r:r/rrcrdrerr]r^r?)rrrIrermr r r!rH s   rHc@seZdZ  dddZdS)rFNcCs(||_||_||_||_||_||_dSr8)ridsrrrUr()rJrrrr(rJrUr r r!rA s  z_SpecState.__init__)FNNNFr%r r r r!r srcCst|tr t|St|Sr8)r-bytesioBytesIOStringIO) read_datar r r! _to_stream s   rPrcs&t}|dgfdd}fdd}fddfdd fd d }tdurDd dl}ttt|jtt|ja|durNt d t d}t tdj _ dj _ dj_ dj_ dj_ |j_d<dj_|j_j_|j_fdd}||_|_ |S)a A helper function to create a mock to replace the use of `open`. It works for `open` called directly or used as a context manager. The `mock` argument is the mock object to configure. If `None` (the default) then a `MagicMock` will be created for you, with the API limited to methods or attributes available on standard file handles. `read_data` is a string for the `read`, `readline` and `readlines` of the file handle to return. This is an empty string by default. Nc(jjdur jjSdj|i|SrD) readlinesrrh_statehandler r!_readlines_side_effect.  z)mock_open.._readlines_side_effectcrQrD)readrrhrSr r!_read_side_effect3 rWz$mock_open.._read_side_effectc?s(EdH dj|i|VqNTr)readlinerh)_iter_side_effectrTr r!_readline_side_effect8 s  z(mock_open.._readline_side_effectc3s4jjdur jjVqdD]}|VqdSrZ)r[r)linerSr r!r\= s   z$mock_open.._iter_side_effectcs jjdur jjStdSrD)r[rrr rSr r!_next_side_effectD s  z$mock_open.._next_side_effectropen)r(r)rrcs6td<jjdkrd<dj_tS)Nrr)rPr[rrrh)r]rTrUrOr r! reset_data` s   zmock_open..reset_data)rP file_spec_ior`rr TextIOWrapperunionrMrr`rrwriterXr[rRrrr)r>rOZ _read_datarVrYr_rcrar )r\r]rTrUrOr!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)rJrLr r r!rv rzPropertyMock._get_child_mockNcCs|Sr8r )rJr2Zobj_typer r r!ry szPropertyMock.__get__cCs ||dSr8r )rJr2rr r r!r{ s zPropertyMock.__set__r8)rrrrrrrr 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/rCr-r rrerrr)r>rr'r r r!r s    rc@s eZdZdZddZddZdS)rz8 Wraps an iterator in an asynchronous iterator. cCs&||_ttd}tj|_||jd<dS)Nr)r4)iteratorr rr0ZCO_ITERABLE_COROUTINEr+rd)rJrgr,r r r!rA s z_AsyncIterator.__init__cs$zt|jWStyYtwr8)rrgr.r/rr r r!r s  z_AsyncIterator.__anext__N)rrrrrArr r r r!r s rrh)NFNNN)FFNN)Nr)__all__rrrLr0rrbuiltinsrtypesrrrZ unittest.utilr functoolsrrZ threadingrrCrrrr r*rr3r7r,r<r@rFrVrQr_rbrgrprkrrrrrrrMISSINGr&ZDELETEDrrrr`r{rrrr rDrArr_rrcrrtrvrxryrrrrrrrrZmultipleZstopallrZ magic_methodsZnumericsrrZinplacerightZ _non_defaultsr"rraZ_sync_async_magicsZ _async_magicsrbrr!rrrr rrrrrrr r$rrrr r7rr(rarBrrrHrr:rr?rbrPr rrrr r r r!sD        1  h4  R   2 R        <+  :   N