U ;rc@sdZdZddlZddlZddlZddlZddlZddlZddlZddl 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.d-d.d/d0d1d2d3d4hZ/d5d6Z0Gd7d8d8e1Z2d9d:Z3Gd;d<dd>e&Z5Gd?d@d@e5Z6dAdBZ7GdCdDdDe5Z8GdEdFdFe8e6Z9dGdHZ:dIdJZ;GdKdLdLe&ZddQdRZ?e*dddddfdSdTZ@GdUdVdVe&ZAdWdXZBdYdZZCe>e@_&eAe@_De?e@_EeCe@_Fd[e@_Gd\ZHd]ZId^Jd_d`eIKDZLd^Jdad`eIKDZMdbdcdddedfdgdhdidjdkdldmdndodpdqdrdshZNdtduZOdvdd^JeHeIeLeMgKDZPdwdxdyhZQdzhZReQeRBZSePeNBZTeTeSBZUd{d|d}d~ddddhZVdddddddddZWeXeXeXeXddddddd ddd ZYddZZddZ[ddZ\ddZ]eZe[e\e]dZ^ddZ_Gddde5Z`Gddde`e6ZaGddde`ZbGddde`e9ZcGddde5ZdGddde5ZeGdddeeebe9ZfGddde&ZgegZhddZiGdddejZkekddZldddZmddZnGddde&ZoepemepehjqfZrdasddZtdddZuGddde9ZvddZwGdddZxdS))Mock MagicMockpatchsentinelDEFAULTANYcallcreate_autospec AsyncMock FILTER_DIRNonCallableMockNonCallableMagicMock mock_open PropertyMocksealz1.0N)CodeType ModuleType MethodType) safe_repr)wrapspartialcCsh|]}|ds|qS_ startswith).0namer#/usr/lib/python3.8/unittest/mock.py (s rTcCs>t|rt|tsdSt|dr*t|d}t|p.checksig)r=_copy_func_detailsr1_mock_check_sig __signature__)r-r5 skipfirstinstancerFrrDr_check_signaturers    rLc Cs:dD]0}zt||t||Wqtk r2YqXqdS)N)__name____doc____text_signature__ __module__ __defaults____kwdefaults__)setattrr$r:)r-funcopy attributerrrrG~s rGcCs@t|trdSt|tttfr(t|jSt|dddk rrBrCrDrrrFsz _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)Ncs j||Sr/)assert_called_withrar5rrrjsz'_setup_func..assert_called_withcs j||Sr/) assert_calledrarkrrrlsz"_setup_func..assert_calledcs j||Sr/)assert_not_calledrarkrrrmsz&_setup_func..assert_not_calledcs j||Sr/)assert_called_oncerarkrrrnsz'_setup_func..assert_called_oncecs j||Sr/)assert_called_once_withrarkrrrosz,_setup_func..assert_called_once_withcs j||Sr/)assert_has_callsrarkrrrpsz%_setup_func..assert_has_callscs j||Sr/)assert_any_callrarkrrrqsz$_setup_func..assert_any_callcs:t_t_j}t|r6|k r6|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|||Sr/)r$r5)attrrBrCrkrrwrappersz"_setup_async_mock..wrapper)assert_awaitedassert_awaited_onceassert_awaited_withassert_awaited_once_withassert_any_awaitassert_has_awaitsassert_not_awaited) r% 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!srrv_mock_return_valuer}_mock_side_effect _mock_parent_mock_new_parent _mock_name_mock_new_namecCs8t|d|}||fdd}||fdd}t||S)NZ_mock_cSs"|j}|dkrt||St||Sr/)rr$)rAr _the_namerErrr_getAs z"_delegating_property.._getcSs*|j}|dkr||j|<n t|||dSr/)rr]rS)rAvaluerrrErrr_setFs 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_listrrrrSs  z_CallList.__contains__cCstt|Sr/)pprintZpformatrYrrrrrasz_CallList.__repr__N)rMrPrrrrrrrrrQsrrcCs|t|}t|sdS|js4|js4|jdk s4|jdk r8dS|}|dk rX||krPdS|j}q<|rh||_||_|rx||_||_dS)NFT)r7r!rrrr)parentrrnew_name_parentrrr_check_and_set_parentes* 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`c Os|f}t|ts^ttj}|j|f||j}dd|D}|r^t ||dr^t |f}t |j |d|j i}tt||}|S)NcSsg|]}|dr|qSspecrrargrrr s z+NonCallableMock.__new__..rrN)r0r r'r;r r8Z bind_partialZ argumentskeysr*AsyncMockMixinr1rMrN _safe_super__new__) clsrBkwbasesrEZ bound_argsZspec_argnewrKrrrrs  zNonCallableMock.__new__NFc Ks|dkr |}|j} || d<|| d<|| d<|| d<d| d<|dk rJ|}d}| dkrZ|dk } |||| | i| d<|| d <d| d <d| d <d| d <d | d<t| d<t| d<t| d<| | d<| r|jf| 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)rArrrspec_setr _spec_state _new_name _new_parent_spec_as_instance _eat_selfZunsaferCr]rrrr8sD     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|dk r~t|s~t|trV|}nt|}t|||} | ot| d}t|}|j } || d<|| d<|| d<|| d<|| d<dS)Nr _spec_class _spec_set_spec_signature _mock_methods _spec_asyncs) dirr%r&r$appendr[r"r1r=r]) rArrrrrrrrresr]rrrrs,    zNonCallableMock._mock_add_speccCs8|j}|jdk r|jj}|tkr4|j|dd}||_|S)N()rr)rrrvr_get_child_mock)rArwrrrZ__get_return_values z"NonCallableMock.__get_return_valuecCs,|jdk r||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|jdkrt|S|jSr/)rr1rrrr __class__!s zNonCallableMock.__class__ryrzr{r|rtcCsN|j}|dkr|jS|j}|dk rJt|sJt|tsJt|sJt|}||_|Sr/)rrr}callabler"rr3)rA delegatedZsfrrrZ__get_side_effect.sz!NonCallableMock.__get_side_effectcCs(t|}|j}|dkr||_n||_dSr/) _try_iterrrr})rArrrrrZ__set_side_effect9s z!NonCallableMock.__set_side_effect)rvr}cCs|dkr g}t||krdS|t|d|_d|_d|_t|_t|_t|_|r^t |_ |rhd|_ |j D]"}t|tsr|tkrqr||qr|j }t|r||k r||dS)z-Restore the mock object to its initial state.NFr)idrryr{rzrrrtr|rsrrrr~valuesr" _SpecState_deletedrur!)rAZvisitedrvr}childrwrrrruDs,  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)entryrrroz0NonCallableMock.configure_mock..)keyrN)sorteditemssplitpopr$rS)rArCrvalrBfinalr)rrrrrbs   zNonCallableMock.configure_mockcCs|dkrt|n:|jdk r<||jks.|tkrLtd|nt|rLt||jsd|drdtd|j|}|tkrt|np|dkrd}|j dk rt |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)rArrfrrrrrxsF          zNonCallableMock.__getattr__cCs|jg}|j}|}d}|dgkr$d}|dk rZ|}||j|d}|jdkrRd}|j}q$tt|}|jpnd}t|dkr|ddkr|d7}||d<d|S)Nrrrr5r)rz().r)rrrrYreversedrrjoin)rAZ _name_listrZlastdotZ_firstrrr_extract_mock_names(      z"NonCallableMock._extract_mock_namecCs^|}d}|dkrd|}d}|jdk rDd}|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|]\}}|tk r|qSr)r)rZm_nameZm_valuerrrrsz+NonCallableMock.__dir__..cSsg|]}|ds|qSrrrerrrrs cSs"g|]}|drt|r|qSr)rrrrrrrs ) r object__dir__rrr1rYr]r~rrset)rAZextrasZ from_typeZ from_dictZfrom_child_mocksrrrrs    zNonCallableMock.__dir__csT|tkrt||SjrHjdk rH|jkrH|jkrHtd|n|tkrbd|}t|n|tkrjdk r|jkrtd|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.csf||Sr/rrBrrerArrrrz-NonCallableMock.__setattr__..rrz Cannot set )rr __setattr__rrr]r:_unsupported_magicsrr!rSr1 _get_methodrr~rrr#r)rArrmsg mock_namerrrrs<    zNonCallableMock.__setattr__cCs|tkr2|t|jkr2tt||||jkr2dS|j|t}||jkr\tt| |n|t krlt ||tk r||j|=t |j|<dSr/) rr1r]delattrr~r^_missingrr __delattr__rr:)rArr)rrrrs  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]:}||}|dksJt|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}|dk rt|dkrNd}|\}}n |\}}}z||j||fWStk r}z|dWYSd}~XYqXn|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? TypeErrorwith_traceback)rA_callrErrBrCrrrr _call_matcherHs   "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 rrrrmbs 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)rzrrr rrrrlls  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.%sr5Nrr rrrrnts z"NonCallableMock.assert_called_oncecsjdkr.}d}d||f}t|fdd}f}j}||kr~t|trn|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_message)r{rrrr" Exception)rArBrCexpectedactualZ error_messager$causerr#rrj~s   z"NonCallableMock.assert_called_withcOs8|jdks,d|jpd|j|f}t||j||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||kr|dkrXd}ndd d|D}t|d t|jd d d |dSt|}g}|D]2}z||Wqt k r| |YqXq|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|]}|qSrrrcrrrrsz4NonCallableMock.assert_has_calls..css|]}t|tr|VqdSr/r"r%rrrr s z3NonCallableMock.assert_has_calls..Nc3s|]}|VqdSr/r*r+rrrr.szCalls 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_foundkallrrrrpsH "z NonCallableMock.assert_has_callscsZ||f}fddjD}||krVt|tr8|nd}||}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.csg|]}|qSrr*r+rrrrsz3NonCallableMock.assert_any_call..Nz%s call not found)rr|r"r%rrrArBrCr&r'r(rrrrrqs zNonCallableMock.assert_any_callcKs|d}||jdkr"tf|St|}t|trB|tkrBt}nbt|trp|tksd|j rj||j krjt}qt}n4t|t st|t rt}qt|t rt }n |jd}|jrd|krd|dnd}||}t||f|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 r1r0r_async_method_magicsr_all_sync_magicsr CallableMixinr r rr\rrr:)rArr_typeklassrUr rrrrs2        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)rAr0rrrrszNonCallableMock._calls_repr) NNNNNNrNFNF)F)FF)N)r)F)r?)-rMrPrrNrr8rrrZ"_NonCallableMock__get_return_valueZ"_NonCallableMock__set_return_valueZ"_NonCallableMock__return_value_docrrvrrryrzr{r|rtZ!_NonCallableMock__get_side_effectZ!_NonCallableMock__set_side_effectr}rurrrrrrrrrrrrmrlrnrjrorprqrrrrrrr sp -      '' !   -'r cCsL|dkr |St|r|St|r$|Sz t|WStk rF|YSXdSr/)r3rXrrr(rrrrs rc @sReZdZddedddddddf ddZddZddZd d Zd d Zd dZ dS)r<Nrc Ks6||jd<tt|j||||||| | f| ||_dS)Nr)r]rr<r8r}) rArr}rvrrrrrrrrCrrrr8#s  zCallableMixin.__init__cOsdSr/rr@rrrrH/szCallableMixin._mock_check_sigcOs$|j|||j|||j||Sr/)rH_increment_mock_call _mock_callr@rrrr94s  zCallableMixin.__call__cOs |j||Sr/)_execute_mock_callr@rrrrB<szCallableMixin._mock_callc Osd|_|jd7_t||fdd}||_|j||jdk }|j}|j}|dk}|j td||f|j }|dk r|r|j t|||f|jdk }|r|jd|}t|||f} |j | |jr|rd} nd} |jdk}|j| |}|j }qpdS)NTrtworrr) ryrz_Callr{r|rrrrrtrrs) rArBrCrZdo_method_callsZmethod_call_nameZmock_call_nameZ is_a_callrZthis_mock_callrrrrrA?s4     z"CallableMixin._increment_mock_callcOs||j}|dk rPt|r|n(t|s:t|}t|rD|n |||}|tk rP|S|jtk r`|jS|jdk rv|j||S|jSr/)r}r3rXrrrrvr)rArBrCeffectrfrrrrCms     z CallableMixin._execute_mock_call) rMrPrrr8rHr9rBrArCrrrrr<!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. NrMrPrrNrrrrrsrcCs8z t||WStk r2t|t||YSXdSr/)r$r: __import__)thingcomp import_pathrrr _dot_lookups  rMcCsB|d}|d}t|}|D]}|d|7}t|||}q |S)Nrrz.%s)rrrIrM)targetZ componentsrLrJrKrrr _importers   rOc@szeZdZdZgZddZddZddZdd Ze j d d Z d d Z ddZ ddZddZddZddZddZdS)_patchNc Csn|dk r(|tk rtd|dk r(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) rArQrUrrrSrrTrRrCrrrr8s(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..) rPrQrUrrrSrrTrRrCattribute_namerU)rApatcherrrrrVs z _patch.copycCs2t|tr||St|r(||S||Sr/)r"r1decorate_classr'r&decorate_async_callabledecorate_callablerAr-rrrr9s     z_patch.__call__cCsNt|D]@}|tjsqt||}t|ds0q|}t||||q|SNr9)rrr TEST_PREFIXr$r#rVrS)rAr>r attr_valuerYrrrrZs    z_patch.decorate_classc csrg}t\}|jD]8}||}|jdk r8||q|jtkr||q|t |7}||fVW5QRXdSr/) contextlib ExitStack patchings enter_contextrXupdaterrrrZ)rApatchedrBkeywargs extra_args exit_stackpatchingrrrrdecoration_helpers        z_patch.decoration_helpercs>tdrjStfddg_S)Nrcc s4||\}}||W5QRSQRXdSr/rkrBrgZnewargsZ newkeywargsr-rfrArrrf(s z)_patch.decorate_callable..patchedr#rcrrr]rrnrr\"s  z_patch.decorate_callablecs>tdrjStfddg_S)Nrcc s:||"\}}||IdHW5QRSQRXdSr/rlrmrnrrrf9s z/_patch.decorate_async_callable..patchedror]rrnrr[3s  z_patch.decorate_async_callablec Cs|}|j}t}d}z|j|}Wn$ttfk rHt||t}YnXd}|tkrft|t rfd|_ |j s|tkrtd||f||fS)NFTz!%s does not have the attribute %r) rQrUrr]r:KeyErrorr$ _builtinsr"rrS)rArNrrelocalrrr get_originalDs  z_patch.get_originalcCs|j|j|j}}}|j|j}}|j}||_|dkr@d}|dkrLd}|dkrXd}|dk rp|dk rptd|dk s|dk r|dkrtd| \}}|t kr||dkr|d} |dkr|}|dkr|}d}n&|dk r|dkr|}d}n |dkr|}|dk s |dk r.|t krtdt |t r.d} |dkrHt |rHt} nt} i} |dk r`|} n^|dk st|dk r|} |dk r|} t| rd| k} n t|  } t | rt} n | rt} |dk r|| d <|dk r|| d <t | t r t| tr |jr |j| d <| || f| }| rt|r|} |dk rB|} t| sZt| sZt} | d | f|d d | |_nl|dk r|t k rtd|t krtdt|}|dkr|}t|f||jd|}n|rtd|}||_||_t |_!zrt"|j|j||j#dk rpi}|jt kr:|||j#<|j$D](}|j!%|}|jt kr@||q@|WS|WS|j&t'(sYnXdS)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))rrrrTrCrRrQrNrrsrr"r1r*r rr[rr r0r rUrer!r`rrvboolr temp_originalis_localrarb _exit_stackrSrXrUrd__exit__sysexc_info)rArrrrTrCrRrerrZinheritKlass_kwargsZ this_specZ not_callableZnew_attrrhrjrrrr __enter__\s                                z_patch.__enter__cGs|jr$|jtk r$t|j|j|jn>t|j|j|jsbt|j|jrP|jdkrbt|j|j|j|`|`|`|j }|` |j |S)zUndo the patch.)rNrPrQ__annotations__rR) rwrvrrSrNrUr rSr#rxry)rAr{rirrrrysz_patch.__exit__cCs|}|j||S)z-Activate a patch, returning any created mock.)r~_active_patchesr)rArfrrrstarts z _patch.startcCs6z|j|Wntk r&YdSX|dddS)zStop an active patch.N)rr3r<ryrrrrstops z _patch.stop)rMrPrrXrr8rVr9rZracontextmanagerrkr\r[rsr~ryrrrrrrrPs   rPc sPzdd\}Wn&ttfk r:tdfYnXfdd}||fS)Nrrz.Need a valid target to patch. You supplied: %rcstSr/rOrrNrrrrz_get_target..)rsplitrr<)rNrUrQrrr _get_target s  rc s>ttkrtdfdd} 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/rrrrrr*rz_patch_object..)r1strrrP) rNrUrrrSrrTrRrCrQrrr _patch_objects   rc sttkrfdd}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/rrrrrrHrz!_patch_multiple..csSr/rrrrrrJrz=Must supply at least one keyword argument with patch.multiplerrN) r1rr<rYrrPrXrUr) rNrrSrrTrRrCrQrrUrrYZ this_patcherrrr_patch_multiple1sH    rc Ks$t|\}} t|| ||||||| S)a7 `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 the `Mock` (or `new_callable`) on construction. `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are available for alternate use-cases. )rrP) rNrrrSrrTrRrCrQrUrrrrbsF rc@sReZdZdZdddZddZdd Zd d Zd d ZddZ ddZ eZ e Z 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_dictdictrreclear _original)rArrrrCrrrr8s   z_patch_dict.__init__cs.ttrStfdd}|S)Ncs&z||WSXdSr/)r _unpatch_dictrfrArr_innersz$_patch_dict.__call__.._inner)r"r1rZr)rArrrrrr9s   z_patch_dict.__call__cCsXt|D]J}t||}|tjrt|drt|j|j|j }||}t |||q|Sr^) rr$rrr_r#rrrrrS)rAr>rr`Z decoratorZ decoratedrrrrZs   z_patch_dict.decorate_classcCs||jS)zPatch the dict.)rrrrrrr~sz_patch_dict.__enter__cCs|j}t|jtrt|j|_|j}|j}z |}Wn.tk rdi}|D]}||||<qNYnX||_|rxt |z| |Wn*tk r|D]}||||<qYnXdSr/) rr"rrrOrrVr:r _clear_dictre)rArrrrerrrrrs&   z_patch_dict._patch_dictcCsR|j}|j}t|z||Wn*tk rL|D]}||||<q6YnXdSr/)rrrrer:)rArrerrrrrsz_patch_dict._unpatch_dictcGs |dS)zUnpatch the dict.F)r)rArBrrrrysz_patch_dict.__exit__N)rF) rMrPrrNr8r9rZr~rrryrrrrrrrs   rcCs>z |Wn,tk r8t|}|D] }||=q(YnXdSr/)rr:rY)rrrrrrr&s  rcCsttjD] }|q dS)z7Stop all active patches. LIFO to unroll nested patches.N)rrPrr)rrrr_patch_stopall/srZtestzlt 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%sNrrnrrrr.Nsr.ccs|]}d|VqdS)zr%sNrrrrrr.Os__get____set__ __delete__ __reversed__ __missing__r __reduce_ex__Z__getinitargs____getnewargs__ __getstate__ __setstate__ __getformat__Z __setformat__rr__subclasses__ __format____getnewargs_ex__csfdd}||_|S)z:Turns a callable object (like a mock) into a real functioncs|f||Sr/rrArBrr,rrmethod`sz_get_method..method)rM)rr-rrr,rr ^s r cCsh|] }d|qS)rr)rrrrrrfs __aenter__ __aexit__ __anext__ __aiter__rrr8r __prepare____instancecheck____subclasscheck____del__cCs t|Sr/)r__hash__rrrrr|rrcCs t|Sr/)r__str__rrrrr}rcCs t|Sr/)r __sizeof__rrrrr~rcCs"t|jd|dt|S)N/)r1rMrrrrrrrr)rrr __fspath__ry?g?) __lt____gt____le____ge____int__r__len__ry __complex__ __float____bool__ __index__rcsfdd}|S)Ncs$jj}|tk r|S|kr dStSNT)__eq__rrNotImplemented)otherret_valrrrrs z_get_eq..__eq__r)rArrrr_get_eqs rcsfdd}|S)Ncs jjtk rtS|krdStSNF)__ne__rrr)rrrrrs  z_get_ne..__ne__r)rArrrr_get_nes rcsfdd}|S)Ncs jj}|tkrtgSt|Sr/)__iter__rrrrrrrrsz_get_iter..__iter__r)rArrrr _get_iters rcsfdd}|S)Ncs(jj}|tkrttgStt|Sr/)rrr_AsyncIteratorrrrrrrs z"_get_async_iter..__aiter__r)rArrrr_get_async_iters r)rrrrcCsbt|t}|tk r||_dSt|}|dk rB||}||_dSt|}|dk r^|||_dSr/)_return_valuesr^rrv_calculate_return_value_side_effect_methodsr})r5rrZfixedZreturn_calculatorrvZ side_effectorrrr_set_return_values   rc@seZdZddZddZdS) MagicMixincOs&|tt|j|||dSr/)_mock_set_magicsrrr8rrrrr8szMagicMixin.__init__cCsttB}|}t|dddk rX||j}t}||}|D]}|t|jkr: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|||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||||dSrrrrrrrs zMagicMock.mock_add_specN)Frrrrrrs rc@s&eZdZddZddZdddZdS) rcCs||_||_dSr/rr)rArrrrrr8szMagicProxy.__init__cCs8|j}|j}|j|||d}t|||t||||S)N)rrr)rrrrSr)rArrmrrr create_mocks  zMagicProxy.create_mockNcCs|Sr/)r)rAr)r=rrrr(szMagicProxy.__get__)N)rMrPrr8rrrrrrrs rcseZdZedZedZedZfddZddZdd Z d d Z d d Z ddZ ddZ dddZddZfddZZS)rrrrcs\tj||tjj|jd<d|jd<d|jd<t|jd<ttd}t j |_ ||jd<dS)NrrZ_mock_await_countZ_mock_await_argsZ_mock_await_args_listrr+) superr8r%rrr]rrr rr'Z CO_COROUTINEco_flags)rArBrC code_mockrrrr81s    zAsyncMockMixin.__init__cst||fdd}|jd7_||_|j||j}|dk rt|rL|nbt|sz t|}Wnt k rxt YnXt|r|n&t |r|||IdH}n |||}|t k r|S|jt k r|jS|jdk rt |jr|j||IdHS|j||S|jS)NTrDr)rFrrrrr}r3rXr StopIterationStopAsyncIterationr%r&rrrvr)rArBrCrrGrfrrrrCAs6         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.Nrrrr rrrris 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.Nrr rrrrqs z"AsyncMockMixin.assert_awaited_oncecszjdkr&}td|dfdd}f}j}||krvt|trf|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_message)rrrrr"r%)rArBrCr&r$r'r(rr#rrzs   z"AsyncMockMixin.assert_awaited_withcOs8|jdks,d|jpdd|jd}t||j||S)zi Assert that the mock was awaited exactly once and with the specified arguments. rrr5rr)rrrrr)rrrrs z'AsyncMockMixin.assert_awaited_once_withcsZ||f}fddjD}||krVt|tr8|nd}||}td||dS)zU Assert the mock has ever been awaited with the specified arguments. csg|]}|qSrr*r+rrrrsz3AsyncMockMixin.assert_any_await..Nz%s await not found)rrr"r%rrr9rrrrs zAsyncMockMixin.assert_any_awaitFc sfdd|D}tdd|Dd}tfddjD}|s||kr|dkrXd}ndd d|D}t|d t|d j|dSt|}g}|D]2}z||Wqtk r||YqXq|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+rrrrsz4AsyncMockMixin.assert_has_awaits..css|]}t|tr|VqdSr/r-rrrrr.s z3AsyncMockMixin.assert_has_awaits..Nc3s|]}|VqdSr/r*r+rrrr.szAwaits not found.z,Error processing expected awaits. Errors: {}cSsg|]}t|tr|ndqSr/r-rrrrrsr/z Actual: z%r not all found in await list) rrrrr1rrYr3r<rrZ) rAr4r5r&r(Z all_awaitsr6r7r8rrrrs>  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 rNrr rrrrs z!AsyncMockMixin.assert_not_awaitedcs&tj||d|_d|_t|_dS)z0 See :func:`.Mock.reset_mock()` rN)rrurrrrrr@rrrruszAsyncMockMixin.reset_mock)F)rMrPrrrrrr8rCrrrrrrrru __classcell__rrrrr,s (   , rc@seZdZdZdS)r aa 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() >>> asyncio.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. NrHrrrrr sr c@s(eZdZdZddZddZddZdS) _ANYz2A helper object that compares equal to everything.cCsdSrrrArrrrr sz _ANY.__eq__cCsdSrrrrrrr sz _ANY.__ne__cCsdS)Nzrrrrrr 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)reprrrrrr! sz*_format_call_signature..cSsg|]\}}d||fqS)z%s=%rr)rrrrrrr" s)rr)rrBrCrZformatted_argsZ args_stringZ kwargs_stringrrrr s rc@seZdZdZd!ddZd"d d Zd d ZejZd dZ ddZ ddZ ddZ ddZ ddZeddZeddZddZdd ZdS)#rFa 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) rrrrrE from_kallrBrC_lenfirstsecondrrrrC s.      z _Call.__new__cCs||_||_||_dSr/)rr_mock_from_kall)rArrrrErrrrr8c sz_Call.__init__c Csh|tkr dSz t|}Wntk r.YdSXd}t|dkrJ|\}}n |\}}}t|ddr|t|ddr||j|jkr|dSd}|dkrdi}}n|dkr|\}}}n|d kr|\} t| tr| }i}n"t| tr| }di}}nd}| }nV|dkr@|\} } t| tr4| }t| tr(| i}}n d| }}n | | }}ndS|rX||krXdS||f||fkS) NTFrrrrrrr)rrrr$rr"rZr) rArZ len_otherZ self_nameZ self_argsZ self_kwargsZ other_nameZ other_argsZ other_kwargsrrrrrrrj sR                z _Call.__eq__cOs<|jdkrtd||fddS|jd}t|j||f||dS)NrrrrrrFrrrrr9 s  z_Call.__call__cCs2|jdkrt|ddSd|j|f}t||ddS)NF)rrz%s.%s)rrrr)rArrrrrr s  z_Call.__getattr__cCs|tjkrtt||Sr/)rZr]r:__getattribute__)rArrrrr s z_Call.__getattribute__cOs|d||S)Nrrr@rrrr sz _Call.countcOs|d||S)Nindexrr@rrrr sz _Call.indexcCs(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}|}|dk r(|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)rAZvalsrJrrr call_list s z_Call.call_list)rrNFT)rNNFT)rMrPrrNrr8rrrr9rrrrrrrBrCrrrrrrrF0 s*  7  rF)rc Kslt|rt|}t|t}t|}d|i}|r8d|i}n |dkrDi}|rT|rTd|d<||t} t|rri}n8|r|rtdt } n"t |st } n|r|rt |st } | d|}|} |dkrd} | f||| |d |} t|trt| |} |rt| nt|| |||dk r,|s,| |j|<|rV|sVd |krVt||dd | d | _t|D]} t| rrq^zt|| } Wntk rYq^YnXd| i}|rd| i}t| tst| || | |}|| j| <np| }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)rKrtrr)rrrr)rJ)r[r1r"r.rerr'Zisdatadescriptor RuntimeErrorr rXr r`rr6rirrLr~rrvrrr$r:rr5 _must_skipr%r&rS)rrrKrrtrCis_typeZ is_async_funcr}r|rr5rrerrrJZ child_klassrrrr s                     rcCsxt|ts$|t|dikrdS|j}|jD]H}|j|t}|tkrFq*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)rrrr>rfrrrrw s   rc@seZdZdddZdS)rFNcCs(||_||_||_||_||_||_dSr/)ridsrrrKr)rArrrrrrKrrrr8 s z_SpecState.__init__)FNNNFrrrrrr s rcCs"t|trt|St|SdSr/)r"bytesioBytesIOStringIO) read_datarrr _to_stream s  rrcs&t}|dgfdd}fdd}fddfdd fd d }tdkrd dl}ttt|jtt|ja|dkrt 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$jjdk rjjSdj||Sr) readlinesrvra_statehandlerr_readlines_side_effect s z)mock_open.._readlines_side_effectcs$jjdk rjjSdj||Sr)readrvrarrr_read_side_effect s z$mock_open.._read_side_effectc?s$EdHdj||Vq dSr)readlinera)_iter_side_effectrrr_readline_side_effect s z(mock_open.._readline_side_effectc3s0jjdk rjjVq dD] }|Vq dSr)r rv)linerrrr  s   z$mock_open.._iter_side_effectcs jjdk rjjStdSr)r rvrrrrr_next_side_effect s z$mock_open.._next_side_effectropen)rrrrcs6td<jjdkr2d<dj_tS)Nrr)rr r}rra)rrrrrr reset_data s    zmock_open..reset_data)r file_spec_iorYrr TextIOWrapperunionrrrr~rvwriter r rr}rr)r5rZ _read_datar r rrrr)r rrrrrr 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. cKs tf|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 Cs^d|_t|D]J}zt||}Wntk r8YqYnXt|tsFq|j|krt|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 rr)r5rrrrrr s     rc@s(eZdZdZddZddZddZdS) rz8 Wraps an iterator in an asynchronous iterator. cCs&||_ttd}tj|_||jd<dS)Nrr+)iteratorr rr'ZCO_ITERABLE_COROUTINErr])rArrrrrr8+ s z_AsyncIterator.__init__cCs|Sr/rrrrrr1 sz_AsyncIterator.__aiter__cs*z t|jWStk r YnXtdSr/)rrrrrrrrr4 s  z_AsyncIterator.__anext__N)rMrPrrNr8rrrrrrr' sr)F)F)NFNNN)FFNN)Nr)y__all__ __version__r%rarr'rrzbuiltinstypesrrrZ unittest.utilr functoolsrrrrqr rrr*r.r!r3r7r=rLrGrXr[r`rirdrrrrrrrMISSINGr ZDELETEDrrrrYrrrrrr rr<rrMrOrPrrrrrrrrZmultipleZstopallr_Z magic_methodsZnumericsrrZinplacerightZ _non_defaultsr rr:Z_sync_async_magicsZ _async_magicsr;rrrrrrrrrrrrr rrrrr rrrrZrFrrrrr1rr6rrr rrrrrrrs~      1  h4 <   2 Mw         8+ B   N