B -_->@sNdZdZddlZddlZddlZddlZddlmZddlm Z m Z dde eDZ e fZdejkrzddlZe ejjfZd ZeZd d Zd d ZddZdddZddZddZddZddZdddZddZdd Z Gd!d"d"e!Z"Gd#d$d$e!Z#e#Z$e$j%Z%e$j&Z'e$j(Z)d%d&Z*d'd(d)d*d+d,d-d.hZ+d/d0Z,Gd1d2d2e-Z.d3d4Z/Gd5d6d6e!Z0Gd7d8d8e!Z1Gd9d:d:e1Z2d;d<Z3Gd=d>d>e1Z4Gd?d@d@e4e2Z5dAdBZ6dCdDZ7dEdFZ8GdGdHdHe!Z9dIdJZ:e%dddddfdKdLZ;ddMdNZdSdTZ?dUdVZ@e;e=_!e>e=_Ae$srjavaTcCstt|tS)N) issubclasstyper )objrrr_is_instance_mock3srcCst|tpt|tot|tS)N) isinstanceBaseExceptionsrr)rrrr _is_exception9s r!cCst|tr4|s4y |j}Wntk r,dSXd}n*t|ts^y |j}Wntk r\dSX|rnt|d}n|}y|t|fSt k rdSXdS)z Given an arbitrary, possibly callable object, try to create a suitable signature object. Return a (reduced func, signature) tuple, or None. NT) rr__init__AttributeError FunctionTypes__call__rinspectZ signature ValueError)funcZ as_instanceZeat_selfZsig_funcrrr_get_signature_object@s$    r)FcsNt|||dkrdS\}fdd}t|||t|_t|_dS)Ncsj||dS)N)bind) _mock_selfargskwargs)sigrrchecksigesz"_check_signature..checksig)r)_copy_func_detailsr_mock_check_sig __signature__)r(mock skipfirstinstancer/r)r.r_check_signature`s    r6c Cs>x8dD]0}yt||t||Wqtk r4YqXqWdS)N)__name____doc____text_signature__ __module__ __defaults____kwdefaults__)setattrgetattrr#)r(funcopy attributerrrr0ls r0cCs&t|trdSt|dddk r"dSdS)NTr%F)rrr>)rrrr _callableys  rAcCst|ttfkS)N)rlisttuple)rrrr_is_listsrDcCsHt|tst|dddk Sx(|f|jD]}|jddk r(dSq(WdS)ztGiven an object, return True if the object is callable. For classes, return True if instances would be callable.r%NTF)rrr>__mro____dict__get)rbaserrr_instance_callables  rIc st|s dSt|t}t|||}|dkr.|S|\}fdd}t|||j}|s^d}||d}d|} t| |||} t| || S)Ncsj||dS)N)r*)r,r-)r.rrr/sz _set_signature..checksigr?)Z _checksig_r3zYdef %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs)) rArrr)r0r7 isidentifierexec _setup_func) r3originalr5r4resultr(r/rcontextsrcr?r)r.r_set_signatures$       rQc s_tsdSfdd}fdd}fdd}fdd}fd d }fd d }fd d} fdd} d_d_d_t_t_t_j _ j _ j _ |_ |_ |_| _| _|_|_|_|__dS)Ncs j||S)N)assert_called_with)r,r-)r3rrrRsz'_setup_func..assert_called_withcs j||S)N) assert_called)r,r-)r3rrrSsz"_setup_func..assert_calledcs j||S)N)assert_not_called)r,r-)r3rrrTsz&_setup_func..assert_not_calledcs j||S)N)assert_called_once)r,r-)r3rrrUsz'_setup_func..assert_called_oncecs j||S)N)assert_called_once_with)r,r-)r3rrrVsz,_setup_func..assert_called_once_withcs j||S)N)assert_has_calls)r,r-)r3rrrWsz%_setup_func..assert_has_callscs j||S)N)assert_any_call)r,r-)r3rrrXsz$_setup_func..assert_any_callcs:t_t_j}t|r6|k r6|dS)N) _CallList method_calls mock_calls reset_mock return_valuer)ret)r?r3rrr\s z_setup_func..reset_mockFr)r3rcalled call_count call_argsrYcall_args_listrZr[r] side_effect_mock_childrenrRrVrWrXr\rSrTrUr2_mock_delegate) r?r3r.rRrSrTrUrVrWrXr\r)r?r3rrLs<       rLcCsd|dd|kS)Nz__%s__r)rrrr _is_magicsrhc@s(eZdZdZddZddZddZdS) _SentinelObjectz!A unique, named, sentinel object.cCs ||_dS)N)r)selfrrrrr"sz_SentinelObject.__init__cCs d|jS)Nz sentinel.%s)r)rjrrr__repr__sz_SentinelObject.__repr__cCs d|jS)Nz sentinel.%s)r)rjrrr __reduce__sz_SentinelObject.__reduce__N)r7r: __qualname__r8r"rkrlrrrrrisric@s(eZdZdZddZddZddZdS) _SentinelzAAccess attributes to return a named object, usable as a sentinel.cCs i|_dS)N) _sentinels)rjrrrr"sz_Sentinel.__init__cCs|dkr t|j|t|S)N __bases__)r#ro setdefaultri)rjrrrr __getattr__sz_Sentinel.__getattr__cCsdS)Nrr)rjrrrrlsz_Sentinel.__reduce__N)r7r:rmr8r"rrrlrrrrrnsrncCs$t|ttttfkr t||S|S)N)rdictrBrCset)valuerrr_copys rvr]_mock_return_valuerc_mock_side_effect _mock_parent_mock_new_parent _mock_name_mock_new_namecCs8t|d|}||fdd}||fdd}t||S)NZ_mock_cSs"|j}|dkrt||St||S)N)rer>)rjr _the_namer.rrr_gets z"_delegating_property.._getcSs*|j}|dkr||j|<n t|||dS)N)rerFr=)rjrurr}r.rrr_set#s z"_delegating_property.._set)_allowed_namesaddproperty)rr}r~rrrr_delegating_propertys  rc@seZdZddZddZdS)rYcCsnt|tst||St|}t|}||kr2dSx6td||dD] }||||}||krFdSqFWdS)NFrT)rrB __contains__lenrange)rjruZ len_valueZlen_selfiZsub_listrrrr0s  z_CallList.__contains__cCstt|S)N)pprintZpformatrB)rjrrrrk>sz_CallList.__repr__N)r7r:rmrrkrrrrrY.srYcCst|tr*y |j}Wntk r(YnXt|s6dS|jsV|jsV|jdk sV|jdk rZdS|}x|dk r|||krtdS|j}q`W|r||_||_|r||_||_dS)NFT) rr$r3r#rr{r|ryrz)parentrurnew_name_parentrrr_check_and_set_parentBs.       rc@s$eZdZddZddZddZdS) _MockItercCst||_dS)N)iterr)rjrrrrr"dsz_MockIter.__init__cCs|S)Nr)rjrrr__iter__fsz_MockIter.__iter__cCs t|jS)N)nextr)rjrrr__next__hsz_MockIter.__next__N)r7r:rmr"rrrrrrrcsrc@seZdZeZdZddZdS)BaseNcOsdS)Nr)rjr,r-rrrr"nsz Base.__init__)r7r:rmrrwrxr"rrrrrksrc sXeZdZdZddZdFddZd d ZdGd d ZdHd dZddZ ddZ dZ e e e e Z e ddZedZedZedZedZedZddZddZe eeZdIdddd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zfd.d/Zd0d1Z d2d3Z!d4d5Z"d6d7Z#d8d9Z$d:d;Z%dd?Z'dJd@dAZ(dBdCZ)dDdEZ*Z+S)Kr z A non-callable version of `Mock`cOs$t|j|fd|ji}t|}|S)Nr8)rr7r8object__new__)clsr,kwnewr5rrrrvs 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)Nryr{r|rzF _mock_sealedTrd _mock_wrapsreZ _mock_calledZ_mock_call_argsrZ_mock_call_countZ_mock_call_args_listZ_mock_mock_callsrZ _mock_unsafe)rF_mock_add_specrYconfigure_mock _safe_superr r")rjspecrrspec_setr _spec_state _new_name _new_parent_spec_as_instance _eat_selfZunsafer-rFrrrr"s:      zNonCallableMock.__init__cCs(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)ryrzr{r|r=)rjr3r@rrr attach_mocks zNonCallableMock.attach_mockcCs|||dS)zAdd 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)r)rjrrrrr mock_add_specszNonCallableMock.mock_add_specc Cszd}d}|dk rPt|sPt|tr(|}nt|}t|||}|oF|d}t|}|j}||d<||d<||d<||d<dS)Nr _spec_class _spec_set_spec_signature _mock_methods)rDrr _get_classr)dirrF) rjrrrrrrZresrFrrrrs  zNonCallableMock._mock_add_speccCs8|j}|jdk r|jj}|tkr4|j|dd}||_|S)Nz())rr)rwrer]r_get_child_mock)rjr^rrrZ__get_return_values  z"NonCallableMock.__get_return_valuecCs,|jdk r||j_n||_t||dddS)Nz())rer]rwr)rjrurrrZ__set_return_values  z"NonCallableMock.__set_return_valuez1The value to be returned when the mock is called.cCs|jdkrt|S|jS)N)rr)rjrrr __class__s zNonCallableMock.__class__r_r`rarbr[cCsN|j}|dkr|jS|j}|dk rJt|sJt|tsJt|sJt|}||_|S)N)rerxrccallablerrr!)rj delegatedZsfrrrZ__get_side_effectsz!NonCallableMock.__get_side_effectcCs(t|}|j}|dkr||_n||_dS)N) _try_iterrerxrc)rjrurrrrZ__set_side_effect s z!NonCallableMock.__set_side_effect)r]rccCs|dkr g}t||krdS|t|d|_d|_d|_t|_t|_t|_|r^t |_ |rhd|_ x0|j D]"}t|tst|tkrqt||qtW|j }t|r||k r||dS)z-Restore the mock object to its initial state.NFr)idappendr_rar`rYr[rbrZrrwrxrdvaluesr _SpecState_deletedr\r)rjZvisitedr]rcZchildr^rrrr\s, zNonCallableMock.reset_mockcKs`xZt|dddD]B\}}|d}|}|}x|D]}t||}q:Wt|||qWdS)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)entryrrr@z0NonCallableMock.configure_mock..)keyrN)sorteditemssplitpopr>r=)rjr-argvalr,finalrrrrrr3s   zNonCallableMock.configure_mockcCs|dkrt|n:|jdk r<||jks.|tkrLtd|nt|rLt||jsd|drdt||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)assertZassret)rrrrr)r#r _all_magicsrhrrrdrGrrr>rrrrrrr5rr)rjrrNrrrrrrIs6            zNonCallableMock.__getattr__cCs|jg}|j}|}d}|dgkr$d}t}xT|dk r~|}||j|d}|jdkrZd}|j}t||krnP|t|q,Wtt|}|jpd}t |dkr|ddkr|d7}||d<d |S)Nrz()rr3r)z()z().r) r|rzrtrrrrBreversedr{rjoin)rjZ _name_listrZlastdotseenZ_firstrrr_extract_mock_nameos0        z"NonCallableMock._extract_mock_namecCs^|}d}|dkrd|}d}|jdk rDd}|jr8d}||jj}dt|j||t|fS)Nr)r3zmock.z name=%rz spec=%rz spec_set=%rz<%s%s%s id='%s'>)rrrr7rr)rjrZ name_stringZ spec_stringrrrrks  zNonCallableMock.__repr__cCshtst|S|jpg}tt|}t|j}dd|D}dd|D}tt |||t|j S)z8Filter the output of `dir(mock)` to only useful members.cSsg|]}|ds|qS)r)r)rerrr sz+NonCallableMock.__dir__..cSs"g|]}|drt|r|qS)r)rrh)rrrrrrs ) r r__dir__rrrrBrFrrtrd)rjZextrasZ from_typeZ from_dictrrrrs    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||S)Nr)r,r)rMrjrrrrz-NonCallableMock.__setattr__..rrz Cannot set )rr __setattr__rrrFr#_unsupported_magicsrrr=r _get_methodrrdrrhasattrr)rjrrumsg mock_namer)rMrjrrs8      zNonCallableMock.__setattr__cs|tkr2|t|jkr2tt||||jkr2dS|j|t}||jkrXt|n|t krht ||tk rx|j|=t |j|<dS)N) rrrFdelattrrdrG_missingsuper __delattr__rr#)rjrr)rrrrs  zNonCallableMock.__delattr__cCs|jpd}t|||S)Nr3)r{_format_call_signature)rjr,r-rrrr_format_mock_call_signatures z+NonCallableMock._format_mock_call_signaturecCsDd}|||}|j}t|dkr.|dd}|j|}|||fS)Nz!Expected call: %s Actual call: %sr)rrar)rjr,r-messageexpected_stringraZ actual_stringrrr_format_mock_failure_messages    z,NonCallableMock._format_mock_failure_messagec Csv|j}|dk rnt|dkr(d}|\}}n |\}}}y||j||fStk rj}z |dSd}~XYqrXn|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. Nrfr)rrr* TypeErrorwith_traceback)rj_callr.rr,r-rrrr _call_matchers   zNonCallableMock._call_matchercCs.|}|jdkr*d|jpd|jf}t|dS)z/assert that the mock was never called. rz7Expected '%s' to not have been called. Called %s times.r3N)r`r{AssertionError)r+rjrrrrrTs  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.r3N)r`r{r)r+rjrrrrrSs   zNonCallableMock.assert_calledcCs.|}|jdks*d|jpd|jf}t|dS)z3assert that the mock was called only once. rz8Expected '%s' to have been called once. Called %s times.r3N)r`r{r)r+rjrrrrrU#s  z"NonCallableMock.assert_called_oncecs||jdkr(}td|ffdd}f}j}||krxt|trh|nd}t||dS)zassert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.NzExpected call: %s Not calledcs}|S)N)r)r)r,r-rjrr_error_message6s z:NonCallableMock.assert_called_with.._error_message)rarrrr Exception)r+r,r-expectedractualcauser)r,r-rjrrR,s   z"NonCallableMock.assert_called_withcOs6|}|jdks*d|jpd|jf}t||j||S)ziassert that the mock was called exactly once and that that call was with the specified arguments.rz1Expected '%s' to be called once. Called %s times.r3)r`r{rrR)r+r,r-rjrrrrrV@s  z'NonCallableMock.assert_called_once_withc sfdd|D}t|tr |nd}tfddjD}|sd||kr`tdt|jf|dSt|}g}x:|D]2}y||Wqvtk r||YqvXqvW|rtdt |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|]}|qSr)r)rc)rjrrrUsz4NonCallableMock.assert_has_calls..Nc3s|]}|VqdS)N)r)rr)rjrr Wsz3NonCallableMock.assert_has_calls..z(Calls not found. Expected: %r Actual: %rz%r not all found in call list) rrrYr[rrBremover'rrC)rjZcallsZ any_orderrrZ all_callsZ not_foundZkallr)rjrrWKs*  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|]}|qSr)r)rr)rjrrrusz3NonCallableMock.assert_any_call..Nz%s call not found)rrbrrrr)rjr,r-rrrrr)rjrrXns zNonCallableMock.assert_any_callcKsxt|}t|ts2t|tr"t}qr# __import__)thingcomp import_pathrrr _dot_lookupFs  rcCsF|d}|d}t|}x$|D]}|d|7}t|||}q"W|S)Nrrz.%s)rrrr)targetZ componentsrrrrrr _importerNs    rcCs t|dS)Nis_local)r)patcherrrr _is_startedYsrc@sdeZdZdZgZddZddZddZdd Zd d Z d d Z ddZ ddZ ddZ ddZdS)_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'getterr@r new_callablercreateZ has_localrautospecr-additional_patchers) rjrr@rrrrrrr-rrrr"cs$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..) rrr@rrrrrrr-attribute_namer)rjrrrrr~sz _patch.copycCst|tr||S||S)N)rrdecorate_classdecorate_callable)rjr(rrrr%s  z_patch.__call__cCsRxLt|D]@}|tjsq t||}t|ds2q |}t||||q W|S)Nr%)rrr TEST_PREFIXr>rrr=)rjrattr attr_valuerrrrrs   z_patch.decorate_classcs<tdrj|Stfdd|g_S)N patchingsc sg}g}t}zybxJjD]@}|}|||jdk rF||q|jtkr||qW|t|7}||S||krt|r||t }YnXWdxt |D]}|j |qWXdS)N) rCr  __enter__rrupdaterrrsysexc_infor__exit__)r,Zkeywargs extra_argsZentered_patchersrpatchingr)r(patchedrrrs*         z)_patch.decorate_callable..patched)rr rr)rjr(r)r(rrrs   z_patch.decorate_callablec Cs|}|j}t}d}y|j|}Wn$ttfk rHt||t}YnXd}|tkrft|t rfd|_ |j s|tkrtd||f||fS)NFTz!%s does not have the attribute %r) rr@rrFr#KeyErrorr> _builtinsrrr)rjrrrMlocalrrr get_originalsz_patch.get_originalcCs<|j|j|j}}}|j|j}}|j}||_|dkr@d}|dkrLd}|dkrXd}|dk rp|dk rptd|dk s|dk r|dkrtd| \}}|t krR|dkrRd} |dkr|}|dkr|}d}n&|dk r|dkr|}d}n |dkr|}|dk s |dk r.|t krtdt |t r.d} t } i} |dk rF|} nN|dk sZ|dk r|} |dk rl|} t| rd| k} n t|  } | rt} |dk r|| d <|dk r|| d <t | t rt| tr|jr|j| d <| || f| }| rt|r|} |dk r|} t| s0t| s0t} | d | f|d d | |_nl|dk r|t k rntd|t krtdt|}|dkr|}t|f||jd|}n|rtd|}||_||_t|j|j||jdk r8i}|jt kr|||j<x.|jD]$}| }|jt kr ||q W|S|S)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=Truer%rrrz())rrzBautospec 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)!rrrrr-rrrrrrrrrrDrr rr r@rrrIrr]boolr temp_originalrr=rrr )rjrrrrr-rrMrZinheritKlass_kwargsZ this_specZ not_callableZnew_attrrrrrrrr s                              z_patch.__enter__cGst|std|jr4|jtk r4t|j|j|jn>t|j|j|j srt |j|jr`|jdkrrt|j|j|j|`|`|`x$t |j D]}t|r|j |qWdS)zUndo the patch.z stop called on unstarted patcher)r8r:r;__annotations__r<N)r RuntimeErrorrrrr=rr@rrrrrr)rjrrrrrr]s z_patch.__exit__cCs|}|j||S)z-Activate a patch, returning any created mock.)r _active_patchesr)rjrNrrrstartus z _patch.startcCs.y|j|Wntk r$YnX|S)zStop an active patch.)r rr'r)rjrrrstop|s z _patch.stop)r7r:rmrr r"rr%rrrr rr!r"rrrrr^s (~rc sPydd\}Wn&ttfk r:tdfYnXfdd}||fS)Nrrz.Need a valid target to patch. You supplied: %rcstS)N)rr)rrrrrz_get_target..)rsplitrr')rr@rr)rr _get_targets r$c s$fdd} 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. csS)Nrr)rrrrrz_patch_object..)r) rr@rrrrrrr-rr)rr _patch_objects  r%c sttkrfdd}n fdd}|s2tdt|}|d\} } t|| | |||||i } | | _xB|ddD]2\} } t|| | |||||i } | | _| j| qvW| 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. cstS)N)rr)rrrrrz!_patch_multiple..csS)Nrr)rrrrrz=Must supply at least one keyword argument with patch.multiplerrN) rstrr'rBrrrrr) rrrrrrr-rrr@rrZ this_patcherr)rr_patch_multiples&        r'c Ks$t|\}} 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 a `MagicMock`. 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 `MagicMock` is used. 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. )r$r) rrrrrrrr-rr@rrrrsE  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|_dS)N)in_dictrsrrclear _original)rjr)rr*r-rrrr"Es   z_patch_dict.__init__cs.ttrStfdd}|S)Ncs"z ||SXdS)N)r( _unpatch_dict)r,r)frjrr_innerQs z$_patch_dict.__call__.._inner)rrrr)rjr-r.r)r-rjrr%Ns  z_patch_dict.__call__cCs\xVt|D]J}t||}|tjr t|dr t|j|j|j }||}t |||q W|S)Nr%) rr>rrr rr(r)rr*r=)rjrr r Z decoratorZ decoratedrrrr\s   z_patch_dict.decorate_classcCs |dS)zPatch the dict.N)r()rjrrrr gsz_patch_dict.__enter__cCs|j}t|jtrt|j|_|j}|j}y |}Wn2tk rhi}x|D]}||||<qPWYnX||_|r|t |y| |Wn.tk rx|D]}||||<qWYnXdS)N) rrr)r&rr*rr#r+ _clear_dictr)rjrr)r*rMrrrrr(ls&     z_patch_dict._patch_dictcCsV|j}|j}t|y||Wn.tk rPx|D]}||||<q8WYnXdS)N)r)r+r/rr#)rjr)rMrrrrr,s z_patch_dict._unpatch_dictcGs |dS)zUnpatch the dict.F)r,)rjr,rrrrsz_patch_dict.__exit__N)rF) r7r:rmr8r"r%rr r(r,rr!r"rrrrr((s   r(cCsBy |Wn0tk r<t|}x|D] }||=q*WYnXdS)N)r*r#rB)r)keysrrrrr/s   r/cCs xttjD] }|q WdS)z7Stop all active patches. LIFO to unroll nested patches.N)rrr r")rrrr_patch_stopallsr1Ztestzlt 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 trunc floor ceil bool next zHadd sub mul matmul div floordiv mod lshift rshift and xor or pow truediv ccs|]}d|VqdS)zi%sNr)rnrrrrsrccs|]}d|VqdS)zr%sNr)rr3rrrrs__get____set__ __delete__ __reversed__ __missing__rl __reduce_ex__Z__getinitargs____getnewargs__ __getstate__ __setstate__ __getformat__Z __setformat__rkr__subclasses__ __format____getnewargs_ex__csfdd}||_|S)z:Turns a callable object (like a mock) into a real functioncs|f||S)Nr)rjr,r)r(rrmethodsz_get_method..method)r7)rr(rAr)r(rrs rcCsh|] }d|qS)z__%s__r)rrArrrrsrrrr"r __prepare____instancecheck____subclasscheck____del__cCs t|S)N)r__hash__)rjrrrrrrcCs t|S)N)r__str__)rjrrrrrcCs t|S)N)r __sizeof__)rjrrrrr)rFrGrHry?g?) __lt____gt____le____ge____int__r__len__r __complex__ __float____bool__ __index__csfdd}|S)Ncs$jj}|tk r|S|kr dStS)NT)__eq__rwrNotImplemented)otherret_val)rjrrrSs z_get_eq..__eq__r)rjrSr)rjr_get_eqs rWcsfdd}|S)Ncs jjtk rtS|krdStS)NF)__ne__rwrrT)rU)rjrrrX s  z_get_ne..__ne__r)rjrXr)rjr_get_ne s rYcsfdd}|S)Ncs jj}|tkrtgSt|S)N)rrwrr)rV)rjrrrsz_get_iter..__iter__r)rjrr)rjr _get_iters rZ)rSrXrcCst|t}|tk r||_dSt|}|dk rdy ||}Wntk rXt|}YnX||_dSt|}|dk r|||_dS)N)_return_valuesrGrr]_calculate_return_valuer#_side_effect_methodsrc)r3rArZfixedZreturn_calulatorr]Z side_effectorrrr_set_return_value%s    r^c@seZdZddZddZdS) MagicMixincOs&|tt|j|||dS)N)_mock_set_magicsrr_r")rjr,rrrrr"=szMagicMixin.__init__cCst}t|dddk rTt|j}t}t|}x$|D]}|t|jkr4t||q4W|tt|j}t|}x|D]}t||t ||qtWdS)Nr) _magicsr> intersectionrrtrrFrr= MagicProxy)rjZ these_magicsZ remove_magicsrrrrrr`Cs   zMagicMixin._mock_set_magicsN)r7r:rmr"r`rrrrr_<sr_c@seZdZdZdddZdS)r z-A version of `MagicMock` that isn't callable.FcCs||||dS)zAdd 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)rr`)rjrrrrrr\s z"NonCallableMagicMock.mock_add_specN)F)r7r:rmr8rrrrrr Zsr c@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||||dS)zAdd 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)rr`)rjrrrrrrrs zMagicMock.mock_add_specN)F)r7r:rmr8rrrrrrgs rc@s.eZdZddZddZddZd dd ZdS) rccCs||_||_dS)N)rr)rjrrrrrr"~szMagicProxy.__init__cOs|}|||S)N) create_mock)rjr,r-mrrrr%szMagicProxy.__call__cCs8|j}|j}|j|||d}t|||t||||S)N)rrr)rrrr=r^)rjrrrerrrrds  zMagicProxy.create_mockNcCs|S)N)rd)rjrrrrrr4szMagicProxy.__get__)N)r7r:rmr"r%rdr4rrrrrc}s rcc@s(eZdZdZddZddZddZdS) _ANYz2A helper object that compares equal to everything.cCsdS)NTr)rjrUrrrrSsz _ANY.__eq__cCsdS)NFr)rjrUrrrrXsz _ANY.__ne__cCsdS)Nzr)rjrrrrksz _ANY.__repr__N)r7r:rmr8rSrXrkrrrrrfsrfcCsdd|}d}ddd|D}dddt|D}|rD|}|r\|rT|d7}||7}||S)Nz%s(%%s)rz, cSsg|] }t|qSr)repr)rrrrrrsz*_format_call_signature..cSsg|]\}}d||fqS)z%s=%rr)rrrurrrrs)rrr)rr,r-rZformatted_argsZ args_stringZ kwargs_stringrrrrsrc@sbeZdZdZdddZdd d Zd d ZejZd dZ ddZ ddZ ddZ ddZ ddZdS)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. rrNFTc Csd}i}t|}|dkr$|\}}}nr|dkrd|\} } t| trX| }t| trR| }qb| }q| | }}n2|dkr|\}t|tr|}nt|tr|}n|}|rt|||fSt||||fS)Nrrrfr)rrr&rCr) rrurrr from_kallr,r-_lenfirstsecondrrrrs.      z _Call.__new__cCs||_||_||_dS)N)r{ry_mock_from_kall)rjrurrrrhrrrr"sz_Call.__init__c Csf|tkr dSy t|}Wntk r,dSXd}t|dkrH|\}}n |\}}}t|ddrzt|ddrz|j|jkrzdSd}|dkrdi}}n|dkr|\}}}n|d kr|\} t| tr| }i}n"t| tr| }di}}nd}| }nV|dkr>|\} } t| tr2| }t| tr&| i}}n d| }}n | | }}ndS|rV||krVdS||f||fkS) NTFrrfryrrrr)rrrr>ryrrCr&) rjrUZ len_otherZ self_nameZ self_argsZ self_kwargsZ other_nameZ other_argsZ other_kwargsrurjrkrrrrSsP                z _Call.__eq__cOs<|jdkrtd||fddS|jd}t|j||f||dS)Nrz())r)rr)r{r)rjr,r-rrrrr%*s  z_Call.__call__cCs2|jdkrt|ddSd|j|f}t||ddS)NF)rrhz%s.%s)rrrh)r{r)rjr rrrrrr2s  z_Call.__getattr__cOs|d||S)Nr)rr)rjr,r-rrrr9sz _Call.countcOs|d||S)Nindex)rr)rjr,r-rrrrm<sz _Call.indexcCs||js&|jpd}|dr"d|}|St|dkr@d}|\}}n0|\}}}|sTd}n|dshd|}nd|}t|||S)Nrz()zcall%srfzcall.%s)rlr{rrr)rjrr,r-rrrrk?s       z_Call.__repr__cCs8g}|}x"|dk r*|jr"|||j}q Wtt|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)rlrryrYr)rjZvalsrrrr call_listTs   z_Call.call_list)rrNFT)rNNFT)r7r:rmr8rr"rSrrXr%rrrrmrkrnrrrrrs  7r)rhc Ks$t|rt|}t|t}d|i}|r0d|i}n |dkrr#rr3 _must_skipr=)rrr5rrr-is_typerrrr3rrMrrr4rrrrest                     rcCs|t|ts$|t|dikrdS|j}xR|jD]H}|j|t}|tkrHq,t|tt frZdStt|ddt rp|SdSq,W|S)z[ Return whether we should skip the first argument on spec's `entry` attribute. rFFr4N) rrr>rrErFrGr staticmethod classmethodMethodWrapperTypes)rrrprrNrrrros  rocCs$y|jStk rt|SXdS)N)rr#r)rrrrrsrc@seZdZdddZdS)rFNcCs(||_||_||_||_||_||_dS)N)ridsrrr5r)rjrrrrrtr5rrrr" s z_SpecState.__init__)FNNNF)r7r:rmr"rrrrr src#spt|trdndfdd|D}|dkrD|dd}n|ddd|d<x|D] }|Vq^WdS)N  csg|] }|qSrr)rl)seprrr! sz&_iterate_read_data..)rbytesr) read_dataZ data_as_listliner)rxr_iterate_read_data s  r}rcsfdd}fdd}fddfddtd krld d l}ttt|jtt|ja|d krtd t d }ttd j _ t d gd j _ d j_ d j_ d j_ |j_d<dj_|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. cs jjdk rjjStdS)Nr) readlinesr]rB)r,r-)_statehandlerr_readlines_side_effect= s z)mock_open.._readlines_side_effectcs(jjdk rjjStdS)Nr)readr]rr)r,r-)rrr{rr_read_side_effectB s z$mock_open.._read_side_effectc3s"EdHxtVqWdS)N)rr)_iter_side_effectr{rr_readline_side_effectG s z(mock_open.._readline_side_effectc3s8jjdk rxjjVqWxdD] }|Vq&WdS)Nr)readliner])r|)rrrrrL s  z$mock_open.._iter_side_effectNropen)rr)rrcs6td<jjdkr2d<dj_tS)Nrr)r}rrcr)r,r-)rrrr{rr reset_datak s    zmock_open..reset_data) file_spec_iorBrtr TextIOWrapperunionBytesIOrrr r]r}writerrr~rcr)r3r{rrrrr)rrrrr{rr 1 s2 "     r c@s(eZdZdZddZddZddZdS) r aW 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|S)N)r)rjr-rrrr szPropertyMock._get_child_mockcCs|S)Nr)rjrZobj_typerrrr4 szPropertyMock.__get__cCs ||dS)Nr)rjrrrrrr5 szPropertyMock.__set__N)r7r:rmr8rr4r5rrrrr x sr c Cs`d|_xTt|D]H}yt||}Wntk r8wYnXt|tsFq|j|krt|qWdS)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#rr rzr)r3r rerrrr s   r)F)F)NFNNN)FFNN)Nr)p__all__ __version__r&rrbuiltinstypesr functoolsrrrr BaseExceptionr platformrZlangZ Throwabler rrrr!r)r6r0rArDrIrQrLrhrrirnrrMISSINGrZDELETEDrrvrrrBrYrrrr rrrrrrrr$r%r'rr(r/r1rsZmultipleZstopallr Z magic_methodsZnumericsrrZinplacerightZ _non_defaultsrrarrr\rTr[rWrYrZr]r^r_r rrcrfrrrCrrrrorrrrSr$r4rsrr}r r rrrrrs      5 !)i5 ,   1Jv        ,  w  G