3 \7@sFdZd ZddlZddlZddlZddlZddlmZddlm Z m Z dde eDZ e fZdejkrzddlZe ejjfZdZeZddZddZddZdddZdd Zd!d"Zd#d$Zd%d&Zdd'd(Zd)d*Zd+d,Z Gd-d.d.e!Z"Gd/d0d0e!Z#e#Z$e$j%Z%e$j&Z'e$j(Z)d1d2Z*d3d4d5d6d7d8d9d:hZ+d;d<Z,Gd=d>d>e-Z.d?d@Z/GdAdBdBe!Z0GdCdDdDe!Z1GdEd d e1Z2dFdGZ3GdHdIdIe1Z4GdJdde4e2Z5dKdLZ6dMdNZ7dOdPZ8GdQdRdRe!Z9dSdTZ:e%dddddfdUdVZ;ddWdXZd\d]Z?d^d_Z@e;e=_!e>e=_Ae#srjavaTcCstt|tS)N) issubclasstyper )objrrr_is_instance_mock2srcCst|tpt|tot|tS)N) isinstanceBaseExceptionsrr)rrrr _is_exception8s r cCst|tr6| r6y |j}Wntk r.dSXd}n*t|ts`y |j}Wntk r^dSX|rpt|d}n|}y|tj|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(FcsDt|||dkrdS\}fdd}t|||t|_dS)Ncsj||dS)N)bind) _mock_selfargskwargs)sigrrchecksigdsz"_check_signature..checksig)r(_copy_func_detailsr_mock_check_sig)r'mock skipfirstinstancer.r)r-r_check_signature_s   r4c#Cs|j|_|j|_y |j|_Wntk r0YnXy |j|_Wntk rRYnXy |j|_Wntk rtYnXy |j|_Wntk rYnXdS)N)__name____doc____text_signature__r" __module__ __defaults____kwdefaults__)r'funcopyrrrr/js$    r/cCs&t|trdSt|dddk r"dSdS)NTr$F)rrgetattr)rrrr _callables  r=cCst|ttfkS)N)rlisttuple)rrrr_is_listsr@cCsHt|tst|dddk Sx(|f|jD]}|jjddk 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  rEc st|s dSt|t}t|||}|dkr.|S|\}fdd}t|||j}|js^d}||d}d|} t| |||} t| || S)Ncsj||dS)N)r))r+r,)r-rrr.sz _set_signature..checksigr;)Z _checksig_r1zYdef %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs)) r=rrr(r/r5 isidentifierexec _setup_func) r1originalr3r2resultr'r.rcontextsrcr;r)r-r_set_signatures$       rMc 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,)r1rrrNsz'_setup_func..assert_called_withcs j||S)N) assert_called)r+r,)r1rrrOsz"_setup_func..assert_calledcs j||S)N)assert_not_called)r+r,)r1rrrPsz&_setup_func..assert_not_calledcs j||S)N)assert_called_once)r+r,)r1rrrQsz'_setup_func..assert_called_oncecs j||S)N)assert_called_once_with)r+r,)r1rrrRsz,_setup_func..assert_called_once_withcs j||S)N)assert_has_calls)r+r,)r1rrrSsz%_setup_func..assert_has_callscs j||S)N)assert_any_call)r+r,)r1rrrTsz$_setup_func..assert_any_callcs:t_t_jj}t|r6|k r6|jdS)N) _CallList method_calls mock_calls reset_mock return_valuer)ret)r;r1rrrXs z_setup_func..reset_mockFr)r1rcalled call_count call_argsrUcall_args_listrVrWrY side_effect_mock_childrenrNrRrSrTrXrOrPrQ_mock_delegate) r;r1rNrOrPrQrRrSrTrXr)r;r1rrHs:       rHcCsd|dd|kS)Nz__%s__r)rrrr _is_magicsrdc@s eZdZdZddZddZdS)_SentinelObjectz!A unique, named, sentinel object.cCs ||_dS)N)r)selfrrrrr!sz_SentinelObject.__init__cCs d|jS)Nz sentinel.%s)r)rfrrr__repr__sz_SentinelObject.__repr__N)r5r8 __qualname__r6r!rgrrrrresrec@s eZdZdZddZddZdS) _SentinelzAAccess attributes to return a named object, usable as a sentinel.cCs i|_dS)N) _sentinels)rfrrrr!sz_Sentinel.__init__cCs|dkr t|jj|t|S)N __bases__)r"rj setdefaultre)rfrrrr __getattr__sz_Sentinel.__getattr__N)r5r8rhr6r!rmrrrrrisricCs$t|ttttfkr t||S|S)N)rdictr>r?set)valuerrr_copys rqrY_mock_return_valuer__mock_side_effect _mock_parent_mock_new_parent _mock_name_mock_new_namecCs8tj|d|}||fdd}||fdd}t||S)NZ_mock_cSs"|j}|dkrt||St||S)N)rar<)rfr _the_namer-rrr_gets z"_delegating_property.._getcSs*|j}|dkr||j|<n t|||dS)N)rarBsetattr)rfrprrxr-rrr_set$s z"_delegating_property.._set)_allowed_namesaddproperty)rrxryr{rrr_delegating_propertys  rc@seZdZddZddZdS)rUcCsnt|tstj||St|}t|}||kr2dSx6td||dD] }||||}||krFdSqFWdS)NFrT)rr> __contains__lenrange)rfrpZ len_valueZlen_selfiZsub_listrrrr1s  z_CallList.__contains__cCstjt|S)N)pprintZpformatr>)rfrrrrg?sz_CallList.__repr__N)r5r8rhrrgrrrrrU/srUcCsxt|s dS|js,|js,|jdk s,|jdk r0dS|}x|dk rR||krJdS|j}q6W|rd||_||_|rt||_||_dS)NFT)rrvrwrtru)parentrprnew_name_parentrrr_check_and_set_parentCs$     rc@s$eZdZddZddZddZdS) _MockItercCst||_dS)N)iterr)rfrrrrr!]sz_MockIter.__init__cCs|S)Nr)rfrrr__iter___sz_MockIter.__iter__cCs t|jS)N)nextr)rfrrr__next__asz_MockIter.__next__N)r5r8rhr!rrrrrrr\src@seZdZeZdZddZdS)BaseNcOsdS)Nr)rfr+r,rrrr!gsz Base.__init__)r5r8rhrrrrsr!rrrrrdsrc @sHeZdZdZddZdDddZd d ZdEd d ZdFd dZddZ ddZ dZ e e e e Z e ddZedZedZedZedZedZddZddZe eeZdGdddd 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(dBdCZ)dS)Ir z A non-callable version of `Mock`cOs$t|j|fd|ji}tj|}|S)Nr6)rr5r6object__new__)clsr+kwnewr3rrrros zNonCallableMock.__new__NFc Ks|dkr |}|j} || d<|| d<|| d<|| d<|dk rB|}d}| dkrR|dk } |j||| | i| d<|| d<d| d<d | d <d| d <d | d <t| d<t| d<t| d<| | d<| r|jf| tt|j||||||dS)NrtrvrwruTr` _mock_wrapsraFZ _mock_calledZ_mock_call_argsrZ_mock_call_countZ_mock_call_args_listZ_mock_mock_callsrV _mock_unsafe)rB_mock_add_specrUconfigure_mock _safe_superr r!)rfspecrrspec_setr _spec_state _new_name _new_parent_spec_as_instance _eat_selfZunsafer,rBrrrr!xs8      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)rtrurvrwrz)rfr1 attributerrr attach_mocks zNonCallableMock.attach_mockcCs|j||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)rfrrrrr mock_add_specszNonCallableMock.mock_add_specc Cs|d}d}|dk rRt| rRt|tr*|}nt|}t|||}|oH|d}t|}|j}||d<||d<||d<||d<dS)Nr _spec_class _spec_set_spec_signature _mock_methods)r@rr _get_classr(dirrB) rfrrrrrrresrBrrrrs  zNonCallableMock._mock_add_speccCs8|j}|jdk r|jj}|tkr4|j|dd}||_|S)Nz())rr)rrrarYr_get_child_mock)rfrZrrrZ__get_return_values  z"NonCallableMock.__get_return_valuecCs,|jdk r||j_n||_t||dddS)Nz())rarYrrr)rfrprrrZ__set_return_values  z"NonCallableMock.__set_return_valuez1The value to be returned when the mock is called.cCs|jdkrt|S|jS)N)rr)rfrrr __class__s zNonCallableMock.__class__r[r\r]r^rWcCsT|j}|dkr|jS|j}|dk rPt| rPt|t rPt| rPt|}||_|S)N)rarsr_callablerrr )rf delegatedZsfrrrZ__get_side_effectsz!NonCallableMock.__get_side_effectcCs(t|}|j}|dkr||_n||_dS)N) _try_iterrarsr_)rfrprrrrZ__set_side_effects z!NonCallableMock.__set_side_effect)rYr_cCs|dkr g}t||krdS|jt|d|_d|_d|_t|_t|_t|_|r^t |_ |rhd|_ x0|j j D]"}t|tst|tkrqt|j|qtW|j }t|r||k r|j|dS)z-Restore the mock object to its initial state.NFr)idappendr[r]r\rUrWr^rVrrrrsr`valuesr _SpecState_deletedrXr)rfZvisitedrYr_ZchildrZrrrrX s, zNonCallableMock.reset_mockcKs`xZt|jdddD]B\}}|jd}|j}|}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|djdS)Nr.)count)entryrrr8sz0NonCallableMock.configure_mock..)keyrN)sorteditemssplitpopr<rz)rfr,argvalr+finalrrrrrr+s   zNonCallableMock.configure_mockcCs|dkrt|n:|jdk r<||jks.|tkrLtd|nt|rLt||jsd|jdrdt||jj|}|tkrt|np|dkrd}|j dk rt |j |}|j |||||d}||j|<n.t |t rt|j|j|j|j|j}||j|<|S) NrrzMock object has no attribute %rassertassret)rrrrr>rr)rr)r"r _all_magicsrdrrr`rCrrr<rrrrrrr3rr)rfrrJrrrrrmAs6            zNonCallableMock.__getattr__c Cs"|jg}|j}|}d}|dgkr$d}t}xT|dk r~|}|j|j|d}|jdkrZd}|j}t||krnP|jt|q,Wtt|}|jpd}t |dkr|dd kr|d7}||d<dj |}d}|dkrd |}d} |j dk rd } |j rd } | |j j } d t|j || t|fS)Nr()rr1r().rmock.z name=%rz spec=%rz spec_set=%rz<%s%s%s id='%s'>)rr)r1r)rwrurorrr}r>reversedrvrjoinrrr5r) rfZ _name_listrZlastdotseenZ_firstrZ name_stringZ spec_stringrrrrggsL           zNonCallableMock.__repr__cCshtstj|S|jpg}tt|}t|j}dd|D}dd|D}tt |||t|j S)z8Filter the output of `dir(mock)` to only useful members.cSsg|]}|jds|qS)r)r)rerrr sz+NonCallableMock.__dir__..cSs$g|]}|jd st|r|qS)r)rrd)rrrrrrs) r r__dir__rrrr>rBrror`)rfZextrasZ from_typeZ from_dictrrrrs    zNonCallableMock.__dir__cs"|tkrtj||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|<tj||S)Nz!Mock object has no attribute '%s'z.Attempting to set unsupported magic method %r.csf||S)Nr)r+r)rIrfrrrsz-NonCallableMock.__setattr__..r)r|r __setattr__rrrBr"_unsupported_magicsrrrzr _get_methodrr`r)rfrrpmsgr)rIrfrrs2       zNonCallableMock.__setattr__cCs|tkr2|t|jkr2tt||||jkr2dS||jkrHtj|||jj|t}|t krft ||tk rv|j|=t |j|<dS)N) rrrBdelattrr __delattr__r`rC_missingrr")rfrrrrrrs   zNonCallableMock.__delattr__cCs|jpd}t|||S)Nr1)rv_format_call_signature)rfr+r,rrrr_format_mock_call_signatures z+NonCallableMock._format_mock_call_signaturecCsDd}|j||}|j}t|dkr.|dd}|j|}|||fS)Nz!Expected call: %s Actual call: %sr)rr]r)rfr+r,messageexpected_stringr]Z actual_stringrrr_format_mock_failure_messages    z,NonCallableMock._format_mock_failure_messagecCst|j}|dk rlt|dkr(d}|\}}n |\}}}y||j||fStk rh}z |jdSd}~XqpXn|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. Nrbr)rrr) TypeErrorwith_traceback)rf_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.r1N)r\rvAssertionError)r*rfrrrrrPs  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.r1N)r\rvr)r*rfrrrrrO s   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.r1N)r\rvr)r*rfrrrrrQs  z"NonCallableMock.assert_called_oncecs||jdkr(j}td|ffdd}jf}jj}||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 calledcsj}|S)N)r)r)r+r,rfrr_error_message's z:NonCallableMock.assert_called_with.._error_message)r]rrrr Exception)r*r+r,expectedractualcauser)r+r,rfrrNs   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.r1)r\rvrrN)r*r+r,rfrrrrrR1s  z'NonCallableMock.assert_called_once_withc sfdd|D}t|tr |nd}tfddjD}|sd||kr`tdt|jf|dSt|}g}x:|D]2}y|j|Wqvtk r|j|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|]}j|qSr)r)rc)rfrrrFsz4NonCallableMock.assert_has_calls..Nc3s|]}j|VqdS)N)r)rr)rfrr Hsz3NonCallableMock.assert_has_calls..z(Calls not found. Expected: %r Actual: %rz%r not all found in call list) rrrUrWrr>remover&rr?)rfZcallsZ any_orderrrZ all_callsZ not_foundZkallr)rfrrS<s*  z NonCallableMock.assert_has_callscsZj||f}fddjD}||krVt|tr8|nd}j||}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|]}j|qSr)r)rr)rfrrrfsz3NonCallableMock.assert_any_call..Nz%s call not found)rr^rrrr)rfr+r,rrrrr)rfrrT_s zNonCallableMock.assert_any_callcKsFt|}t|ts2t|tr"t}q.) rrrrrrrrrr,attribute_namer)rfrrrrrisz _patch.copycCst|tr|j|S|j|S)N)rrdecorate_classdecorate_callable)rfr'rrrr$vs  z_patch.__call__cCsRxLt|D]@}|jtjsq t||}t|ds2q |j}t||||q W|S)Nr$)rrr TEST_PREFIXr<rrrz)rfrattr attr_valuerrrrr|s   z_patch.decorate_classcs<tdrjj|Stfdd|g_S)N patchingscsg}g}t}zybxJjD]@}|j}|j||jdk rF|j|q|jtkr|j|qW|t|7}||S||krt|r|j|t j }YnXWdxt |D]}|j |qWXdS)N) r?r __enter__rrupdaterrrsysexc_infor__exit__)r+Zkeywargs extra_argsZentered_patchersr patchingr)r'patchedrrrs*         z)_patch.decorate_callable..patched)rrrr)rfr'r)r'rrrs   z_patch.decorate_callablec Cs|j}|j}t}d}y|j|}Wn$ttfk rHt||t}YnXd}|tkrft|t rfd|_ |j r|tkrtd||f||fS)NFTz!%s does not have the attribute %r) rrrrBr"KeyErrorr< _builtinsrrr)rfrrrIlocalrrr get_originalsz_patch.get_originalcCs>|j|j|j}}}|j|j}}|j}|j|_|dkr@d}|dkrLd}|dkrXd}|dk rp|dk rptd|dk s|dk r|dkrtd|j \}}|t ko|dkrTd} |dkr|}|dkr|}d}n&|dk r|dkr|}d}n |dkr|}|dk s |dk r,|t krtdt |t r,d} t } i} |dk rD|} nN|dk sX|dk r|} |dk rj|} t| r~d| k} n t|  } | rt} |dk r|| d<|dk r|| d <t | t rt| tr|jr|j| d <| j|| f| }| rt|r|} |dk r|} t|  r2t|  r2t} | jd | f|d d | |_nl|dk r|t k rptd |t krtdt|}|dkr|}t|f||jd|}n|rtd|}||_||_t|j|j||jdk r:i}|jt kr|||j<x.|jD]$}|j }|jt kr|j|qW|S|S)zPerform the patch.FNzCan't specify spec and autospecTz6Can't provide explicit spec_set *and* spec or autospecz!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)TN)!rrrrr,rrrrrrrrrr@rr rr rr rrErrYboolr temp_originalrrzrrr )rfrrrrr,rrIrZinheritKlass_kwargsZ this_specZ not_callableZnew_attrrrrrrrr s                              z_patch.__enter__cGst|std|jr4|jtk r4t|j|j|jnBt|j|j|j rvt |j|j sd|jdkrvt|j|j|j|`|`|`x$t |j D]}t|r|j |qWdS) zUndo the patch.z stop called on unstarted patcherr6r8r9__annotations__r:N)r6r8r9rr:)r RuntimeErrorrrrrzrrrrrrrr )rfr rrrrr Hs z_patch.__exit__cCs|j}|jj||S)z-Activate a patch, returning any created mock.)r _active_patchesr)rfrJrrrstart`s z _patch.startc Cs.y|jj|Wntk r$YnX|jS)zStop an active patch.)rrr&r )rfrrrstopgs z _patch.stop)r5r8rhrrr!rr$rrrr r rrrrrrrIs (~rc sPyjdd\}Wn&ttfk r:tdfYnXfdd}||fS)Nrrz.Need a valid target to patch. You supplied: %rcstS)N)rr)rrrrysz_get_target..)rsplitrr&)rrrr)rr _get_targetss 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)rrrrsz_patch_object..)r) rrrrrrrrr,rr)rr _patch_object}s  r!c sttkrfdd}n fdd}|s2tdt|j}|d\} } t|| | |||||i } | | _xB|ddD]2\} } t|| | |||||i } | | _| jj| 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)rrrrsz!_patch_multiple..csS)Nrr)rrrrsz=Must supply at least one keyword argument with patch.multiplerrN) rstrr&r>rrrrr) rrrrrrr,rrrrrZ 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,rrrrrrsE  c@sVeZdZdZfdfddZddZddZd d Zd d Zd dZ 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. FcKs>t|trt|}||_t||_|jj|||_d|_dS)N) rr"rin_dictrnrr clear _original)rfr%rr&r,rrrr!0s   z_patch_dict.__init__cs.ttrjStfdd}|S)Nc s"jz ||SjXdS)N)r$ _unpatch_dict)r+r)frfrr_inner>s z$_patch_dict.__call__.._inner)rrrr)rfr)r*r)r)rfrr$;s  z_patch_dict.__call__cCs\xVt|D]J}t||}|jtjr t|dr t|j|j|j }||}t |||q W|S)Nr$) rr<rrrrr$r%rr&rz)rfrrrZ decoratorZ decoratedrrrrIs   z_patch_dict.decorate_classcCs |jdS)zPatch the dict.N)r$)rfrrrr Tsz_patch_dict.__enter__cCs|j}|j}|j}y |j}Wn2tk rPi}x|D]}||||<q8WYnX||_|rdt|y|j|Wn.tk rx|D]}||||<qWYnXdS)N)rr%r&rr"r' _clear_dictr )rfrr%r&rIrrrrr$Ys"   z_patch_dict._patch_dictc CsV|j}|j}t|y|j|Wn.tk rPx|D]}||||<q8WYnXdS)N)r%r'r+r r")rfr%rIrrrrr(ss z_patch_dict._unpatch_dictcGs |jdS)zUnpatch the dict.F)r()rfr+rrrr sz_patch_dict.__exit__N) r5r8rhr6r!r$rr r$r(r rrrrrrr$s   r$c CsBy |jWn0tk r<t|}x|D] }||=q*WYnXdS)N)r&r"r>)r%keysrrrrr+s   r+cCs xttjD] }|jq WdS)z7Stop all active patches. LIFO to unroll nested patches.N)rrrr)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__ __reduce__ __reduce_ex__Z__getinitargs____getnewargs__ __getstate__ __setstate__ __getformat__ __setformat__rgr__subclasses__ __format____getnewargs_ex__csfdd}||_|S)z:Turns a callable object (like a mock) into a real functioncs|f||S)Nr)rfr+r)r'rrmethodsz_get_method..method)r5)rr'r?r)r'rrs rcCsh|] }d|qS)z__%s__r)rr?rrrrsrmrr!r __prepare____instancecheck____subclasscheck____del__cCs tj|S)N)r__hash__)rfrrrrsrcCs tj|S)N)r__str__)rfrrrrscCs tj|S)N)r __sizeof__)rfrrrrs)rDrErFry?g?) __lt____gt____le____ge____int__r__len__r  __complex__ __float____bool__ __index__csfdd}|S)Ncs$jj}|tk r|S|kr dStS)NT)__eq__rrrNotImplemented)otherret_val)rfrrrQs z_get_eq..__eq__r)rfrQr)rfr_get_eqs rUcsfdd}|S)Ncs jjtk rtS|krdStS)NF)__ne__rrrrR)rS)rfrrrVs  z_get_ne..__ne__r)rfrVr)rfr_get_nes rWcsfdd}|S)Ncs jj}|tkrtgSt|S)N)rrrrr)rT)rfrrrsz_get_iter..__iter__r)rfrr)rfr _get_iters rX)rQrVrc Cstj|t}|tk r||_dStj|}|dk rdy ||}Wntk rXt|}YnX||_dStj|}|dk r|||_dS)N)_return_valuesrCrrY_calculate_return_valuer"_side_effect_methodsr_)r1r?rZfixedZreturn_calulatorrYZ side_effectorrrr_set_return_values    r\c@seZdZddZddZdS) MagicMixincOs&|jtt|j|||jdS)N)_mock_set_magicsrr]r!)rfr+rrrrr!(szMagicMixin.__init__cCst}t|dddk rTtj|j}t}t|}x$|D]}|t|jkr4t||q4W|tt|j}t|}x|D]}t||t ||qtWdS)Nr) _magicsr< intersectionrrorrBrrz MagicProxy)rfZ these_magicsZ remove_magicsrrrrrr^.s   zMagicMixin._mock_set_magicsN)r5r8rhr!r^rrrrr]'sr]c@seZdZdZdddZdS)r z-A version of `MagicMock` that isn't callable.FcCs|j|||jdS)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^)rfrrrrrrGs z"NonCallableMagicMock.mock_add_specN)F)r5r8rhr6rrrrrr Esc@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|j|||jdS)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^)rfrrrrrr]s zMagicMock.mock_add_specN)F)r5r8rhr6rrrrrrRs c@s.eZdZddZddZddZd dd ZdS) racCs||_||_dS)N)rr)rfrrrrrr!iszMagicProxy.__init__cOs|j}|||S)N) create_mock)rfr+r,mrrrr$mszMagicProxy.__call__cCs8|j}|j}|j|||d}t|||t||||S)N)rrr)rrrrzr\)rfrrrcrrrrbqs  zMagicProxy.create_mockNcCs|jS)N)rb)rfrrrrrr0zszMagicProxy.__get__)N)r5r8rhr!r$rbr0rrrrrahs rac@s(eZdZdZddZddZddZdS) _ANYz2A helper object that compares equal to everything.cCsdS)NTr)rfrSrrrrQsz _ANY.__eq__cCsdS)NFr)rfrSrrrrVsz _ANY.__ne__cCsdS)Nzr)rfrrrrgsz _ANY.__repr__N)r5r8rhr6rQrVrgrrrrrdsrdcCsdd|}d}djdd|D}djddt|jD}|rD|}|r\|rT|d7}||7}||S)Nz%s(%%s)rz, cSsg|] }t|qSr)repr)rrrrrrsz*_format_call_signature..cSsg|]\}}d||fqS)z%s=%rr)rrrprrrrs)rrr)rr+r,rZformatted_argsZ args_stringZ kwargs_stringrrrrsrc@sveZdZdZfddddfddZfddddfdd Zd d ZejZd d Z 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. rNFTc Csf}i}t|}|dkr$|\}}}nr|dkrd|\} } t| trX| }t| trR| }qb| }q| | }}n2|dkr|\}t|tr|}nt|tr|}n|}|rtj|||fStj||||fS)Nrrbr)rrr"r?r) rrprrr from_kallr+r,_lenfirstsecondrrrrs.      z _Call.__new__cCs||_||_||_dS)N)rvrt_mock_from_kall)rfrprrrrfrrrr!sz_Call.__init__c Csf|tkr dSy t|}Wntk r,dSXd}t|dkrH|\}}n |\}}}t|ddrzt|ddrz|j|jkrzdSd}|dkrfi}}n|dkr|\}}}n|dkr|\} t| tr| }i}n"t| tr| }fi}}nf}| }nV|dkr>|\} } t| tr2| }t| tr&| i}}n f| }}n | | }}ndS|rV||krVdS||f||fkS) NTFrrbrtrrr)rrrr<rtrr?r") rfrSZ len_otherZ self_nameZ self_argsZ self_kwargsZ other_nameZ other_argsZ other_kwargsrprhrirrrrQsP                z _Call.__eq__cOs<|jdkrtd||fddS|jd}t|j||f||dS)Nrz())r)rr)rvr)rfr+r,rrrrr$s  z_Call.__call__cCs2|jdkrt|ddSd|j|f}t||ddS)NF)rrfz%s.%s)rrrf)rvr)rfrrrrrrms  z_Call.__getattr__cOs|jd||S)Nr)rm)rfr+r,rrrr$sz _Call.countcOs|jd||S)Nindex)rm)rfr+r,rrrrk'sz _Call.indexcCs||js&|jpd}|jdr"d|}|St|dkr@d}|\}}n0|\}}}|sTd}n|jdshd|}nd|}t|||S)Nrz()zcall%srbzcall.%s)rjrvrrr)rfrr+r,rrrrg*s       z_Call.__repr__cCs8g}|}x"|dk r*|jr"|j||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)rjrrtrUr)rfvalsrrrr call_list?s   z_Call.call_list)r5r8rhr6rr!rQrrVr$rmrrkrgrmrrrrrs  7r)rfcKs,t|rt|}t|t}d|i}|r0d|i}n |dkr.rrxrxrxrx)rbytesr) read_dataZ data_as_listliner)rwr_iterate_read_data s  r|rcsfdd}fdd}fddtdkr`ddl}ttt|jjtt|ja|dkrttd t d }ttd j _ t dgdj _ dj_ dj_ dj_ |j_d <d j_|j_fd d}||_|_ |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` methoddline`, and `readlines` of the file handle to return. This is an empty string by default. cs jjdk rjjStdS)Nr) readlinesrYr>)r+r,)_statehandlerr_readlines_side_effect( s z)mock_open.._readlines_side_effectcs(jjdk rjjStjdS)Nr)readrYrr)r+r,)r~rrzrr_read_side_effect- s z$mock_open.._read_side_effectc3sJjjdk rxjjVqWxdD] }|Vq&WxtVq6WdS)Nr)readlinerYr)r{)r~rrzrr_readline_side_effect2 s  z(mock_open.._readline_side_effectNropen)rr)rrcs6td<jjdkr2d<dj_tS)Nrr)r|rr_r)r+r,)rr~rrzrr reset_dataS s    zmock_open..reset_data) file_spec_ior>ror TextIOWrapperunionBytesIOrrr rYr|writerrr}r_)r1rzrrrrr)rr~rrzrr  s.  "     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)rfr,rrrri szPropertyMock._get_child_mockcCs|S)Nr)rfrZobj_typerrrr0l szPropertyMock.__get__cCs ||dS)Nr)rfrrrrrr1n szPropertyMock.__set__N)r5r8rhr6rr0r1rrrrr ` s) rrrrrrrrr r r r r )F)F)NFNNN)FFNN)Nr)o__all__ __version__r%rr builtinstypesr functoolsrrrr BaseExceptionrplatformrZlangZ Throwabler superrrr r(r4r/r=r@rErMrHrdrrerirrZMISSINGrZDELETEDrrqr|rr>rUrrrr rrrrrrrr r!r#rr$r+r-rnZmultipleZstopallrZ magic_methodsZnumericsrrZinplacerightZ _non_defaultsrr_rrrZrRrYrUrWrXr[r\r]r rrardrrr?rrrrnrrrrQr#r0rrrr|r r rrrrs     4  i5 ,   1Jv        ,  w  D