a DOg@sdZddlZddlZddlZddlZddlZddlZddlZddlmZddl m Z m Z m Z ddl mZddlmZmZddeeDZd ZeZd d Zd d ZddZddZddZddZdddZddZddZddZ dd 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+Z,e)j-Z.hd-Z/d.d/Z0Gd0d1d1e1Z2d2d3Z3Gd4d5d5e&Z4Gd6d7d7e&Z5Gd8d9d9e5Z6e7e6j8Z9Gd:d;d;e1Z:dd?d?e5ZdDdEZ?GdFdGdGe&Z@dHdIZAe*dddddfdJdKZBddLdMZCe*dddddfdNdOZDGdPdQdQe&ZEdRdSZFdTdUZGeBeD_&eEeD_HeCeD_IeGeD_JdVeD_KdWZLdXZMdYNdZd[eMODZPdYNd\d[eMODZQhd]ZRd^d_ZSd`ddYNeLeMePeQgODZThdaZUdbhZVeUeVBZWeTeRBZXeXeWBZYhdcZZdddedfdedgdedhdediZ[e\e\e\e\djddddkdld djddm Z]dndoZ^dpdqZ_drdsZ`dtduZae^e_e`eadvZbdwdxZcGdydzdze5ZdGd{d|d|ede6ZeGd}d~d~edZfGdddede=ZgGddde5ZhGddde5ZiGdddeiefe=ZjGddde&ZkekZlddZmGdddenZoeoddZpdddZqddZrGddde&ZseteqeteljufZvdawddZxdddZyGddde=ZzddZ{GdddZ|dS))Mock MagicMockpatchsentinelDEFAULTANYcallcreate_autospec AsyncMock FILTER_DIRNonCallableMockNonCallableMagicMock mock_open PropertyMocksealN)iscoroutinefunction)CodeType ModuleType MethodType) safe_repr)wrapspartialcCsh|]}|ds|qS_ startswith).0namer2/opt/alt/python39/lib64/python3.9/unittest/mock.py 'r TcCs<t|rt|tsdSt|dr*t|d}t|p:t|S)NF__func__)_is_instance_mock isinstancer hasattrgetattrrinspectZ isawaitableobjrrr _is_async_obj/s   r*cCst|ddrt|SdSdS)N__code__F)r&rfuncrrr_is_async_func7s r.cCstt|tSN) issubclasstyper r(rrrr#>sr#cCst|tpt|tot|tSr/)r$ BaseExceptionr1r0r(rrr _is_exceptionDs r3cCs"t|trt|dr|jS|SdSNmock)r$ FunctionTypesr%r5r(rrr _extract_mockKsr7cCst|tr|s|j}d}n*t|tsDz |j}WntyBYdS0|rTt|d}n|}z|t|fWSt y|YdS0dS)z Given an arbitrary, possibly callable object, try to create a suitable signature object. Return a (reduced func, signature) tuple, or None. TN) r$r1__init__r6__call__AttributeErrorrr' signature ValueError)r-Z as_instanceZeat_selfZsig_funcrrr_get_signature_objectTs     r=FcsNt|||durdS\}fdd}t|||t|_t|_dS)Ncsj|i|dSr/bindselfargskwargssigrrchecksigvsz"_check_signature..checksig)r=_copy_func_detailsr1_mock_check_sig __signature__)r-r5 skipfirstinstancerFrrDr_check_signatureqs    rLc Cs8dD].}zt||t||Wqty0Yq0qdS)N)__name____doc____text_signature__ __module__ __defaults____kwdefaults__)setattrr&r:)r-funcopy attributerrrrG}s  rGcCs@t|trdSt|tttfr(t|jSt|dddurrBrCrDrrrFsz _set_signature..checksigrT)Z _checksig_r5zYdef %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs))r$r1r=rGrM isidentifierexec _setup_func) r5originalrKrJresultr-rFrcontextsrcrTrrDr_set_signatures$       ric s_fdd}fdd}fdd}fdd}fd d }fd d }fd d} fdd} d_d_d_t_t_t_j_j _ j _ |_ |_ |_ | _| _|_|_|_|__dS)Ncsj|i|Sr/)assert_called_withrar5rrrjsz'_setup_func..assert_called_withcsj|i|Sr/) assert_calledrarkrrrlsz"_setup_func..assert_calledcsj|i|Sr/)assert_not_calledrarkrrrmsz&_setup_func..assert_not_calledcsj|i|Sr/)assert_called_oncerarkrrrnsz'_setup_func..assert_called_oncecsj|i|Sr/)assert_called_once_withrarkrrrosz,_setup_func..assert_called_once_withcsj|i|Sr/)assert_has_callsrarkrrrpsz%_setup_func..assert_has_callscsj|i|Sr/)assert_any_callrarkrrrqsz$_setup_func..assert_any_callcs:t_t_j}t|r6|ur6|dSr/) _CallList method_calls mock_calls reset_mock return_valuer#)retrTr5rrrus z_setup_func..reset_mockFr)r5called call_count call_argsrrcall_args_listrsrtrv side_effect_mock_childrenrjrorprqrurlrmrnrI_mock_delegate) rTr5rErjrlrmrnrorprqrurrxrrds8       rdcsJtjj_d_d_t_fdd}dD]}t|t||q.dS)Nrcstj||i|Sr/)r&r5)attrrBrCrkrrwrappersz"_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_argsrrawait_args_listrSr)r5rrUrrkr_setup_async_mocks   rcCsd|dd|kS)N__%s__rrrrr _is_magicsrc@s(eZdZdZddZddZddZdS) _SentinelObjectz!A unique, named, sentinel object.cCs ||_dSr/rrArrrrr8sz_SentinelObject.__init__cCs d|jSNz sentinel.%srrArrr__repr__sz_SentinelObject.__repr__cCs d|jSrrrrrr __reduce__sz_SentinelObject.__reduce__N)rMrP __qualname__rNr8rrrrrrrsrc@s(eZdZdZddZddZddZdS) _SentinelzAAccess attributes to return a named object, usable as a sentinel.cCs i|_dSr/) _sentinelsrrrrr8"sz_Sentinel.__init__cCs|dkr t|j|t|S)N __bases__)r:r setdefaultrrrrr __getattr__%sz_Sentinel.__getattr__cCsdS)Nrrrrrrr+sz_Sentinel.__reduce__N)rMrPrrNr8rrrrrrr sr>_mock_return_value_mock_side_effectr} _mock_name_mock_new_parent _mock_parentrv_mock_new_namecCs8t|d|}||fdd}||fdd}t||S)NZ_mock_cSs"|j}|durt||St||Sr/)rr&)rAr _the_namerErrr_get@s z"_delegating_property.._getcSs*|j}|dur||j|<n t|||dSr/)rr]rS)rAvaluerrrErrr_setEs z"_delegating_property.._set)_allowed_namesaddproperty)rrrrrrr_delegating_property=s  rc@seZdZddZddZdS)rrcCslt|tst||St|}t|}||kr2dStd||dD]"}||||}||krDdSqDdS)NFrT)r$rY __contains__lenrange)rArZ len_valueZlen_selfiZsub_listrrrrRs  z_CallList.__contains__cCstt|Sr/)pprintZpformatrYrrrrr`sz_CallList.__repr__N)rMrPrrrrrrrrrPsrrcCs|t|}t|sdS|js4|js4|jdus4|jdur8dS|}|durX||urPdS|j}q<|rh||_||_|rx||_||_dS)NFT)r7r#rrrr)parentrrnew_name_parentrrr_check_and_set_parentds* rc@seZdZddZddZdS) _MockItercCst||_dSr/)iterr))rAr)rrrr8sz_MockIter.__init__cCs t|jSr/)nextr)rrrr__next__sz_MockIter.__next__N)rMrPrr8rrrrrrsrc@seZdZeZdZddZdS)BaseNcOsdSr/rr@rrrr8sz Base.__init__)rMrPrrrrr8rrrrrsrc @sdeZdZdZddZdLddZd d ZdMd d ZdNd dZddZ ddZ dZ e e e e Z e ddZedZedZedZedZedZddZddZe eeZdOdddd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Z dPd3d4Z!d5d6Z"d7d8Z#d9d:Z$d;d<Z%d=d>Z&d?d@Z'dAdBZ(dQdCdDZ)dEdFZ*dGdHZ+dRdJdKZ,dS)Sr z A non-callable version of `Mock`cOs||f}t|tsTtj|g|Ri|j}|d|d}|durTt|rTt|f}t|j|d|j i}t t | |}|S)Nspec_setspecrN) r0AsyncMockMixin _MOCK_SIGZ bind_partialZ argumentsr^r*r1rMrN _safe_superr __new__)clsrBkwbasesZ bound_argsZspec_argnewrKrrrrs zNonCallableMock.__new__NFc Ks|dur |}|j} || d<|| d<|| d<|| d<d| d<|durJ|}d}| durZ|du} |||| | i| d<|| d <d| d <d| d <d| d <d | d<t| d<t| d<t| d<| | d<| r|jfi| tt|||||||dS)NrrrrF _mock_sealedTr~ _mock_wrapsrZ _mock_calledZ_mock_call_argsrZ_mock_call_countZ_mock_call_args_listZ_mock_mock_callsrs _mock_unsafe)r]_mock_add_specrrconfigure_mockrr r8)rArrrrr _spec_state _new_name _new_parent_spec_as_instance _eat_selfZunsaferCr]rrrr8s<     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)r7rrrrrS)rAr5rUZ inner_mockrrr 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)rrArrrrr mock_add_specszNonCallableMock.mock_add_specc Csd}d}g}t|D]}tt||dr||q|dur|t|s|t|trT|}nt|}t|||} | or| d}t|}|j} || d<|| d<|| d<|| d<|| d<dS)Nr _spec_class _spec_set_spec_signature _mock_methods _spec_asyncs) dirrr&appendr[r$r1r=r]) rArrrrrrrrresr]rrrrs*    zNonCallableMock._mock_add_speccCs8|j}|jdur|jj}|tur4|j|dd}||_|S)N()rr)rrrvr_get_child_mock)rArwrrrZ__get_return_values z"NonCallableMock.__get_return_valuecCs,|jdur||j_n||_t||dddS)Nr)rrvrr)rArrrrZ__set_return_values  z"NonCallableMock.__set_return_valuez1The value to be returned when the mock is called.cCs|jdurt|S|jSr/)rr1rrrr __class__s zNonCallableMock.__class__ryrzr{r|rtcCsN|j}|dur|jS|j}|durJt|sJt|tsJt|sJt|}||_|Sr/)rrr}callabler$rr3)rA delegatedZsfrrrZ__get_side_effect'sz!NonCallableMock.__get_side_effectcCs(t|}|j}|dur||_n||_dSr/) _try_iterrrr})rArrrrrZ__set_side_effect2s z!NonCallableMock.__set_side_effectrvr}cCs|dur g}t||vrdS|t|d|_d|_d|_t|_t|_t|_|r^t |_ |rhd|_ |j D](}t|tsr|turqr|j|||dqr|j }t|r||ur||dS)z-Restore the mock object to its initial state.NFrr)idrryr{rzrrrtr|rsrrrr~valuesr$ _SpecState_deletedrur#)rAZvisitedrvr}childrwrrrru=s, zNonCallableMock.reset_mockcKsXt|dddD]>\}}|d}|}|}|D]}t||}q6t|||qdS)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)entryrrrhr!z0NonCallableMock.configure_mock..)keyrN)sorteditemssplitpopr&rS)rArCargvalrBfinalr)rrrrr[s   zNonCallableMock.configure_mockcCs|dvrt|n:|jdur<||jvs.|tvrLtd|nt|rLt||jsd|drdtd|j|}|turt|np|durd}|j durt |j |}|j |||||d}||j|<n.t |t rt|j|j|j|j|j}||j|<|S)N>rrzMock object has no attribute %r)assertZassretz1Attributes cannot start with 'assert' or 'assret')rrrrr)r:r _all_magicsrrrr~r^rrr&rr$rrrrrKrr)rArrfrrrrrqs:           zNonCallableMock.__getattr__cCs|jg}|j}|}d}|dgkr$d}|durZ|}||j|d}|jdkrRd}|j}q$tt|}|jpnd}t|dkr|ddvr|d7}||d<d|S)Nrrrr5r)rz().r)rrrrYreversedrrjoin)rAZ _name_listrZlastdotZ_firstrrr_extract_mock_names(      z"NonCallableMock._extract_mock_namecCs^|}d}|dvrd|}d}|jdurDd}|jr8d}||jj}dt|j||t|fS)Nr)r5zmock.z name=%rz spec=%rz spec_set=%rz<%s%s%s id='%s'>)rrrrMr1r)rArZ name_stringZ spec_stringrrrrs   zNonCallableMock.__repr__cCsvtst|S|jpg}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)rZm_nameZm_valuerrr sz+NonCallableMock.__dir__..cSsg|]}|ds|qSrrrerrrrr!cSs"g|]}|drt|r|qSr)rrrrrrrs) r object__dir__rrr1rYr]r~rrset)rAZextrasZ from_typeZ from_dictZfrom_child_mocksrrrrs    zNonCallableMock.__dir__csT|tvrt||SjrHjdurH|jvrH|jvrHtd|n|tvrbd|}t|n|tvrjdur|jvrtd|t |st t |t |||fdd}n(t |d|t t |||j|<n,|dkr|_dSt |||r|j|<jrFt|sFd|}td|t||S)Nz!Mock object has no attribute '%s'z.Attempting to set unsupported magic method %r.csg|Ri|Sr/rrBrrerArrrr!z-NonCallableMock.__setattr__..rrz Cannot set )rr __setattr__rrr]r:_unsupported_magicsrr#rSr1 _get_methodrr~rrr%r)rArrmsg mock_namerrrrs<    zNonCallableMock.__setattr__cCs|tvr2|t|jvr2tt||||jvr2dS|j|t}||jvr\tt| |n|t urlt ||tur||j|=t |j|<dSr/) rr1r]delattrr~r^_missingrr __delattr__rr:)rArr)rrrr s  zNonCallableMock.__delattr__cCs|jpd}t|||Sr4)r_format_call_signaturerArBrCrrrr_format_mock_call_signatures z+NonCallableMock._format_mock_call_signaturercCs.d}|||}|j}|j|}||||fS)Nz.expected %s not found. Expected: %s Actual: %s)rr{)rArBrCactionmessageexpected_stringr{Z actual_stringrrr_format_mock_failure_messages   z,NonCallableMock._format_mock_failure_messagecCsj|s |jSd}|ddd}|j}|D]:}||}|dusJt|trPqfq*t|}|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)rreplacerr~r^r$rr7)rArrEnamesZchildrenrrrr_get_call_signature_from_name s  z-NonCallableMock._get_call_signature_from_namec Cst|tr&t|dkr&||d}n|j}|durt|dkrNd}|\}}n |\}}}z"|j|i|}t||j|jWSt y}z| dWYd}~Sd}~00n|SdS)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$rZrrrr?rrBrC TypeErrorwith_traceback)rA_callrErrBrCZ bound_callrrrr _call_matcherAs   "zNonCallableMock._call_matchercCs0|jdkr,d|jpd|j|f}t|dS)z/assert that the mock was never called. rz9Expected '%s' to not have been called. Called %s times.%sr5Nrzr _calls_reprAssertionErrorrAr rrrrm\s z!NonCallableMock.assert_not_calledcCs$|jdkr d|jpd}t|dS)z6assert that the mock was called at least once rz"Expected '%s' to have been called.r5N)rzrrrrrrrlfs  zNonCallableMock.assert_calledcCs0|jdks,d|jpd|j|f}t|dS)z3assert that the mock was called only once. rz:Expected '%s' to have been called once. Called %s times.%sr5Nrrrrrrnns z"NonCallableMock.assert_called_oncecsjdur.}d}d||f}t|fdd}tfdd}j}||krt|trv|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}|Sr/rr rBrCrArr_error_messages z:NonCallableMock.assert_called_with.._error_messageTtwo)r{rrr_Callr$ Exception)rArBrCexpectedactualZ error_messager#causerr"rrjxs   z"NonCallableMock.assert_called_withcOs<|jdks,d|jpd|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.%sr5)rzrrrrjrArBrCr rrrros z'NonCallableMock.assert_called_once_withc sfdd|D}tdd|Dd}tfddjD}|s||vr|durXd}ndd d|D}t|d t|jd d d |dSt|}g}|D]0}z||Wqt y| |Yq0q|rtdj pdt ||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`.csg|]}|qSrrrcrrrrr!z4NonCallableMock.assert_has_calls..css|]}t|tr|VqdSr/r$r'rrrr r!z3NonCallableMock.assert_has_calls..Nc3s|]}|VqdSr/r,r-rrrr0r!zCalls not found.z+Error processing expected calls. Errors: {}cSsg|]}t|tr|ndqSr/r/rrrrrs Expected: ZActual)prefixrz@%r does not contain all of %r in its call list, found %r insteadr5) rrrrtformatrrrstriprYremover<rrrZ) rAcalls any_orderr(r*Z all_callsproblem not_foundkallrrrrpsN  z NonCallableMock.assert_has_callscsjt||fdd}t|tr$|nd}fddjD}|sL|t|vrf||}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$Ncsg|]}|qSrr,r-rrrrr!z3NonCallableMock.assert_any_call..z%s call not found)rr&r$r'r| _AnyComparerrrrArBrCr(r*r)rrrrrqs zNonCallableMock.assert_any_callcKs|d}||jdvr&tfi|S|jrZd|vrBd|dnd}||}t|t|}t|trz|t vrzt}nbt|t r|t vs|j r||j vrt}qt}n4t|t st|trt}qt|trt}n |jd}|fi|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).rrrrrr)r^r]r rrr:r1r0r_async_method_magicsr_all_sync_magicsr CallableMixinr r rr\)rArrrUr _typeklassrrrrs2       zNonCallableMock._get_child_mockCallscCs"|js dSd|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)rtr)rAr2rrrrszNonCallableMock._calls_repr) NNNNNNrNFNF)F)FF)N)r)F)rB)-rMrPrrNrr8rrrZ"_NonCallableMock__get_return_valueZ"_NonCallableMock__set_return_valueZ"_NonCallableMock__return_value_docrrvrrryrzr{r|rtZ!_NonCallableMock__get_side_effectZ!_NonCallableMock__set_side_effectr}rurrrrrrr rrrrrmrlrnrjrorprqrrrrrrr s` -      '' !   -&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|]\}}||kqSrr)rr(r)rrrrsz-_AnyComparer.__contains__..TF)allzip)rAitemrrrrrs z_AnyComparer.__contains__N)rMrPrrNrrrrrr; sr;cCsJ|dur |St|r|St|r$|Sz t|WStyD|YS0dSr/)r3rXrrr(rrrrs  rc @sReZdZddedddddddf ddZddZddZd d Zd d Zd dZ dS)r?Nrc Ks:||jd<tt|j||||||| | fi| ||_dS)Nr)r]rr?r8r}) rArr}rvrrrrrrrrCrrrr8.s   zCallableMixin.__init__cOsdSr/rr@rrrrH:szCallableMixin._mock_check_sigcOs0|j|i||j|i||j|i|Sr/)rH_increment_mock_call _mock_callr@rrrr9?szCallableMixin.__call__cOs|j|i|Sr/)_execute_mock_callr@rrrrHGszCallableMixin._mock_callc Osd|_|jd7_t||fdd}||_|j||jdu}|j}|j}|dk}|j td||f|j }|dur|r|j t|||f|jdu}|r|jd|}t|||f} |j | |jr|rd} nd} |jdk}|j| |}|j }qpdS)NTrr$rrr) ryrzr&r{r|rrrrrtrrs) rArBrCrZdo_method_callsZmethod_call_nameZmock_call_nameZ is_a_callrZthis_mock_callrrrrrGJs4     z"CallableMixin._increment_mock_callcOs|j}|durTt|r|n,t|s:t|}t|rH|n||i|}|turT|S|jturd|jS|jdur~|j|i|S|jSr/)r}r3rXrrrrvr)rArBrCeffectrfrrrrIxs   z CallableMixin._execute_mock_call) rMrPrrr8rHr9rHrGrIrrrrr?,s .r?c@seZdZdZdS)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. NrMrPrrNrrrrrsrcCs6z t||WSty0t|t||YS0dSr/)r&r: __import__)thingcomp import_pathrrr _dot_lookups   rPcCsB|d}|d}t|}|D]}|d|7}t|||}q |S)Nrrz.%s)rrrLrP)targetZ componentsrOrMrNrrr _importers   rRc@szeZdZdZgZddZddZddZdd Ze j d d Z d d Z ddZ ddZddZddZddZddZdS)_patchNc Csn|dur(|turtd|dur(td||_||_||_||_||_||_d|_||_ ||_ | |_ g|_ dS)Nz,Cannot use 'new' and 'new_callable' togetherz1Cannot use 'autospec' and 'new_callable' togetherF) rr<getterrUr new_callablercreateZ has_localrautospecrCadditional_patchers) rArTrUrrrVrrWrUrCrrrr8s(z_patch.__init__c CsHt|j|j|j|j|j|j|j|j|j }|j |_ dd|j D|_ |S)NcSsg|] }|qSr)copy)rprrrrsz_patch.copy..) rSrTrUrrrVrrWrUrCattribute_namerX)rApatcherrrrrYs z _patch.copycCs2t|tr||St|r(||S||Sr/)r$r1decorate_classr'rdecorate_async_callabledecorate_callablerAr-rrrr9s     z_patch.__call__cCsNt|D]@}|tjsqt||}t|ds0q|}t||||q|SNr9)rrr TEST_PREFIXr&r%rYrS)rArAr attr_valuer\rrrr]s    z_patch.decorate_classccsg}tf}|jD]8}||}|jdur8||q|jtur||q|t |7}||fVWdn1sx0YdSr/) contextlib ExitStack patchings enter_contextr[updaterrrrZ)rApatchedrBkeywargs extra_args exit_stackpatchingrrrrdecoration_helpers        z_patch.decoration_helpercs>tdrjStfddg_S)NrfcsD||"\}}|i|WdS1s60YdSr/rnrBrjZnewargsZ newkeywargsr-rirArrri3s z)_patch.decorate_callable..patchedr%rfrrr`rrqrr_-s  z_patch.decorate_callablecs>tdrjStfddg_S)NrfcsJ||(\}}|i|IdHWdS1s<0YdSr/rorprqrrriDs z/_patch.decorate_async_callable..patchedrrr`rrqrr^>s  z_patch.decorate_async_callablec Cs|}|j}t}d}z|j|}Wn"ttfyFt||t}Yn0d}|tvrdt|t rdd|_ |j s|turtd||f||fS)NFTz!%s does not have the attribute %r) rTrUrr]r:KeyErrorr& _builtinsr$rrV)rArQrrelocalrrr get_originalOs  z_patch.get_originalcCs|j|j|j}}}|j|j}}|j}||_|dur@d}|durLd}|durXd}|durp|durptd|dus|dur|dvrtd| \}}|t ur|durd} |dur|}|dur|}d}n&|dur|dur|}d}n |dur|}|dus |dur.|t urtdt |t r.d} |durHt |rHt} nt} i} |dur`|} n^|dust|dur|} |dur|} t| rd| v} n t|  } t | rt} n | rt} |dur|| d <|dur|| d <t | t r t| tr |jr |j| d <| || fi| }| rt|r|} |durF|} t| s^t| s^t} | d | f|d d | |_nl|dur|t urtd|t urtdt|}|dur|}t|f||jd|}n|rtd|}||_||_t |_!zrt"|j|j||j#durti}|jt ur>|||j#<|j$D](}|j!%|}|jt urD||qD|WS|WS|j&t'(sYn0dS)zPerform the patch.FNzCan't specify spec and autospec)TNz6Can't provide explicit spec_set *and* spec or autospecTz!Can't use 'spec' with create=Truer9rrrrrzBautospec creates the mock for you. Can't specify autospec and new.z%Can't use 'autospec' with create=True)r_namez.Can't pass kwargs to a mock we aren't creating))rrrrWrCrUrTrQrrvrr$r1r*r rr[rr r0r rUrhr#r`rrvboolr temp_originalis_localrdre _exit_stackrSr[rXrg__exit__sysexc_info)rArrrrWrCrUreruZinheritKlass_kwargsZ this_specZ not_callableZnew_attrrkrmrrrr __enter__gs                               z_patch.__enter__cGs|jr$|jtur$t|j|j|jn>t|j|j|jsbt|j|jrP|jdvrbt|j|j|j|`|`|`|j }|` |j |S)zUndo the patch.)rNrPrQ__annotations__rR) rzryrrSrQrUr rVr%r{r|)rAr~rlrrrr|sz_patch.__exit__cCs|}|j||Sz-Activate a patch, returning any created mock.)r_active_patchesrrArfrrrstarts z _patch.startcCs4z|j|Wnty$YdS0|dddSzStop an active patch.N)rr5r<r|rrrrstop s  z _patch.stop)rMrPrr[rr8rYr9r]rdcontextmanagerrnr_r^rvrr|rrrrrrrSs   rSc sPzdd\}Wn&tttfy:tdYn0fdd}||fS)Nrrz,Need a valid target to patch. You supplied: cstSr/rRrrQrrrr!z_get_target..)rsplitrr<r:)rQrUrTrrr _get_targets  rc s>tturtdfdd} t| |||||||| 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 strcsSr/rrrrrr5r!z_patch_object..)r1strrrS) rQrUrrrVrrWrUrCrTrrr _patch_objects   rc stturfdd}n fdd}|s2tdt|}|d\} } t|| | |||||i } | | _|ddD]2\} } t|| | |||||i } | | _| j| qt| 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. cstSr/rrrrrrSr!z!_patch_multiple..csSr/rrrrrrUr!z=Must supply at least one keyword argument with patch.multiplerrN) r1rr<rYrrSr[rXr) rQrrVrrWrUrCrTrrUrr\Z this_patcherrrr_patch_multiple<s,      rc Ks$t|\}} t|| ||||||| S)az `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` 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. )rrS) rQrrrVrrWrUrCrTrUrrrrms G  rc@sZeZdZdZdddZddZdd Zd d Zd d ZddZ ddZ ddZ ddZ dS) _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. rFcKs,||_t||_|j|||_d|_dSr/)in_dictdictrrhclear _original)rArrrrCrrrr8s   z_patch_dict.__init__cs.ttrStfdd}|S)Ncs0z|i|WS0dSr/)r _unpatch_dictrfrArr_inners z$_patch_dict.__call__.._inner)r$r1r]r)rArrrrrr9s   z_patch_dict.__call__cCsXt|D]J}t||}|tjrt|drt|j|j|j }||}t |||q|Sra) rr&rrrbr%rrrrrS)rArArrc decoratorZ decoratedrrrr]s   z_patch_dict.decorate_classcCs||jS)zPatch the dict.)rrrrrrrsz_patch_dict.__enter__cCs|j}t|jtrt|j|_|j}|j}z |}Wn,tybi}|D]}||||<qLYn0||_|rvt |z| |Wn(ty|D]}||||<qYn0dSr/) rr$rrrRrrYr:r _clear_dictrh)rArrrrerrrrrs&     z_patch_dict._patch_dictcCsP|j}|j}t|z||Wn(tyJ|D]}||||<q4Yn0dSr/)rrrrhr:)rArrerrrrrs z_patch_dict._unpatch_dictcGs|jdur|dS)zUnpatch the dict.NF)rr)rArBrrrr|)s z_patch_dict.__exit__cCs|}tj||Sr)rrSrrrrrrr0s z_patch_dict.startcCs4ztj|Wnty$YdS0|dddSr)rSrr5r<r|rrrrr7s  z_patch_dict.stopN)rF) rMrPrrNr8r9r]rrrr|rrrrrrrs   rcCs<z |Wn*ty6t|}|D] }||=q&Yn0dSr/)rr:rY)rkeysrrrrrBs   rcCsttjD] }|q dS)z7Stop all active patches. LIFO to unroll nested patches.N)rrSrr)rrrr_patch_stopallKsrtestzlt 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 ccs|]}d|VqdS)zi%sNrrnrrrr0jr!r0ccs|]}d|VqdS)zr%sNrrrrrr0kr!> __format__ __delete__ __getformat____get__ __setstate____getnewargs__ __setformat__ __missing__r__set__r__getnewargs_ex__ __reduce_ex__ __getstate____subclasses__rZ__getinitargs__ __reversed__csfdd}||_|S)z:Turns a callable object (like a mock) into a real functioncs|g|Ri|Sr/rrArBrr,rrmethod|sz_get_method..method)rM)rr-rrr,rrzs rcCsh|] }d|qS)rr)rrrrrr s> __aenter__ __anext__ __aexit__ __aiter__>rrrr8__instancecheck____del__ __prepare____subclasscheck__cCs t|Sr/)r__hash__rrrrrr!rcCs t|Sr/)r__str__rrrrrr!cCs t|Sr/)r __sizeof__rrrrrr!cCs"t|jd|dt|S)N/)r1rMrrrrrrrr!)rrr __fspath__ry?g?) __lt____gt____le____ge____int__r__len__r| __complex__ __float____bool__ __index__rcsfdd}|S)Ncs$jj}|tur|S|ur dStSNT)__eq__rrNotImplemented)otherret_valrrrrs z_get_eq..__eq__r)rArrrr_get_eqs rcsfdd}|S)Ncs jjturtS|urdStSNF)__ne__rrr)rrrrrs  z_get_ne..__ne__r)rArrrr_get_nes rcsfdd}|S)Ncs jj}|turtgSt|Sr/)__iter__rrrrrrrrsz_get_iter..__iter__r)rArrrr _get_iters rcsfdd}|S)Ncs(jj}|turttgStt|Sr/)rrr_AsyncIteratorrrrrrrs z"_get_async_iter..__aiter__r)rArrrr_get_async_iters r)rrrrcCsbt|t}|tur||_dSt|}|durB||}||_dSt|}|dur^|||_dSr/)_return_valuesr^rrv_calculate_return_value_side_effect_methodsr})r5rrZfixedZreturn_calculatorrvZ side_effectorrrr_set_return_values   rc@seZdZddZddZdS) MagicMixincOs*|tt|j|i||dSr/)_mock_set_magicsrrr8rrrrr8szMagicMixin.__init__cCsttB}|}t|dddurX||j}t}||}|D]}|t|jvr:t||q:|tt|j}t|}|D]}t ||t ||qvdS)Nr) _magicsr=r& intersectionrrr1r]r rS MagicProxy)rAZ orig_magicsZ these_magicsZ remove_magicsrr@rrrrs  zMagicMixin._mock_set_magicsN)rMrPrr8rrrrrrsrc@seZdZdZdddZdS)r z-A version of `MagicMock` that isn't callable.FcCs||||dSrrrrrrrrs z"NonCallableMagicMock.mock_add_specN)FrMrPrrNrrrrrr sr c@seZdZddZdS)AsyncMagicMixincOs*|tt|j|i||dSr/)rrrr8rrrrr8szAsyncMagicMixin.__init__NrMrPrr8rrrrrsrc@seZdZdZdddZdS)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`. FcCs||||dSrrrrrrr+s zMagicMock.mock_add_specN)Frrrrrr s rc@s&eZdZddZddZdddZdS) rcCs||_||_dSr/rr)rArrrrrr87szMagicProxy.__init__cCs8|j}|j}|j|||d}t|||t||||S)N)rrr)rrrrSr)rArrmrrr create_mock;s  zMagicProxy.create_mockNcCs|Sr/)r)rAr)r@rrrrDszMagicProxy.__get__)N)rMrPrr8rrrrrrr6s rcseZdZedZedZedZfddZddZdd Z d d Z d d Z ddZ ddZ dddZddZfddZZS)rrrrcs`tj|i|tjj|jd<d|jd<d|jd<t|jd<ttd}t j |_ ||jd<dS)NrrZ_mock_await_countZ_mock_await_argsZ_mock_await_args_listrr+) superr8rrrr]rrr rr'Z CO_COROUTINEco_flags)rArBrC code_mockrrrr8Ms    zAsyncMockMixin.__init__cst||fdd}|jd7_||_|j||j}|durt|rL|nft|sz t|}Wnt yvt Yn0t|r|n,t |r||i|IdH}n||i|}|t ur|S|j t ur|jS|jdur t |jr|j|i|IdHS|j|i|S|jS)NTr$r)r&rrrrr}r3rXr StopIterationStopAsyncIterationrrrrvr)rArBrCrrJrfrrrrI]s6       z!AsyncMockMixin._execute_mock_callcCs(|jdkr$d|jpdd}t|dS)zA Assert that the mock was awaited at least once. r Expected r5z to have been awaited.Nrrrrrrrrs zAsyncMockMixin.assert_awaitedcCs0|jdks,d|jpdd|jd}t|dS)z@ Assert that the mock was awaited exactly once. rrr5$ to have been awaited once. Awaited  times.Nrrrrrrs  z"AsyncMockMixin.assert_awaited_oncecsjdur&}td|dfdd}tfdd}j}||kr~t|trn|nd}t||dS)zN Assert that the last await was with the specified arguments. NzExpected await: z Not awaitedcsjdd}|S)Nawait)rr r!r"rrr#sz:AsyncMockMixin.assert_awaited_with.._error_messageTr$)rrrrr&r$r')rArBrCr(r#r)r*rr"rrs   z"AsyncMockMixin.assert_awaited_withcOs<|jdks,d|jpdd|jd}t||j|i|S)zi Assert that the mock was awaited exactly once and with the specified arguments. rrr5rr)rrrrr+rrrrs  z'AsyncMockMixin.assert_awaited_once_withcsjt||fdd}t|tr$|nd}fddjD}|sL|t|vrf||}td||dS)zU Assert the mock has ever been awaited with the specified arguments. Tr$Ncsg|]}|qSrr,r-rrrrr!z3AsyncMockMixin.assert_any_await..z%s await not found)rr&r$r'rr;rrr<rrrrs zAsyncMockMixin.assert_any_awaitFc sfdd|D}tdd|Dd}tfddjD}|s||vr|durXd}ndd d|D}t|d t|d j|dSt|}g}|D]0}z||Wqty||Yq0q|rtd 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`. csg|]}|qSrr,r-rrrrr!z4AsyncMockMixin.assert_has_awaits..css|]}t|tr|VqdSr/r/rrrrr0r!z3AsyncMockMixin.assert_has_awaits..Nc3s|]}|VqdSr/r,r-rrrr0r!zAwaits not found.z,Error processing expected awaits. Errors: {}cSsg|]}t|tr|ndqSr/r/rrrrrsr1z Actual: z%r not all found in await list) rrrrr3rrYr5r<rrZ) rAr6r7r(r*Z all_awaitsr8r9r:rrrrsF   z AsyncMockMixin.assert_has_awaitscCs0|jdkr,d|jpdd|jd}t|dS)z9 Assert that the mock was never awaited. rrr5z# to not have been awaited. Awaited rNrrrrrrs  z!AsyncMockMixin.assert_not_awaitedcs*tj|i|d|_d|_t|_dS)z0 See :func:`.Mock.reset_mock()` rN)rrurrrrrr@rrrruszAsyncMockMixin.reset_mock)F)rMrPrrrrrr8rIrrrrrrrru __classcell__rrrrrHs (   , rc@seZdZdZdS)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. NrKrrrrr sr c@s(eZdZdZddZddZddZdS) _ANYz2A helper object that compares equal to everything.cCsdSrrrArrrrr- sz _ANY.__eq__cCsdSrrrrrrr0 sz _ANY.__ne__cCsdS)Nzrrrrrr3 sz _ANY.__repr__N)rMrPrrNrrrrrrrr* srcCs`d|}d}ddd|D}ddd|D}|r@|}|rX|rP|d7}||7}||S)Nz%s(%%s)rz, cSsg|] }t|qSr)repr)rrrrrr= r!z*_format_call_signature..cSsg|]\}}d||fqS)z%s=%rr)rrrrrrr> s)rr)rrBrCrZformatted_argsZ args_stringZ kwargs_stringrrrr: s rc@szeZdZdZdddZdd d Zd d ZejZd dZ ddZ ddZ ddZ e ddZe ddZddZddZdS)r&a 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. rrNFTc Csd}i}t|}|dkr$|\}}}nr|dkrd|\} } t| trX| }t| trR| }qb| }q| | }}n2|dkr|\}t|tr|}nt|tr|}n|}|rt|||fSt||||fS)Nrrr)rr$rrZr) rrrrr% from_kallrBrC_lenfirstsecondrrrr_ s.      z _Call.__new__cCs||_||_||_dSr/)rr_mock_from_kall)rArrrr%rrrrr8 sz_Call.__init__c Cs\z t|}Wnty"tYS0d}t|dkr>|\}}n |\}}}t|ddrpt|ddrp|j|jkrpdSd}|dkrdi}}n|dkr|\}}}n|dkr|\} t| tr| }i}n"t| tr| }di}}nd}| }nV|dkr4|\} } t| tr(| }t| tr| i}}n d| }}n | | }}ndS|rL||krLdS||f||fkS) NrrrFrrrr)rrrr&rr$rZr) rArZ len_otherZ self_nameZ self_argsZ self_kwargsZ other_nameZ other_argsZ other_kwargsrrrrrrr sN                  z _Call.__eq__cOs<|jdurtd||fddS|jd}t|j||f||dS)Nrrrrrr&rrrrr9 s  z_Call.__call__cCs2|jdurt|ddSd|j|f}t||ddS)NF)rrz%s.%s)rrrr)rArrrrrr s  z_Call.__getattr__cCs|tjvrtt||Sr/)rZr]r:__getattribute__)rArrrrr s z_Call.__getattribute__cCs(t|dkr|\}}n |\}}}||fS)Nr)rrrrr_get_call_arguments s   z_Call._get_call_argumentscCs |dSNrrrrrrrB sz _Call.argscCs |dS)NrrrrrrrC sz _Call.kwargscCs||js&|jpd}|dr"d|}|St|dkr@d}|\}}n0|\}}}|sTd}n|dshd|}nd|}t|||S)Nrrzcall%srzcall.%s)rrrrr)rArrBrCrrrr s       z_Call.__repr__cCs4g}|}|dur(|jr |||j}qtt|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)rrrrrr)rAZvalsrMrrr call_list s z_Call.call_list)rrNFT)rNNFT)rMrPrrNrr8rrrr9rrrrrBrCrrrrrrr&L s&  5  r&)rc Ksht|rt|}t|t}t|}d|i}|r8d|i}n |durDi}|rT|rTd|d<||t} t|rri}n8|r|rtdt } n"t |st } n|r|rt |st } | d|}|} |durd} | f||| |d |} t|trt| |} |rt| nt|| |||dur,|s,| |j|<|rV|sVd |vrVt||dd | d | _t|D]} t| rrq^zt|| } WntyYq^Yn0d| i}|rd| i}t| tst| || | |}|| j| <nn| }t|tr| j}t|| |}||d <t| rt }nt}|f|| | |d|}|| j| <t| ||dt|tr^t| | |q^| S)aICreate a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the `spec` object as their spec. Functions or methods being mocked will have their arguments checked to check that they are called with the correct signature. If `spec_set` is True then attempting to set attributes that don't exist on the spec object will raise an `AttributeError`. If a class is used as a spec then the return value of the mock (the instance of the class) will have the same spec. You can use a class as the spec for an instance object by passing `instance=True`. The returned mock will only be callable if instances of the mock are callable. `create_autospec` also takes arbitrary keyword arguments that are passed to the constructor of the created mock.rrNTrzJInstance can not be True when create_autospec is mocking an async functionrr)rrrrrvr)rKrwrr)rrrr)rJ)r[r1r$r.rhrr'Zisdatadescriptor RuntimeErrorr rXr r`rr6rirrLr~rrvrrr&r:rr5 _must_skiprrS)rrrKrrwrCis_typeZ is_async_funcrrrr5rrerrrJZ child_klassrrrr s                     rcCsxt|ts$|t|divrdS|j}|jD]H}|j|t}|turFq*t|tt frZdSt|t rl|SdSq*|S)z[ Return whether we should skip the first argument on spec's `entry` attribute. r]F) r$r1r&rr\r]r^rrVrWr6)rrrrArfrrrr s   rc@seZdZdddZdS)rFNcCs(||_||_||_||_||_||_dSr/)ridsrrrKr)rArrrrrrKrrrr8 s z_SpecState.__init__)FNNNFrrrrrr srcCs"t|trt|St|SdSr/)r$bytesioBytesIOStringIO) read_datarrr _to_stream s  r rcs&t}|dgfdd}fdd}fddfdd fd d }tdurd dl}ttt|jtt|ja|durt 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. Ncs(jjdurjjSdj|i|Sr) readlinesrvra_statehandlerr_readlines_side_effect s z)mock_open.._readlines_side_effectcs(jjdurjjSdj|i|Sr)readrvrarrr_read_side_effect s z$mock_open.._read_side_effectc?s(EdHdj|i|Vq dSr)readlinera)_iter_side_effectrrr_readline_side_effect s z(mock_open.._readline_side_effectc3s0jjdurjjVq dD] }|Vq dSr)rrv)linerrrr s   z$mock_open.._iter_side_effectcs jjdurjjStdSr)rrvrrrrr_next_side_effect s z$mock_open.._next_side_effectropen)rr)rrcs6td<jjdkr2d<dj_tS)Nrr)r rr}rra)rrrr rr reset_data s    zmock_open..reset_data)r  file_spec_iorYrr TextIOWrapperunionr rrrrvwriterrr r}rr)r5r Z _read_datarrrrrr)rrrrr rr 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. cKstfi|Sr/)r)rArCrrrr szPropertyMock._get_child_mockNcCs|Sr/r)rAr)Zobj_typerrrr szPropertyMock.__get__cCs ||dSr/r)rAr)rrrrr! szPropertyMock.__set__)N)rMrPrrNrrrrrrrr s rc Cspd|_t|D]\}zt||}Wnty6YqYn0t|tsDqt|j|trXq|j |urt |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&r:r$r r~r^rrr)r5rrrrrr% s      rc@s eZdZdZddZddZdS)rz8 Wraps an iterator in an asynchronous iterator. cCs&||_ttd}tj|_||jd<dS)Nrr+)iteratorr rr'ZCO_ITERABLE_COROUTINErr])rAr rrrrr8A s z_AsyncIterator.__init__cs(z t|jWStyYn0tdSr/)rr rrrrrrrG s   z_AsyncIterator.__anext__N)rMrPrrNr8rrrrrr= sr)F)F)NFNNN)FFNN)Nr)}__all__rrdrr'rr}builtinsrtypesrrrZ unittest.utilr functoolsrrrrtr rrr*r.r#r3r7r=rLrGrXr[r`rirdrrrrrrrMISSINGr ZDELETEDrrrrYrrrrrr r;r8rr;rr?rrPrRrSrrrrrrrrZmultipleZstopallrbZ magic_methodsZnumericsrrZinplacerightZ _non_defaultsrrr=Z_sync_async_magicsZ _async_magicsr>rrrrrrrrrrrrr rrrrr rrrrZr&rrrrr1rr6rr r rrrrrrrs0       1  h4 <   2 N        8+ :   N