B Tt|@s\dZdZddlZddlZddlZddlZddlZddlZddlm Z m Z ddl m Z m Z ddeeDZefZdejkrddlZeejjfZd ZeZd d Zd d ZddZddZdddZddZddZddZ ddZ!dddZ"dd 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(Z.d)d*d+d,d-d.d/d0hZ/d1d2Z0Gd3d4d4e1Z2d5d6Z3Gd7d8d8e%Z4Gd9d:d:e%Z5Gd;d<dZ7Gd?d@d@e5Z8GdAdBdBe8e6Z9dCdDZ:dEdFZ;dGdHZe)dddddfdMdNZ?ddOdPZ@e)dddddfdQdRZAGdSdTdTe%ZBdUdVZCdWdXZDe?eA_%eBeA_Ee@eA_FeDeA_GdYeA_HdZZId[ZJd\Kd]d^eJLDZMd\Kd_d^eJLDZNd`dadbdcdddedfdgdhdidjdkdldmdndodpdqhZOdrdsZPdtdd\KeIeJeMeNgLDZQeQeOBZRdudvdwdxdydzd{d|hZSd}d~dd~dd~dZTeUeUeUeUddddddd dd ZVddZWddZXddZYeWeXeYdZZddZ[Gddde%Z\Gddde\e6Z]Gddde\e9Z^Gddde%Z_Gddde%Z`e`ZaddZbGdddecZdedddZedddZfddZgddZhGddde%ZiejefejeajkfZldamddZndddZoGddde9ZpddZqdS))Mock MagicMockpatchsentinelDEFAULTANYcallcreate_autospec FILTER_DIRNonCallableMockNonCallableMagicMock mock_open PropertyMocksealz1.0N) ModuleType MethodType)wrapspartialcCsh|]}|ds|qS)_) startswith).0namer2/opt/alt/python37/lib64/python3.7/unittest/mock.py &srjavaTcCstt|tS)N) issubclasstyper )objrrr_is_instance_mock5srcCst|tpt|tot|tS)N) isinstanceBaseExceptionsrr)rrrr _is_exception;s r"cCs"t|trt|dr|jS|SdS)Nmock)r FunctionTypeshasattrr#)rrrr _extract_mockBsr&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) r r__init__AttributeErrorr$__call__rinspectZ signature ValueError)funcZ as_instanceZeat_selfZsig_funcrrr_get_signature_objectKs$    r-FcsNt|||dkrdS\}fdd}t|||t|_t|_dS)Ncsj||dS)N)bind) _mock_selfargskwargs)sigrrchecksigpsz"_check_signature..checksig)r-_copy_func_detailsr_mock_check_sig __signature__)r,r# skipfirstinstancer3r)r2r_check_signatureks    r9c Cs>x8dD]0}yt||t||Wqtk r4YqXqWdS)N)__name____doc____text_signature__ __module__ __defaults____kwdefaults__)setattrgetattrr()r,funcopy attributerrrr4ws r4cCs@t|trdSt|tttfr(t|jSt|dddk r.checksigrB)Z _checksig_r#zYdef %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs)) rFr rr-r4r: isidentifierexec _setup_func) r#originalr8r7resultr,r3rcontextsrcrBr)r2r_set_signatures$       rWc 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)r0r1)r#rrrXsz'_setup_func..assert_called_withcs j||S)N) assert_called)r0r1)r#rrrYsz"_setup_func..assert_calledcs j||S)N)assert_not_called)r0r1)r#rrrZsz&_setup_func..assert_not_calledcs j||S)N)assert_called_once)r0r1)r#rrr[sz'_setup_func..assert_called_oncecs j||S)N)assert_called_once_with)r0r1)r#rrr\sz,_setup_func..assert_called_once_withcs j||S)N)assert_has_calls)r0r1)r#rrr]sz%_setup_func..assert_has_callscs j||S)N)assert_any_call)r0r1)r#rrr^sz$_setup_func..assert_any_callcs:t_t_j}t|r6|k r6|dS)N) _CallList method_calls mock_calls reset_mock return_valuer)ret)rBr#rrrbs z_setup_func..reset_mockFr)r#rcalled call_count call_argsr_call_args_listr`rarc side_effect_mock_childrenrXr\r]r^rbrYrZr[r6_mock_delegate) rBr#r2rXrYrZr[r\r]r^rbr)rBr#rrRs<       rRcCsd|dd|kS)Nz__%s__r)rrrr _is_magicsrnc@s(eZdZdZddZddZddZdS) _SentinelObjectz!A unique, named, sentinel object.cCs ||_dS)N)r)selfrrrrr'sz_SentinelObject.__init__cCs d|jS)Nz sentinel.%s)r)rprrr__repr__sz_SentinelObject.__repr__cCs d|jS)Nz sentinel.%s)r)rprrr __reduce__sz_SentinelObject.__reduce__N)r:r= __qualname__r;r'rqrrrrrrrosroc@s(eZdZdZddZddZddZdS) _SentinelzAAccess attributes to return a named object, usable as a sentinel.cCs i|_dS)N) _sentinels)rprrrr'sz_Sentinel.__init__cCs|dkr t|j|t|S)N __bases__)r(ru setdefaultro)rprrrr __getattr__ sz_Sentinel.__getattr__cCsdS)Nrr)rprrrrrsz_Sentinel.__reduce__N)r:r=rsr;r'rxrrrrrrrtsrtcCs$t|ttttfkr t||S|S)N)rdictrHrIset)valuerrr_copys r|rc_mock_return_valueri_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)rkrA)rpr _the_namer2rrr_get+s z"_delegating_property.._getcSs*|j}|dkr||j|<n t|||dS)N)rkrLr@)rpr{rrr2rrr_set0s z"_delegating_property.._set)_allowed_namesaddproperty)rrrrrrr_delegating_property(s  rc@seZdZddZddZdS)r_cCsnt|tst||St|}t|}||kr2dSx6td||dD] }||||}||krFdSqFWdS)NFrT)r rH __contains__lenrange)rpr{Z len_valueZlen_selfiZsub_listrrrr=s  z_CallList.__contains__cCstt|S)N)pprintZpformatrH)rprrrrqKsz_CallList.__repr__N)r:r=rsrrqrrrrr_;sr_cCst|}t|sdS|js4|js4|jdk s4|jdk r8dS|}x|dk rZ||krRdS|j}q>W|rl||_||_|r|||_||_dS)NFT)r&rrrrr)parentr{rnew_name_parentrrr_check_and_set_parentOs&     rc@s$eZdZddZddZddZdS) _MockItercCst||_dS)N)iterr)rprrrrr'ksz_MockIter.__init__cCs|S)Nr)rprrr__iter__msz_MockIter.__iter__cCs t|jS)N)nextr)rprrr__next__osz_MockIter.__next__N)r:r=rsr'rrrrrrrjsrc@seZdZeZdZddZdS)BaseNcOsdS)Nr)rpr0r1rrrr'usz Base.__init__)r:r=rsrr}r~r'rrrrrrsrc @sXeZdZdZddZdHddZd d ZdId d ZdJd dZddZ ddZ dZ e e e e Z e ddZedZedZedZedZedZddZddZe eeZdKdddd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Z d2d3Z!d4d5Z"d6d7Z#d8d9Z$d:d;Z%dd?Z'd@dAZ(dLdBdCZ)dDdEZ*dFdGZ+dS)Mr z A non-callable version of `Mock`cOs$t|j|fd|ji}t|}|S)Nr;)rr:r;object__new__)clsr0kwnewr8rrrr}s 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_sealedTrj _mock_wrapsrkZ _mock_calledZ_mock_call_argsrZ_mock_call_countZ_mock_call_args_listZ_mock_mock_callsr` _mock_unsafe)rL_mock_add_specr_configure_mock _safe_superr r')rpspecrrspec_setr _spec_state _new_name _new_parent_spec_as_instance _eat_selfZunsafer1rLrrrr's:      zNonCallableMock.__init__cCs0t|}d|_d|_d|_d|_t|||dS)z Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the `method_calls` and `mock_calls` attributes of this one.Nr)r&rrrrr@)rpr#rCZ inner_mockrrr 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)rprrrrr 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)rJr r _get_classr-dirrL) rprrrrrrZresrLrrrrs  zNonCallableMock._mock_add_speccCs8|j}|jdk r|jj}|tkr4|j|dd}||_|S)Nz())rr)r}rkrcr_get_child_mock)rprdrrrZ__get_return_values  z"NonCallableMock.__get_return_valuecCs,|jdk r||j_n||_t||dddS)Nz())rkrcr}r)rpr{rrrZ__set_return_values  z"NonCallableMock.__set_return_valuez1The value to be returned when the mock is called.cCs|jdkrt|S|jS)N)rr)rprrr __class__s zNonCallableMock.__class__rerfrgrhracCsN|j}|dkr|jS|j}|dk rJt|sJt|tsJt|sJt|}||_|S)N)rkr~ricallabler rr")rp delegatedZsfrrrZ__get_side_effectsz!NonCallableMock.__get_side_effectcCs(t|}|j}|dkr||_n||_dS)N) _try_iterrkr~ri)rpr{rrrrZ__set_side_effects z!NonCallableMock.__set_side_effect)rcricCs|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)idappendrergrfr_rarhr`rr}r~rjvaluesr _SpecState_deletedrbr)rpZvisitedrcrichildrdrrrrbs, 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)entryrrrIz0NonCallableMock.configure_mock..)keyrN)sorteditemssplitpoprAr@)rpr1argvalr0finalrrrrrr<s   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_magicsrnrrrjrMrrrArr rrrrr8rr)rprrTrrrrrxRs6            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()rr#r)z()z().r) rrrzrrrrHreversedrrjoin)rpZ _name_listrZlastdotseenZ_firstrrr_extract_mock_namexs0        z"NonCallableMock._extract_mock_namecCs^|}d}|dkrd|}d}|jdk rDd}|jr8d}||jj}dt|j||t|fS)Nr)r#zmock.z name=%rz spec=%rz spec_set=%rz<%s%s%s id='%s'>)rrrr:rr)rprZ name_stringZ spec_stringrrrrqs  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_valuerrr sz+NonCallableMock.__dir__..cSsg|]}|ds|qS)r)r)rerrrrscSs"g|]}|drt|r|qS)r)rrn)rrrrrrs ) r r__dir__rrrrHrLrjrrrz)rpZextrasZ 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||S)Nr)r0r)rSrprrrrz-NonCallableMock.__setattr__..rrz Cannot set )rr __setattr__rrrLr(_unsupported_magicsrrr@r _get_methodrrjrrr%r)rprr{msg mock_namer)rSrprrs8      zNonCallableMock.__setattr__cCs|tkr2|t|jkr2tt||||jkr2dS|j|t}||jkr\tt| |n|t krlt ||tk r||j|=t |j|<dS)N) rrrLdelattrrjrM_missingrr __delattr__rr()rprrrrrrs  zNonCallableMock.__delattr__cCs|jpd}t|||S)Nr#)r_format_call_signature)rpr0r1rrrr_format_mock_call_signatures z+NonCallableMock._format_mock_call_signaturecCsDd}|||}|j}t|dkr.|dd}|j|}|||fS)Nz!Expected call: %s Actual call: %sr)rrgr)rpr0r1messageexpected_stringrgZ actual_stringrrr_format_mock_failure_messages    z,NonCallableMock._format_mock_failure_messagecCsl|s |jSd}|ddd}|j}x@|D]8}||}|dksLt|trPPq,t|}|j}|j}q,W|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. Nz()rr)rreplacerrjrMr rr&)rprr2namesZchildrenrrrr_get_call_signature_from_names    z-NonCallableMock._get_call_signature_from_namec Cst|tr&t|dkr&||d}n|j}|dk rt|dkrNd}|\}}n |\}}}y||j||fStk r}z |dSd}~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. rlrNr)r rIrrrr. TypeErrorwith_traceback)rp_callr2rr0r1rrrr _call_matcher(s   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.r#N)rfrAssertionError)r/rprrrrrZBs  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.r#N)rfrr)r/rprrrrrYKs   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.r#N)rfrr)r/rprrrrr[Ts  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)r0r1rprr_error_messagegs z:NonCallableMock.assert_called_with.._error_message)rgrrrr Exception)r/r0r1expectedractualcauser)r0r1rprrX]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.r#)rfrrrX)r/r0r1rprrrrr\qs  z'NonCallableMock.assert_called_once_withc sfdd|D}tdd|Dd}tfddjD}|s||kr|dkrXd}ndd d|D}td |t|jf|dSt|}g}x:|D]2}y||Wqtk r||YqXqW|rtd t |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)rprrrsz4NonCallableMock.assert_has_calls..css|]}t|tr|VqdS)N)r r)rrrrr sz3NonCallableMock.assert_has_calls..Nc3s|]}|VqdS)N)r)rr)rprrrszCalls not found.z+Error processing expected calls. Errors: {}cSsg|]}t|tr|ndqS)N)r r)rrrrrrsz%s Expected: %r Actual: %rz%r not all found in call list) rr_raformatrrHremover+rrI) rpZcallsZ any_orderrrZ all_callsZproblemZ not_foundZkallr)rprr]|s4   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)rprrrsz3NonCallableMock.assert_any_call..Nz%s call not found)rrhr rrr)rpr0r1rrrrr)rprr^s zNonCallableMock.assert_any_callcKsxt|}t|ts2t|tr"t}q.) rrrCrrr rr rr1attribute_namer )rprrrrr sz _patch.copycCst|tr||S||S)N)r rdecorate_classdecorate_callable)rpr,rrrr)s  z_patch.__call__cCsRxLt|D]@}|tjsq t||}t|ds2q |}t||||q W|S)Nr))rrr TEST_PREFIXrAr%r r@)rprattr attr_valuerrrrrs   z_patch.decorate_classcs<tdrj|Stfdd|g_S)N patchingsc srg}t\}xBjD]8}||}|jdk r:||q|jtkr||qW|t |7}||SQRXdS)N) contextlib ExitStackr enter_contextrupdaterrrrI)r0Zkeywargs extra_args exit_stackpatchingr)r,patchedrrrs       z)_patch.decorate_callable..patched)r%rrr)rpr,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) rrCrrLr(KeyErrorrA _builtinsr rr )rprrrSlocalrrr get_originalsz_patch.get_originalcCsn|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|_yrt |j|j||j!dk rHi}|jt kr|||j!<x2|j"D](}|j#|}|jt kr||qW|S|S|j$t%&sdYnXdS)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)'rrrr r1rrrrr rr rrrJrr rr rCrrrOrrcboolr temp_originalrrr _exit_stackr@rr r__exit__sysexc_info)rprrrr r1rrSrZinheritKlass_kwargsZ this_specZ not_callableZnew_attrrrrrrr __enter__s                                z_patch.__enter__cGst|std|jr4|jtk r4t|j|j|jn>t|j|j|j srt |j|jr`|jdkrrt|j|j|j|`|`|`|j }|` |j |S)zUndo the patch.z stop called on unstarted patcher)r;r=r>__annotations__r?) r RuntimeErrorrr#rr@rrCrr r%r$r%)rpr'rrrrr%s z_patch.__exit__cCs|}|j||S)z-Activate a patch, returning any created mock.)r*_active_patchesr)rprTrrrstarts z _patch.startcCs4y|j|Wntk r$YnX|dddS)zStop an active patch.N)r-rr+r%)rprrrstops z _patch.stop)r:r=rsrr-r'r r)rrr r*r%r.r/rrrrrs rc sPydd\}Wn&ttfk r:tdfYnXfdd}||fS)Nrrz.Need a valid target to patch. You supplied: %rcstS)N)rr)rrrrrz_get_target..)rsplitrr+)rrCrr)rr _get_targets r1c 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 strcsS)Nrr)rrrrrz_patch_object..)rstrrr) rrCrrr rr rr1rr)rr _patch_objects    r3c 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) rr2r+rHrrrr r) rrr rr rr1rrrCrrZ this_patcherr)rr_patch_multiples&        r4c 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. )r1r) rrrr rr rr1rrCrrrr sE  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_dictryrrclear _original)rpr6rr7r1rrrr'ts   z_patch_dict.__init__cs.ttrStfdd}|S)Ncs"z ||SXdS)N)r5 _unpatch_dict)r0r)frprr_inners z$_patch_dict.__call__.._inner)r rrr)rpr:r;r)r:rprr)}s  z_patch_dict.__call__cCs\xVt|D]J}t||}|tjr t|dr t|j|j|j }||}t |||q W|S)Nr)) rrArrrr%r5r6rr7r@)rprrrZ decoratorZ decoratedrrrrs   z_patch_dict.decorate_classcCs |dS)zPatch the dict.N)r5)rprrrr*sz_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) rr r6r2rr7r r(r8 _clear_dictr)rprr6r7rSrrrrr5s&     z_patch_dict._patch_dictcCsV|j}|j}t|y||Wn.tk rPx|D]}||||<q8WYnXdS)N)r6r8r<rr()rpr6rSrrrrr9s z_patch_dict._unpatch_dictcGs |dS)zUnpatch the dict.F)r9)rpr0rrrr%sz_patch_dict.__exit__N)rF) r:r=rsr;r'r)rr*r5r9r%r.r/rrrrr5Ws   r5cCsBy |Wn0tk r<t|}x|D] }||=q*WYnXdS)N)r7r(rH)r6keysrrrrr<s   r<cCs xttjD] }|q WdS)z7Stop all active patches. LIFO to unroll nested patches.N)rrr-r/)rrrr_patch_stopallsr>Ztestzlt 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)rr@rrrrs__get____set__ __delete__ __reversed__ __missing__rr __reduce_ex__Z__getinitargs____getnewargs__ __getstate__ __setstate__ __getformat__Z __setformat__rqr__subclasses__ __format____getnewargs_ex__csfdd}||_|S)z:Turns a callable object (like a mock) into a real functioncs|f||S)Nr)rpr0r)r,rrmethodsz_get_method..method)r:)rr,rNr)r,rrs rcCsh|] }d|qS)z__%s__r)rrNrrrr srxrr'r __prepare____instancecheck____subclasscheck____del__cCs t|S)N)r__hash__)rprrrrrrcCs t|S)N)r__str__)rprrrrrcCs t|S)N)r __sizeof__)rprrrrr)rSrTrUry?g?) __lt____gt____le____ge____int__r__len__r% __complex__ __float____bool__ __index__csfdd}|S)Ncs$jj}|tk r|S|kr dStS)NT)__eq__r}rNotImplemented)otherret_val)rprrr`0s z_get_eq..__eq__r)rpr`r)rpr_get_eq/s rdcsfdd}|S)Ncs jjtk rtS|krdStS)NF)__ne__r}rra)rb)rprrre:s  z_get_ne..__ne__r)rprer)rpr_get_ne9s rfcsfdd}|S)Ncs jj}|tkrtgSt|S)N)rr}rr)rc)rprrrCsz_get_iter..__iter__r)rprr)rpr _get_iterBs rg)r`rercCst|t}|tk r||_dSt|}|dk rdy ||}Wntk rXt|}YnX||_dSt|}|dk r|||_dS)N)_return_valuesrMrrc_calculate_return_valuer(_side_effect_methodsri)r#rNrZfixedZreturn_calculatorrcZ side_effectorrrr_set_return_valueTs    rkc@seZdZddZddZdS) MagicMixincOs&|tt|j|||dS)N)_mock_set_magicsrrlr')rpr0rrrrr'lszMagicMixin.__init__cCst}t|dddk rTt|j}t}t|}x$|D]}|t|jkr4t||q4W|tt|j}t|}x|D]}t||t ||qtWdS)Nr) _magicsrA intersectionrrzrrLrr@ MagicProxy)rpZ these_magicsZ remove_magicsrrrrrrmrs   zMagicMixin._mock_set_magicsN)r:r=rsr'rmrrrrrlksrlc@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)rrm)rprrrrrrs z"NonCallableMagicMock.mock_add_specN)F)r:r=rsr;rrrrrr sr 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)rrm)rprrrrrrs zMagicMock.mock_add_specN)F)r:r=rsr;rrrrrrs rc@s.eZdZddZddZddZd dd ZdS) rpcCs||_||_dS)N)rr)rprrrrrr'szMagicProxy.__init__cOs|}|||S)N) create_mock)rpr0r1mrrrr)szMagicProxy.__call__cCs8|j}|j}|j|||d}t|||t||||S)N)rrr)rrrr@rk)rprrrrrrrrqs  zMagicProxy.create_mockNcCs|S)N)rq)rprrrrrrAszMagicProxy.__get__)N)r:r=rsr'r)rqrArrrrrps rpc@s(eZdZdZddZddZddZdS) _ANYz2A helper object that compares equal to everything.cCsdS)NTr)rprbrrrr`sz _ANY.__eq__cCsdS)NFr)rprbrrrresz _ANY.__ne__cCsdS)Nzr)rprrrrqsz _ANY.__repr__N)r:r=rsr;r`rerqrrrrrssrscCsdd|}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)rrr{rrrrs)rrr)rr0r1rZformatted_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)Nrrrlr)rr r2rIr) rr{rrr from_kallr0r1_lenfirstsecondrrrrs.      z _Call.__new__cCs||_||_||_dS)N)rr_mock_from_kall)rpr{rrrrurrrr'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) NTFrrlrrrrr)rrrrArr rIr2) rprbZ len_otherZ self_nameZ self_argsZ self_kwargsZ other_nameZ other_argsZ other_kwargsr{rwrxrrrr`sP                z _Call.__eq__cOs<|jdkrtd||fddS|jd}t|j||f||dS)Nrz())r)rr)rr)rpr0r1rrrrr)Ys  z_Call.__call__cCs2|jdkrt|ddSd|j|f}t||ddS)NF)rruz%s.%s)rrru)rr)rprrrrrrxas  z_Call.__getattr__cOs|d||S)Nr)rx)rpr0r1rrrrhsz _Call.countcOs|d||S)Nindex)rx)rpr0r1rrrrzksz _Call.indexcCs||js&|jpd}|dr"d|}|St|dkr@d}|\}}n0|\}}}|sTd}n|dshd|}nd|}t|||S)Nrz()zcall%srlzcall.%s)ryrrrr)rprr0r1rrrrqns       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)ryrrr_r)rpZvalsrrrr call_lists   z_Call.call_list)rrNFT)rNNFT)r:r=rsr;rr'r`rrer)rxrrzrqr{rrrrrs  7r)ruc Ks$t|rt|}t|t}d|i}|r0d|i}n |dkr._readlines_side_effectcs$jjdk rjjSdj||S)Nr)readrc)r0r1)rrrr_read_side_effectc s z$mock_open.._read_side_effectc?s(EdHxdj||VqWdS)Nr)readline)r0r1)_iter_side_effectrrr_readline_side_effecth s z(mock_open.._readline_side_effectc3s8jjdk rxjjVqWxdD] }|Vq&WdS)Nr)rrc)line)rrrrrm s  z$mock_open.._iter_side_effectcs jjdk rjjStdS)Nr)rrcrr)rrrr_next_side_effectt s z$mock_open.._next_side_effectropen)rr)rrcs6td<jjdkr2d<dj_tS)Nrr)rrrir)r0r1)rrrrrr reset_data s    zmock_open..reset_data)r file_spec_iorHrzr TextIOWrapperunionrrrr*rcwriterrrrirr)r#rZ _read_datarrrrrr)rrrrrrr O s8 "    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)rpr1rrrr szPropertyMock._get_child_mockcCs|S)Nr)rprZobj_typerrrrA szPropertyMock.__get__cCs ||dS)Nr)rprrrrrrB szPropertyMock.__set__N)r:r=rsr;rrArBrrrrr 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)rrrAr(r r rr)r#rrrrrrr s   r)F)F)NFNNN)FFNN)Nr)r__all__ __version__rr*rr&builtinsrtypesrr functoolsrrrr BaseExceptionr!platformrZlangZ Throwabler superrrr"r&r-r9r4rFrJrOrWrRrnrrortrrMISSINGrZDELETEDrr|rrrHr_rrrr rrrrrrrr1r3r4rr5r<r>ryZmultipleZstopallrZ magic_methodsZnumericsrrZinplacerightZ _non_defaultsrrnrrrirarhrdrfrgrjrkrlr rrprsrrrIrrrr|rrrr`r$rrr r rrrrrs        5 Zi5    1Jv        ,  w  N