gMdZddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z m Z m Z ddlmZddlmZmZddlmZGdd eZeeDchc]}|j1d r|c}Zd ZeZd Zd ZdZdZ dZ!dZ"dydZ#dZ$dZ%dZ&dZ'dydZ(dZ)dZ*dZ+Gdde,Z-Gdde,Z.e.Z/e/j`Z0e/jbZ2e/jfZ4hd Z5d!Z6Gd"d#e7Z8d$Z9Gd%d&e,Z:Gd'd(e,Z;Gd)d*e;Z<e=ee<Dchc]$}|j1d+r|j}d+&c}Z?Gd,d-e7Z@d.ZAGd/d0e;ZBGd1d2eBe<ZCd3ZDGd4d5e,ZEd6ZFe0dddddfdd7d8ZG dzd9ZHe0dddddfdd7d:ZIGd;dZLeGeI_,eJeI_MeHeI_NeLeI_Od?eI_Pd@ZQdAZRdBjdCeRjDZUdBjdDeRjDZVhdEZWdFZXdBjeQeReUeVgjDchc]}dG|z c}ZYhdHZZdIhZ[eZe[zZ\eYeWzZ]e]e\zZ^hdJZ_dKdLdMdNdOZ`eaeaeaeadPddddQdRd dPddS ZbdTZcdUZddVZedWZfecedeeefdXZgdYZhGdZd[e;ZiGd\d]eie<ZjGd^d_eiZkGd`daeieCZlGdbdce;Zm ejee jdZpee ZqGdddee;ZsGdfdgesekeCZtGdhdie,ZueuZvdjZwGdkdlexZyeydmZz d{dd7dnZ{doZ|Gdpdqe,Z}e~e{e~evjfZdadadrZd|dsZGdtdueCZdvZGdwdxZycc}wcc}wcc}w#er$rdZpYwxYw)})Mock MagicMockpatchsentinelDEFAULTANYcallcreate_autospec AsyncMock FILTER_DIRNonCallableMockNonCallableMagicMock mock_open PropertyMocksealN)iscoroutinefunction)CodeType ModuleType MethodType) safe_repr)wrapspartial)RLockceZdZdZy)InvalidSpecErrorz8Indicates that an invalid value was used as a mock spec.N__name__ __module__ __qualname____doc__4/opt/alt/python312/lib64/python3.12/unittest/mock.pyrr)sBr"r_Tct|rt|tsyt|dr t |d}t |xst j|S)NF__func__)_is_instance_mock isinstancer hasattrgetattrrinspect isawaitableobjs r# _is_async_objr/5sGji&@sJc:& s # ?w':':3'??r"c4t|ddr t|Sy)N__code__F)r*r)funcs r#_is_async_funcr3=stZ&"4((r"c4tt|tSN) issubclasstyper r-s r#r'r'Ds d3i 11r"cjt|txs"t|txrt|tSr5)r( BaseExceptionr7r6r-s r# _is_exceptionr:Js-3 & A3@*S-"@r"cVt|trt|dr |jS|SNmock)r( FunctionTypesr)r=r-s r# _extract_mockr?Qs%#}%'#v*>xx r"cvt|tr|s|j}d}nRt|ttfrt|trd}|j }nt|t s |j}|r t|d}n|} |tj|fS#t$rYywxYw#t$rYywxYw)z Given an arbitrary, possibly callable object, try to create a suitable signature object. Return a (reduced func, signature) tuple, or None. TN) r(r7__init__ classmethod staticmethodr&r>__call__AttributeErrorrr+ signature ValueError)r2 as_instanceeat_selfsig_funcs r#_get_signature_objectrKZs $k}} D; 5 6 dK (H}} m , ==D4&W&&x000   s$( BB, B)(B), B87B8Fct|||y\}fd}t|||t|_t|_y)Nc*j|i|yr5bind)selfargskwargssigs r#checksigz"_check_signature..checksig$!&!r")rK_copy_func_detailsr7_mock_check_sig __signature__)r2r= skipfirstinstancerTrSs @r#_check_signaturer[}sI h :C {ID#"tX&!)DJ"DJr"c `dD]} t||t||y#t$rY)wxYw)N)rr __text_signature__r __defaults____kwdefaults__)setattrr*rE)r2funcopy attributes r#rVrVs:   GYi(@ A     s ! --ct|tryt|tttfrt |j St|ddyy)NTrDF)r(r7rCrBr _callabler&r*r-s r#rdrdsD#t# k:>?&&sJ%1 r"c0t|ttfvSr5)r7listtupler-s r#_is_listrhs 9u %%r"ct|tst|ddduS|f|jzD]}|jj dyy)ztGiven an object, return True if the object is callable. For classes, return True if instances would be callable.rDNTF)r(r7r*__mro____dict__get)r.bases r#_instance_callablernsV c4 sJ-T99$ ==  Z ( 4% r"c t|t}t|||}||S|\} fd}t|||j}|j sd}||d}d|z} t | |||} t| | | S)Nc*j|i|yr5rN)rQrRrSs r#rTz _set_signature..checksigrUr"ra) _checksig_r=zYdef %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs))r(r7rKrVr isidentifierexec _setup_func) r=originalrZrYresultr2rTnamecontextsrcrarSs @r#_set_signaturerzs 8T*I "8Xy AF ~ ID#"tX&   D    %t4G $&* +C #wdmGs# Nr"c_fd}fd}fd}fd}fd}fd}fd} fd} d _d _d_t _t _t _j_j_ j_ |_ |_ |_ | _| _|_|_|_|__y) Nc(j|i|Sr5)assert_called_withrQrRr=s r#r}z'_setup_func..assert_called_with&t&&777r"c(j|i|Sr5) assert_calledr~s r#rz"_setup_func..assert_calleds!t!!42622r"c(j|i|Sr5)assert_not_calledr~s r#rz&_setup_func..assert_not_calleds%t%%t6v66r"c(j|i|Sr5)assert_called_oncer~s r#rz'_setup_func..assert_called_oncerr"c(j|i|Sr5)assert_called_once_withr~s r#rz,_setup_func..assert_called_once_withs+t++T.assert_has_callss$t$$d5f55r"c(j|i|Sr5)assert_any_callr~s r#rz$_setup_func..assert_any_calls#t##T4V44r"ct_t_jj}t |r|ur|jyyyr5) _CallList method_calls mock_calls reset_mock return_valuer')retrar=s r#rz_setup_func..reset_mocksL({&[ "" S !#+ NN +6 !r"Fr)r=called call_count call_argsrcall_args_listrrr side_effect_mock_childrenr}rrrrrrrrX_mock_delegate) rar=rSr}rrrrrrrs `` r#rtrtsGL8378=65GNGG&[G$;G"G,,G**G!00G!3G&=G#/G-G#G)G 1G!3GG!Dr"c tjj_d_d_t _fd}dD]}t|t||y)Nrc<tj||i|Sr5)r*r=)attrrQrRr=s r#wrapperz"_setup_async_mock..wrapper s 'wtyy$'888r")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=rrbs` r#_setup_async_mockrsV ++99DDDO$;D 9,  i)!<=,r"cd|ddz|k(S)N__%s__r!rws r# _is_magicrs d1Rj D ((r"c"eZdZdZdZdZdZy)_SentinelObjectz!A unique, named, sentinel object.c||_yr5rrPrws r#rAz_SentinelObject.__init__"s  r"c d|jzSNz sentinel.%srrPs r#__repr__z_SentinelObject.__repr__%tyy((r"c d|jzSrrrs r# __reduce__z_SentinelObject.__reduce__(rr"N)rrrr rArrr!r"r#rr s'))r"rc"eZdZdZdZdZdZy) _SentinelzAAccess attributes to return a named object, usable as a sentinel.ci|_yr5) _sentinelsrs r#rAz_Sentinel.__init__.s r"cb|dk(rt|jj|t|S)N __bases__)rEr setdefaultrrs r# __getattr__z_Sentinel.__getattr__1s, ;  ))$0EFFr"cy)Nrr!rs r#rz_Sentinel.__reduce__7sr"N)rrrr rArrr!r"r#rr,sKG r"r> _mock_namer _mock_parentr_mock_new_name_mock_new_parent_mock_side_effect_mock_return_valuecftj|d|z}||fd}||fd}t||S)N_mock_cN|j}| t||St||Sr5)rr*)rPrw _the_namerSs r#_getz"_delegating_property.._getLs,!! ;4+ +sD!!r"cZ|j}|||j|<yt|||yr5)rrkr`)rPvaluerwrrSs r#_setz"_delegating_property.._setQs,!! ;',DMM) $ Cu %r")_allowed_namesaddproperty)rwrrrs r#_delegating_propertyrIs>t4I " $y& D$ r"ceZdZdZdZy)rct|tstj||St|}t|}||kDryt d||z dzD]}||||z}||k(syy)NFrT)r(rf __contains__lenrange)rPr len_valuelen_selfisub_lists r#rz_CallList.__contains__^sw%&$$T51 1J t9 x q(Y.23AAa k*H5 4r"c>tjt|Sr5)pprintpformatrfrs r#rz_CallList.__repr__ls~~d4j))r"N)rrrrrr!r"r#rr\s  *r"rct|}t|sy|js$|js|j |j y|}|||ury|j }||r||_||_|r||_||_y)NFT)r?r'rrrr)parentrrwnew_name_parents r#_check_and_set_parentrps % E U #   U11    '    +G   e **  !'' # r"ceZdZdZdZy) _MockIterc$t||_yr5)iterr.)rPr.s r#rAz_MockIter.__init__s 9r"c,t|jSr5)nextr.rs r#__next__z_MockIter.__next__sDHH~r"N)rrrrArr!r"r#rrs r"rceZdZeZdZdZy)BaseNcyr5r!rPrQrRs r#rAz Base.__init__s r")rrrrrrrAr!r"r#rrs  r"rceZdZdZeZ d,dZ d,dZdZd-dZ d.dZ d Z d Z d Z ee e e Zed Zed ZedZedZedZedZdZdZeeeZd/ddddedefdZdZdZdZdZdZ dZ!dZ"dZ#d0d Z$d!Z%d"Z&d#Z'd$Z(d%Z)d&Z*d'Z+d-d(Z,d)Z-d*Z.d1d+Z/y)2r z A non-callable version of `Mock`NFc  |f} t|ts|xs|}|t|rt|f} t|j| d|j i}t t|j|}|S)Nr ) r6AsyncMockMixinr/r7rr _safe_superr __new__)clsspecrrwspec_setr _spec_state _new_name _new_parent_spec_as_instance _eat_selfunsaferRbasesspec_argnewrZs r#rzNonCallableMock.__new__sm#~.'4H# h(?'-3<<CKK(@A4<d..6&& D'C!$D  r"cj|j||j_y||_t||ddy)Nr%)rrrr)rPrs r#__set_return_valuez"NonCallableMock.__set_return_value*s2    */4D   ,&+D # !$tT :r"z1The value to be returned when the mock is called.cH|j t|S|jSr5)rr7rs r# __class__zNonCallableMock.__class__6s$    #: r"rrrrrc|j}| |jS|j}|8t|s-t |t st |st |}||_|Sr5)rrrcallabler(rr:)rP delegatedsfs r#__get_side_effectz!NonCallableMock.__get_side_effectCs\''  )) )  " " N8B<"2y1-:K2B$&I ! r"cTt|}|j}|||_y||_yr5) _try_iterrrr)rPrr/s r#__set_side_effectz!NonCallableMock.__set_side_effectNs-% ''  %*D "$)I !r"rrrrc|g}t||vry|jt|d|_d|_d|_t |_t |_t |_|r t|_ |rd|_ |jjD]/}t|ts|t ur|j#|||1|j}t%|r||ur|j#|yyy)z-Restore the mock object to its initial state.NFrr5)idr!rrrrrrrrrrrvaluesr( _SpecState_deletedrr')rPvisitedrrchildrs r#rzNonCallableMock.reset_mockYs ?G d8w  r$x  #+'k%K &-D # %)D "((//1E%,0A   W<[  Y2 %% S !co NN7 #'6 !r"c t|jdD]H\}}|jd}|j}|}|D]}t ||}t |||Jy)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)c*|djdS)Nr.)count)entrys r#z0NonCallableMock.configure_mock..sq1Dr")keyr?N)sorteditemssplitpopr*r`)rPrRargvalrQfinalr.rAs r#rzNonCallableMock.configure_mockyshv||~$E FHC 99S>DHHJECc5) C $Fr"c |dvr t||j$||jvs|tvr$td|zt|r t||jsD|jr||jvr*|j ds|t vrt|d|dtj5|jj|}|tur t||Jd}|jt|j|}|j|||||}||j|<nat|t rQ t#|j$|j&|j(|j*|j,}||j|<ddd|S#t.$r6|j0dxs|}t/d|d |d |d |j$d wxYw#1swYSxYw) 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.)rrwrrrrCannot autospec attr from target , as it has already been mocked out. [target=, attr=r)rEr _all_magicsrr startswith_ATTRIB_DENY_LISTr _lockrrlr:rr*r'r(r9r rrrZrrwrrk)rPrwrvr target_names r#rzNonCallableMock.__getattr__s  4 4 & &    +4---1D$%F%MNN t_ & &  $*<*<DL^L^@^OPTX\mTm$h''+h.KMNN " "((,,T2F!$T**##/$D$4$4d;E--d%4 $..4##D)FJ/ D, V__foo v{{F.4##D);#> (D"&-- "="EK*/x}&/*##'('&++CDDD/#> s&6B GAFG?GGG(c||jg}|j}|}d}|dgk(rd}|B|}|j|j|zd}|jdk(rd}|j}|Btt |}|j xsd}t |dkDr |ddvr|dz }||d<dj|S)Nr?r%rr=r)r%z().r)rrr!rfreversedrrjoin)rP _name_listrlastdot_firsts r#_extract_mock_namez"NonCallableMock._extract_mock_names))* '' $ C!D   g44s: ;C%%-..G!(:./ *F z?Q !}M1#  1 wwz""r"c|j}d}|dvrd|z}d}|j)d}|jrd}||jjz}dt |j||dt |dS) Nr)r=zmock.z name=%rz spec=%rz spec_set=%r)rarrrr7r7)rPrw name_string spec_strings r#rzNonCallableMock.__repr__s&&( ( ($t+K    '$K~~, %(8(8(A(AAK J     tH   r"ctstj|S|jxsg}t t |}t |j}|jjDcgc]\}}|tur|}}}|Dcgc]}|jdr|}}|Dcgc] }|jdr t|r|"}}tt||z|z|zScc}}wcc}wcc}w)z8Filter the output of `dir(mock)` to only useful members.r$)r object__dir__rr r7rfrkrrEr:rVrrDset)rPextras from_type from_dictm_namem_valuefrom_child_mockses r#rhzNonCallableMock.__dir__s>>$' '##)rT O ' *.*=*=*C*C*E(*Evwh& *E (!*C 1c1BQ C )# 1c1Bq\ #c&9,y8;KKLMM(D#s2C2 C8$C8.%C=c`|tvrtj||Sjr6j*|jvr|j vrt d|z|tvrd|z}t ||tvrj|jvrt d|zt|s)tt|t|||fd}n^t|d|tt|||j|<n*|dk(r|_yt|||r|j|<j r/t#|s#j%d|}t d|t'|t(r|j |<ytj||S)Nz!Mock object has no attribute '%s'z.Attempting to set unsupported magic method %r.cg|i|Sr5r!)rQkwrurPs r#rBz-NonCallableMock.__setattr__..sHT,GD,GB,Gr"r,r?z Cannot set )rrg __setattr__rrrkrE_unsupported_magicsrUr'r`r7 _get_methodrrrrr)rar(r)rPrwrmsg mock_namerus` @r#rtzNonCallableMock.__setattr__s > !%%dD%8 8nn!3!3!? ** *  % !Dt!KL L ( (BTIC % % [ !!-$d>P>P2P$%H4%OPP$U+T D+dE*BC G&dE4>T D%0,1##D) [ $D  $T5$=,1##D)   WT4%82245Qtf=I ;yk!:; ; e\ *"'DMM$  !!$e44r"c|tvr;|t|jvr$tt||||jvry|jj |t }||jvr tt|j|n|tur t||t ur |j|=t|j|<yr5) rUr7rkdelattrrrl_missingrr __delattr__r:rE)rPrwr.s r#r|zNonCallableMock.__delattr__+s ; 44:+>+>#> DJ %4==(!!%%dH5 4==  . : :4 @ H_ & & h ##D)$,D!r"c<|jxsd}t|||Sr<)r_format_call_signaturerPrQrRrws r#_format_mock_call_signaturez+NonCallableMock._format_mock_call_signature=s(&%dD&99r"cpd}|j||}|j}|j|}||||fzS)Nz0expected %s not found. Expected: %s Actual: %s)rr)rPrQrRactionmessageexpected_stringr actual_strings r#_format_mock_failure_messagez,NonCallableMock._format_mock_failure_messageBsFF::4HNN 888)D &/=AAAr"c |s |jSd}|jddjd}|j}|D]K}|j |}|t |t r|St|}|j}|j}M|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. Nr%rr?)rreplacerFrrlr(r9r?)rPrwrSnameschildrenr<s r#_get_call_signature_from_namez-NonCallableMock._get_call_signature_from_nameJs'' ' T2&,,S1&&DLL&E} 5* = &e, //++ r"cvt|tr#t|dkDr|j|d}n |j}|Pt|dk(rd}|\}}n|\}}} |j |i|}t ||j|jS|S#t$r}|jdcYd}~Sd}~wwxYw)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(rgrrrrOrrQrR TypeErrorwith_traceback)rP_callrSrwrQrR bound_callrps r# _call_matcherzNonCallableMock._call_matcherks eU #E Q44U1X>C&&C ?5zQ$ f%*"dF .%SXXt6v6 D*//:3D3DEEL .''-- .s2B B8B3-B83B8c|jdk7r._error_messages33D&ACJr"Ttwo)rrrr_Callr( Exception)rPrQrRexpectedactual error_messagercauses``` r#r}z"NonCallableMock.assert_called_withs >> !77fEH"F)M / / %%eT6N&EF##DNN3 X  *8Y ?HTE !12 = r"c|jdk(sz3NonCallableMock.assert_has_calls..FAZ9-EaNc3@K|]}j|ywr5rrcrPs r#rz3NonCallableMock.assert_has_calls..sM_d003_zCalls not found.z+Error processing expected calls. Errors: {} Expected: z Actual)prefixr?r=z does not contain all of z in its call list, found z instead)rrrrformatr(rrrrstriprfremoverGr!rrg) rPcalls any_orderrrr all_callsproblemrp not_foundkalls ` r#rz NonCallableMock.assert_has_callss~4995aD&&q)59FFMMT__MM y(=0G ,-3V-5$7-5*4Ay)AAt$K-5$7.8%i !!*5!1 2''z':AA#FGI  O  D '  &  &*oo&?&?&+I&6 C   7:$7 '  & 'sD+D#D((EEc"|jt||fd}t|tr|nd}|jDcgc]}|j|}}|s |t |vr!|j ||}td|z|ycc}w)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.TrNz%s call not found)rrr(rr _AnyComparerrrrPrQrRrrrrrs r#rzNonCallableMock.assert_any_calls %%eT6N&EF&x;151D1DE1DA$$$Q'1DE HL$88">>tVLO #o5 9FB c J|jr,d|vrd|dnd}|j|z}t||jd}||jdvr t di|St |}t|tr|tvrt }nt|tr0|tvs|jr||jvrt}nTt }nMt|ts.t|trt}n&t|trt }n|j"d}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).rwr?r%rrrr!)rrarErlrkr r7r6r_async_method_magicsr_all_sync_magicsr CallableMixinr r rrj)rPrsrbrxr_typeklasss r#r'zNonCallableMock._get_child_mocks   ,2bL!BvJ<(dI//1I=I + +FF;'  n5 5?r? "T  eY 'I9M,ME ~ .--&&98J8J+J!!E=1%!56!E?3MM!$E{r{r"cT|jsyd|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)rPrs r#rzNonCallableMock._calls_repr's-F82i89;;r") NNNNNNrNFNFF)FFr5)r)Calls)0rrrr rrXrrArrr"_NonCallableMock__get_return_value"_NonCallableMock__set_return_value"_NonCallableMock__return_value_docrrr,rrrrrr!_NonCallableMock__get_side_effect!_NonCallableMock__set_side_effectrboolrrrrarrhrtr|rrrrrrrr}rrrr'rr!r"r#r r s`* GE=AEIBEI, 8*Z  #L  !,!;!;c!AN!R&66K-%r"c|j}|Bt|r|t|st|}t|r |||i|}|tur|S|j tur |j S|jr(|jj tur |j S|j|j|i|S|j Sr5) rr:rdrrrrrr)rPrQrReffectrvs r#rz CallableMixin._execute_mock_calls!!  V$ v&f ( L00W$  " "' 1$$ $   4#6#6#C#C7#R$$ $    '#4##T4V4 4   r") rrrrrArWrDrrrr!r"r#rr[s8 d$d!RT ' 08,7\!r"rceZdZdZy)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. * `unsafe`: By default, accessing any attribute whose name starts with *assert*, *assret*, *asert*, *aseert*, or *assrt* raises an AttributeError. Additionally, an AttributeError is raised when accessing attributes that match the name of an assertion method without the prefix `assert_`, e.g. accessing `called_once` instead of `assert_called_once`. Passing `unsafe=True` will allow access to these attributes. * `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#rrs7r"rc:d}|D]}||vst|dy)N) autospect auto_specset_specz5 might be a typo; use unsafe=True if this is intended) RuntimeError)kwargs_to_checktypostypos r#_check_spec_arg_typosrs1 2E ? "(OP r"ceZdZdZgZdddZdZdZdZe jdZ d Z d Z d Zd Zd ZdZdZy)_patchNFrc ~| |tur td| td| s t| t|rt d|d|dt|rt d|d|d||_||_||_||_||_ ||_ d|_ ||_ ||_ | |_g|_d|_y)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)rrGrr'rgetterrbr new_callablercreate has_localrautospecrRadditional_patchers is_started) rPrrbrrrrrrrRrs r#rAz_patch.__init__s  #'! B# G !& ) T ""#I=166:XQ@A A X &"#I=1AAI AOP P "(       #% r"c ft|j|j|j|j|j |j |j|j|j }|j|_ |jDcgc]}|jc}|_ |Scc}wr5) rrrbrrrrrrrRattribute_namercopy)rPpatcherps r#rz _patch.copy7s KK499 KK MM4,,dkk  "&!4!4"66' 6AFFH6' #' s B.ct|tr|j|Stj|r|j |S|j |Sr5r(r7decorate_classr+rdecorate_async_callabledecorate_callable)rPr2s r#rDz_patch.__call__DsM dD !&&t, ,  & &t ,//5 5%%d++r"ct|D]^}|jtjs#t ||}t |ds<|j }t||||`|SNrD)r rVr TEST_PREFIXr*r)rr`)rPrr attr_valuers r#r z_patch.decorate_classLsaJD??5#4#45 -J:z2iikG E4!4 5 r"c#RKg}tj5}|jD]U}|j|}|j|j |2|j tusE|j|W|t|z }||fdddy#1swYyxYwwr5) contextlib ExitStack patchings enter_contextrupdaterrr!rg)rPpatchedrQkeywargs extra_args exit_stackpatchingrHs r#decoration_helperz_patch.decoration_helperZs  ! ! #z#-- ..x8**6OOC(\\W,%%c* . E*% %D" "$ # #s#B'AB+'B B'B$ B'ctdrjjStfdg_S)Nrclj||5\}}|i|cdddS#1swYyxYwr5rrQrnewargs newkeywargsr2rrPs r#rz)_patch.decorate_callable..patchedos=''(,(025Kg{W4 4222s *3r)rr!rrPr2rs``@r#r z_patch.decorate_callableisK 4 % NN ! !$ 'K t 5  5 "Fr"ctdrjjStfdg_S)NrcKj||5\}}|i|d{cdddS7 #1swYyxYwwr5rrs r#rz/_patch.decorate_async_callable..patchedsN''(,(025Kg{!7:k::22;22s#A646 A6?Ar"r#s``@r#r z_patch.decorate_async_callablezsK 4 % NN ! !$ 'K t ;  ; "Fr"cH|j}|j}t}d} |j|}d}|tvrt|trd|_ |js|turt |d|||fS#tt f$rt ||t}YiwxYw)NFTz does not have the attribute ) rrbrrkrEKeyErrorr* _builtinsr(rr)rPtargetrwrulocals r# get_originalz_patch.get_originals~~ t,HE 9 FJ!?DK{{x72 7=tD ) 6vtW5H 6sA>> B! B!c J|jr td|j|j|j}}}|j |j }}|j}|j|_ |durd}|durd}|durd}| | td|||dvr td|j\}}|turl|id} |dur |}|dur|}d}n| |dur |}d}n|dur|}||%|tur tdt|trd} ||} nb|t|rt } nN||D|} ||} t#| rd | v} n t%|  } t| rt } n| rt&} n t(} nt(} i} ||| d <||| d <t| tr+t+| t,r|j.r|j.| d <| j1|| di| }| rFt3|r:|} ||} t#| st5| st&} | j7d | d|d d| |_n||tur td|tur tdt;|}|dur|}t3|jr)t=d|j.d|jd|dt3|rMt?|jd|j}t=d|j.d|d|jd|d tA|f||j.d|}n |r td|}||_!||_"tGjH|_%d|_ tM|j|j.||jNui}|jtur|||jN<|jPD]A}|jJjS|}|jtus1|j1|C|S|S#|jTtWjXsYyxYw)zPerform the patch.zPatch is already startedFNzCan't specify spec and autospec)TNz6Can't provide explicit spec_set *and* spec or autospecTz!Can't use 'spec' with create=TruerDrrrwr%r&zBautospec creates the mock for you. Can't specify autospec and new.z%Can't use 'autospec' with create=TruerQz: as the patch target has already been mocked out. [target=rTrrrRrS)r_namez.Can't pass kwargs to a mock we aren't creatingr!)-rrrrrrrRrrr)rr+rr(r7r/r rhr.r rr6r rbrr'rnrGrrrr*r temp_originalis_localrr _exit_stackr`rrr__exit__sysexc_info)rPrrrrrRrrur*inheritKlass this_spec not_callable_kwargsrYnew_attrrrrHs r# __enter__z_patch.__enter__s ??9: :"hh 4==8T==$++&(( kkm  5=D u H u H   4=> >  !5 L (TU U++-% '>h.Gt|t#'HD!t##HDT!#8#7w&#$GHHh-"G'$-"9!!X%9 ' (II&#-Y#>L'/ ':#:L +%E!0E%E!G"&#&. #5$'5/2t~~"&.. NN6 ""'"C,S1! ' (I +&y10E F##($4SD$4+2$4  !'!(7" GHHH~H4# -&+DNN+=>#{{oWXLCDD!*%dkk:t{{K &+DNN+=]"o&#{{oWXLCDD "(BX(,B:@BC LM M% %//1  DKK :"". 88w&7:Jt223 $ 8 8H**88BC||w."))#.!9"!J  4==#,,.12sB O<%O<:O<<$P"c|jsy|jr>|jtur,t |j |j |jnt|j |j |jsYt|j |j r|j dvr+t |j |j |j|`|`|`|j}|` d|_|j|S)zUndo the patch.N)r rr^__annotations__r_F) rr/r.rr`r)rbrzrr)r0r1)rPr3rs r#r1z_patch.__exit__=s  ==T//w> DKK1C1C D DKK 0;; T^^(L+== T^^T5G5GH   M K%%  "z""H--r"c\|j}|jj||Sz-Activate a patch, returning any created mock.)r:_active_patchesr!rPrvs r#startz _patch.startVs'! ##D) r"c~ |jj||jdddS#t$rYywxYwzStop an active patch.N)r?rrGr1rs r#stopz _patch.stop]sD   ' ' - }}T4..   s 0 <<)rrrrr?rArrDr rcontextmanagerrr r r+r:r1rArDr!r"r#rr sgNOAF# L ,  # #""0Xt.2/r"rc |jdd\}}t t j ||fS#tttf$rtd|wxYw)Nr?rz,Need a valid target to patch. You supplied: )rsplitrrGrErpkgutil resolve_name)r)rbs r# _get_targetrJisjG"MM#q1  7'' 0) ;; z> 2G:6* EG GGs 3#Arc vtturtdfd} 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 strcSr5r!r)sr#rBz_patch_object..sVr"r)r7strrr) r)rbrrrrrrrrRrs ` r# _patch_objectrOrsS$ F|sjK L  F  3f(L& r"c ~tturttj}nfd}|s t dt |j}|d\} } t|| | |||||i } | | _ |ddD]:\} } t|| | |||||i } | | _ | jj| <| 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. cSr5r!rMsr#rBz!_patch_multiple..sr"z=Must supply at least one keyword argument with patch.multiplerrN) r7rNrrHrIrGrfrErrrr!) r)rrrrrrRrrErbrr this_patchers ` r#_patch_multiplerSs, F|s--v6  K    E1XNIs 3fh,G'G) 3 IsD&( lB '0 ###**<8 $ Nr"c Ht|\} } t| | |||||||| 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)rJr) r)rrrrrrrrRrrbs r#rrs7V$F+FI  3f(L& r"cTeZdZdZddZdZdZdZdZdZ dZ d Z d Z d Z d Zy ) _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. c ||_t||_|jj|||_d|_yr5)in_dictdictr8rclear _original)rPrXr8rZrRs r#rAz_patch_dict.__init__/s4 6l  6" r"ct|tr|j|Stj|r|j |S|j |Sr5r)rPfs r#rDz_patch_dict.__call__8sM a &&q) )  & &q )//2 2%%a((r"c2tfd}|S)Ncj |i|jS#jwxYwr5rV _unpatch_dictrQrsr]rPs r#_innerz-_patch_dict.decorate_callable.._innerAs8     %$~"~""$""$s+=rrPr]rcs`` r#r z_patch_dict.decorate_callable@ q %  % r"c2tfd}|S)NcKj |i|d{jS7#jwxYwwr5r`rbs r#rcz3_patch_dict.decorate_async_callable.._innerMsD     %^^+""$,""$s%A  757A 7A  A rdres`` r#r z#_patch_dict.decorate_async_callableLrfr"ct|D]{}t||}|jtjs/t |ds>G - NN8 $ -'}   -s7AAc<|j|jy)zUnpatch the dict.F)r[ra)rPrQs r#r1z_patch_dict.__exit__s >> %    r"cd|j}tjj||Sr>)r:rr?r!r@s r#rAz_patch_dict.starts'!%%d+ r"c tjj||j dddS#t$rYywxYwrC)rr?rrGr1rs r#rDz_patch_dict.stopsD   " " ) )$ / }}T4..   s4 AAN)r!F)rrrr rArDr r r r:rVrar1rArDr!r"r#rVrVs>8)   +8 -/r"rVcn |jy#t$rt|}|D]}||=YywxYwr5)rZrErf)rXkeysrCs r#rnrns9  G}C s 44c`ttjD]}|jy)z7Stop all active patches. LIFO to unroll nested patches.N)r[rr?rD)rs r#_patch_stopallrvs &001 2r"testzlt 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 zDadd sub mul matmul truediv floordiv mod lshift rshift and xor or pow c#&K|] }d|z yw)zi%sNr!rns r#rrs7&6519&6c#&K|] }d|z yw)zr%sNr!rzs r#rrs5$4q$4r|>rh__get____set__r __delete__ __format__r __missing__ __getstate__ __reversed__ __setstate__ __getformat__ __reduce_ex____getnewargs____subclasses____getinitargs____getnewargs_ex__c fd}||_|S)z:Turns a callable object (like a mock) into a real functionc|g|i|Sr5r!)rPrQrsr2s r#methodz_get_method..methodsD&4&2&&r")r)rwr2rs ` r#rvrvs'FO Mr"r> __aexit__ __anext__ __aenter__ __aiter__>__del__rrAr __prepare__rt__instancecheck____subclasscheck__c,tj|Sr5)rg__hash__rs r#rBrBs V__T2r"c,tj|Sr5)rg__str__rs r#rBrBs FNN40r"c,tj|Sr5)rg __sizeof__rs r#rBrBsv006r"cjt|jd|jdt|S)N/)r7rrar7rs r#rBrBs3$t*"5"5!6a8O8O8Q7RRSTVW[T\S]^r")rrr __fspath__ry?g?) __lt____gt____le____ge____int__r__len__r1 __complex__ __float____bool__ __index__rcfd}|S)NcZjj}|tur|S|urytSNT)__eq__rrNotImplemented)otherret_valrPs r#rz_get_eq..__eq__s/++00 ' !N 5=r"r!)rPrs` r#_get_eqrs Mr"cfd}|S)Nc^jjturtS|urytSNF)__ne__rrr)rrPs r#rz_get_ne..__ne__#s* ;; ) ) 8N 5=r"r!)rPrs` r#_get_ner"s Mr"cfd}|S)Ncljj}|tur tgSt|Sr5)__iter__rrrrrPs r#rz_get_iter..__iter__,s/--22 g 8OG}r"r!)rPrs` r# _get_iterr+s Or"cfd}|S)Ncjj}|turtt gStt |Sr5)rrr_AsyncIteratorrrs r#rz"_get_async_iter..__aiter__6s8..33 g !$r(+ +d7m,,r"r!)rPrs` r#_get_async_iterr5s- r")rrrrctj|t}|tur||_ytj|}|||}||_yt j|}||||_yyr5)_return_valuesrlrr_calculate_return_value_side_effect_methodsr)r=rrwfixedreturn_calculatorr side_effectors r#_set_return_valuerFs{   tW -E G#/33D9$(. *(,,T2M *40!r"ceZdZdZdZy) MagicMixinc|jtt|j|i||jyr5)_mock_set_magicsrrrA)rPrQrss r#rAzMagicMixin.__init__Ys6 . J%..;; r"c zttz}|}t|ddU|j|j}t }||z }|D]&}|t |jvst||(|t t |jz }t |}|D]}t||t||y)Nr) _magicsrr* intersectionrrir7rkrzr` MagicProxy)rP orig_magics these_magics remove_magicsrArs r#rzMagicMixin._mock_set_magics_s 44 " 4$ / ;&33D4F4FGLEM',6M&DJ///D%(' $c$t**=*=&>> T !E E5*UD"9 :"r"N)rrrrArr!r"r#rrXs  ;r"rceZdZdZddZy)r z-A version of `MagicMock` that isn't callable.cH|j|||jyrrrrs r#rz"NonCallableMagicMock.mock_add_specy D(+ r"Nr)rrrr rr!r"r#r r ws 7 r"r c eZdZy)AsyncMagicMixinN)rrrr!r"r#rrsr"rc6eZdZdZddZdddeffdZxZS)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`. FcH|j|||jyrrrs r#rzMagicMock.mock_add_specrr")rrc|r#|jrt|jrd}tj|d|i|y)NFr)rrsuperr)rPrrQrRr,s r#rzMagicMock.reset_mocks< $//* !LDF|FvFr"r)rrrr rrr __classcell__r,s@r#rrs&  9> G G Gr"rc eZdZdZdZddZy)rc ||_||_yr5rwr)rPrwrs r#rAzMagicProxy.__init__s  r"c|j}|j}|j|||}t|||t ||||S)N)rwrr)rwrr'r`r)rPrArms r# create_mockzMagicProxy.create_mocksM   " "/5 # 7q!&!U+r"Nc"|jSr5)r)rPr.rs r#r~zMagicProxy.__get__s!!r"r5)rrrrArr~r!r"r#rrs"r"rceZdZedZedZedZfdZdZdZ dZ dZ d Z d Z dd Zd Zfd ZxZS)rrrrctj|i|tjj|j d<d|j d<d|j d<t |j d<tr7tt}t|j d<t|j d<ntt}tjtjztjz|_d|_d |_d|_d|_||j d <d |j d <t)|j d <i|j d<d|j d<y)Nrr_mock_await_count_mock_await_args_mock_await_args_listrrr)rQrRr1r rr^r_r<)rrArrrrkr _CODE_SIGr _CODE_ATTRSrr+ CO_COROUTINE CO_VARARGSCO_VARKEYWORDSco_flags co_argcount co_varnamesco_posonlyargcountco_kwonlyargcountrg)rPrQrR code_mockr,s r#rAzAsyncMockMixin.__init__s6$)&)*1););)I)I o&-. )*,0 ()1: -. '=I08I  } -4=I  0 1':I     !$$ %  !"  2 '( $&' #$- j!$/ j!(- n%*, &'+/ '(r"cKt||fd}|xjdz c_||_|jj ||j }|_t |r|t|s t|}t |r&|t|r||i|d{}n||i|}|tur|S|jtur |jS|jAt|jr|j|i|d{S|j|i|S|jS#t$rtwxYw777w)NTrr)rrrrr!rr:rdr StopIterationStopAsyncIterationrrrrr)rPrQrRrrrvs r#rz!AsyncMockMixin._execute_mock_callsTtVn$/ A ##E*!!  V$ v&-!&\F !( L$V,%t6v6600W$  " "' 1$$ $    '"4#3#34-T--t>v>>>#4##T4V4 4   -%--,-7?s=A-E0 D-;#EEA+E E "E-D==EEc`|jdk(rd|jxsdd}t|y)zA Assert that the mock was awaited at least once. r Expected r=z to have been awaited.Nrrrrs r#rzAsyncMockMixin.assert_awaited s;   q doo788NOC % % !r"cz|jdk(s,d|jxsdd|jd}t|y)z@ Assert that the mock was awaited exactly once. rrr=$ to have been awaited once. Awaited rNrrs r#rz"AsyncMockMixin.assert_awaited_once sM1$t8&9:#//09C % %%r"c8j!j}td|dfd}jt fd}jj}||k7r%t |t r|nd}t||y)zN Assert that the last await was with the specified arguments. NzExpected await: z Not awaitedc0jd}|S)Nawait)rrrs r#rz:AsyncMockMixin.assert_awaited_with.._error_message( s33D&3QCJr"Tr)rrrrrr(r)rPrQrRrrrrs``` r#rz"AsyncMockMixin.assert_awaited_with s ?? "77fEH #3H:]!KL L %%eT6N&EF##DOO4 X  *8Y ?HTE !12 = r"c|jdk(s,d|jxsdd|jd}t||j|i|S)zi Assert that the mock was awaited exactly once and with the specified arguments. rrr=rr)rrrrrs r#rz'AsyncMockMixin.assert_awaited_once_with2 s` 1$t8&9:#//09C % %'t''888r"c"|jt||fd}t|tr|nd}|jDcgc]}|j|}}|s |t |vr!|j ||}td|z|ycc}w)zU Assert the mock has ever been awaited with the specified arguments. TrNz%s await not found)rrr(rrrrrrs r#rzAsyncMockMixin.assert_any_await= s%%eT6N&EF&x;151E1EF1EA$$$Q'1EF HL$88">>tVLO $6 9Grc @|Dcgc]}j|}}td|Dd}tfdjD}|sb||vr]|d}n1dj |Dcgc]}t |t r|ndc}}t|dt|dj|yt|}g} |D]} |j| | rtt| d|ycc}wcc}w#t$r| j| YXwxYw) 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`. c3BK|]}t|ts|ywr5rrs r#rz3AsyncMockMixin.assert_has_awaits..W rrNc3@K|]}j|ywr5rrs r#rz3AsyncMockMixin.assert_has_awaits..X sS>Rt11!4>RrzAwaits not found.z,Error processing expected awaits. Errors: {}rz Actual: z not all found in await list) rrrrrr(rrrfrrGr!rg) rPrrrrr all_awaitsrrprrs ` r#rz AsyncMockMixin.assert_has_awaitsJ s\4995aD&&q)59FFMSd>R>RSS z)=1G ,-3V-5$7-5*4Ay)AAt$K-5$7.8%i !!*5!1 23#3346  *%  D '!!$'  49)4DF  7:$7 '  & 'sC6+C;DDDcz|jdk7r,d|jxsdd|jd}t|y)z9 Assert that the mock was never awaited. rrr=z# to not have been awaited. Awaited rNrrs r#rz!AsyncMockMixin.assert_not_awaitedv sM   q t8&9:#//09C % % !r"cttj|i|d|_d|_t |_y)z0 See :func:`.Mock.reset_mock()` rN)rrrrrr)rPrQrRr,s r#rzAsyncMockMixin.reset_mock s5 D+F+({r"r)rrrrrrrrArrrrrrrrrrrs@r#rrs\&}5K%l3J*+<=O0B&!P&&>$ 9 *X&++r"rceZdZdZy)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 s'r"r c"eZdZdZdZdZdZy)_ANYz2A helper object that compares equal to everything.cyrr!rPrs r#rz _ANY.__eq__ sr"cyrr!rs r#rz _ANY.__ne__ sr"cy)Nzr!rs r#rz _ANY.__repr__ sr"N)rrrr rrrr!r"r#r r  s8r"r c d|z}d}dj|Dcgc] }t|c}}dj|jDcgc] \}}|d|c}}} |r|}| r |r|dz }|| z }||zScc}wcc}}w)Nz%s(%%s)rz, =)r\reprrE) rwrQrRrformatted_argsrH args_stringrCr kwargs_strings r#r~r~ s$GN))$7$3T#Y$78KII171?:33M$  d "N-' ^ ##8s A>B ceZdZdZ ddZ ddZdZejZdZ dZ dZ d Z e d Ze d Zd Zd Zy)ra 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. Ncnd}i}t|}|dk(r|\}}}nh|dk(r2|\} } t| tr| }t| tr| }n9| }n6| | }}n1|dk(r,|\}t|tr|}nt|tr|}n|}|rtj |||fStj ||||fS)Nr!rr)rr(rNrgr) rrrwrr from_kallrQrR_lenfirstseconds r#rz _Call.__new__ s5z 19!& D$ QY!ME6%%fe,!D#F$ff QYFE%%E5) ==tVn5 5}}S4v"677r"c.||_||_||_yr5)rr_mock_from_kall)rPrrwrrrs r#rAz_Call.__init__ s"(r"c" t|}d}t|dk(r|\}}n|\}}}t|ddr't|ddr|j|jk7ryd}|dk(rdi}}n|dk(r|\}}}nv|dk(r5|\} t | t r| }i}nXt | tr| }di}}nAd}| }n<|dk(r6|\} } t | tr| }t | t r| i}}n d| }}n| | }}ny|r||k7ry||f||fk(S#t$r tcYSwxYw) NrrrFrr!rr)rrrr*rr(rgrN) rPr len_other self_name self_args self_kwargs other_name other_args other_kwargsrrrs r#rz _Call.__eq__ sV "E I t9>%) "I{04 -Iy+ D.$ /GE>SW4X%%););; >')2 J !^38 0J L !^FE%'" ! E3'" +-rL  $ !^!ME6%%" fe,/5r J/16 J+0&L  y0L)i-EEE_ "! ! "s C<<D Dc|jtd||fdS|jdz}t|j||f||S)Nrr%rrrrrs r#rDz_Call.__call__H sH ?? ""dF+$7 7%dootV44MMr"cr|j t|dS|jd|}t||dS)NF)rwrr?)rwrrr))rPrrws r#rz_Call.__getattr__P s6 ?? "de4 4//40$tu==r"c^|tjvrttj||Sr5)rgrkrE__getattribute__)rPrs r#r,z_Call.__getattribute__W s' 5>> ! %%dD11r"cDt|dk(r |\}}||fS|\}}}||fS)Nr)rrs r#_get_call_argumentsz_Call._get_call_arguments] s: t9>LD&V|"& D$V|r"c(|jdSNrr.rs r#rQz _Call.argse '')!,,r"c(|jdS)Nrr1rs r#rRz _Call.kwargsi r2r"c|js(|jxsd}|jdrd|z}|St|dk(rd}|\}}n'|\}}}|sd}n|jdsd|z}nd|z}t |||S)Nrr%zcall%srzcall.%s)rrrVrr~)rPrwrQrRs r#rz_Call.__repr__m s##??,fDt$$K t9>DLD&!% D$__T* 4'$%dD&99r"cg}|}|,|jr|j||j}|,tt |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.)rr!rrr[)rPvalsthings r# call_listz_Call.call_list sM$$ E"&&E$((r")r!rNFT)r!NNFT)rrrr rrArrgrrDrr,r.rrQrRrr8r!r"r#rr s|$:?8@>C)2Fj]]FN>2 ----:* )r"r)rc t|r t|}t|t}t|rt d|dt |}d|i} |rd|i} n|i} | r|rd| d<|s t ||jd|}|} |d } | j|t} tj|ri} n=|r|r td t} n't|st} n|r|rt!|st} | d||| |d | } t|t"rt%| |} |rt'| nt)|| ||||s| |j*|<|jd d} |r|sd |vrt-||dd| | | _t1|D]}t3|r t5||}d|i}| rt9| |r|j||rd|i}t|t"st;||| ||}|| j*|<n~| }t|t"r | j<}t?|||}||d<tA|rt}nt}|d||||d|}|| j*|<||_t)|||t|t"stC| ||t| r|r| jDdi|| S#t6$rYCwxYw)aCreate 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` 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. `create_autospec` also takes arbitrary keyword arguments that are passed to the constructor of the created mock.z'Cannot autospec a Mock object. [object=rrrNTrrwrzJInstance can not be True when create_autospec is mocking an async function)rrrrwrrr%)rZr-rrrdr)rrwrr)rYr!)#rhr7r(r'rr3rrGrrr+isdatadescriptorrr rdr rnr>rzrr[rr rr rr*rEr)r9r= _must_skiprr`r)rrrZrr-rrRis_type is_async_funcr8rr5r=wrappedrAru child_kwargsrrrY child_klasss r#r r s.~Dzt$G"**. 45 5"4(MtnGt$ 8'+#$ f% JJvu %EI  NN6 E%   >? ? t_$ X&8&>$  (W  (& (D$ &dD)  d #tWh78(,u%jj$'GxN&$@+D(T2629;T U   tU+H) ww.   h  / &1L(M2XxuhGC),D   &F$ ."48I(1L %"8,' ' BV%5*0B4@BC),D   &*}C  Xsi @ c= ) D% %gn6%f% KU   s J?? K  K c,t|ts|t|divry|j}|jD]X}|j j |t}|tur,t|ttfryt|tr|cSy|S)z[ Return whether we should skip the first argument on spec's `entry` attribute. rkF) r(r7r*r,rjrkrlrrCrBr>)rrAr<rrvs r#r;r;( s dD ! GD*b1 1~~##E73 W   f|[9 :  .N Nr"ceZdZ ddZy)r9NcX||_||_||_||_||_||_yr5)ridsrrrZrw)rPrrrrwrDrZs r#rAz_SpecState.__init__F s,       r")FNNNF)rrrrAr!r"r#r9r9D s 48/4r"r9cvt|trtj|Stj|Sr5)r(bytesioBytesIOStringIO) read_datas r# _to_streamrK\ s*)U#zz)$${{9%%r"c d t}|dg fd} fd} fd fd fd}tVddl}tt t |j jt t |jat+ddl}tt t |ja |tdt }tt  j_ d j_ d j_ d j _ d j"_ | j_ d < d  j _| j"_ j&_| j(_ fd }||_ |_ |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. NcjjjjSdj|i|Sr0) readlinesrrQrR_statehandles r#_readlines_side_effectz)mock_open.._readlines_side_effectr sC    ( ( 4##00 0"vay""D3F33r"cjjjjSdj|i|Sr0)readrrOs r#_read_side_effectz$mock_open.._read_side_effectw s= ;; # # /;;++ +vay~~t.v..r"c?`KEd{ dj|i|7wr0)readline)rQrR_iter_side_effectrPs r#_readline_side_effectz(mock_open.._readline_side_effect| s<$&&&$&)$$d5f5 5 's .,.c3Kjj jjdD]}|ywr0)rWr)linerPrQs r#rXz$mock_open.._iter_side_effect sB ?? ' ' 3oo2221IDJsAAcxjjjjStdSr0)rWrr)rPrQsr#_next_side_effectz$mock_open.._next_side_effect s1 ?? ' ' 3??// /F1Ir"ropen)rwr)rrctd<jjdk(rd<dj_tS)Nrr)rKrWrr)rQrRrYrPrQrJs r# reset_datazmock_open..reset_data sHy)q ?? & &&) 3-/F1I*0)FOO 'r")rK file_spec_iorfrir  TextIOWrapperunionrH open_specr^rr:rwriterTrWrNrrr) r=rJ _read_datarRrUr]rbr`rXrYrPrQs ` @@@@r#rrc sWI&J$ F4 / 6  S!2!234::3s3;;?O;PQR S]+,  |f95 I &F$*F! $FLL#FKK#'FOO $(F!/FKK%'F1I"()FOO#9F "3FOO"3FOO"DD Kr"c$eZdZdZdZddZdZy)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. c tdi|S)Nr!)r)rPrRs r#r'zPropertyMock._get_child_mock s"6""r"Nc|Sr5r!)rPr.obj_types r#r~zPropertyMock.__get__ s v r"c||yr5r!)rPr.rIs r#rzPropertyMock.__set__ s  S r"r5)rrrr r'r~rr!r"r#rr s#r"rcd|_t|D]d} t||}t |t s!t |j j|trK|j|usZt|fy#t$rYswxYw)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) rr r*rEr(r rrlr9rr)r=rrs r#rr sDD  d#A!_-  a&&**40* =    % G   s A;; BBceZdZdZdZdZy)rz8 Wraps an iterator in an asynchronous iterator. cz||_tt}tj|_||j d<y)Nrr1)iteratorr rr+CO_ITERABLE_COROUTINErrk)rPrprs r#rAz_AsyncIterator.__init__ s/  #X6 $:: $- j!r"c^K t|jS#t$rYtwxYwwr5)rrprrrs r#rz_AsyncIterator.__anext__ s1  & &     s-- *-*-N)rrrr rArr!r"r#rr s. !r"rr)NFNNN)FFNN)Nr)__all__rrrGr+rr2builtinsrHrtypesrrr unittest.utilr functoolsrr threadingrrrr rVr(r rrr/r3r'r:r?rKr[rVrdrhrnrzrtrrrgrrrrMISSINGr{DELETEDr:rrrfrrrrr frozenset removeprefixrWrr3rrrrrJrOrSrrVrnrvrYmultiplestopallr magic_methodsnumericsr\rFinplaceright _non_defaultsrvrr_sync_async_magics _async_magicsrrUrurrrrrrrrrrr rrrrFrArrrGrr r rr~rgrrr r;r9r7rr>rarerKrrrr)rwrs00r#rs &  '22#$CyC"(m Hmd4??33GTm H   @2  F # & 6."b>6) )f )   ;          &**(6  6 X   :   j G DGB""$!!!'(*;*;T"BCIh-K E+TE+P((V 6  f$$v)Ev)r uCGS*/Sl8        &Od4$0!!e] IP l dIs*N;3N;0)O& O:+O OO