3 C\FF@sddlmZdZddlmZddlZddlZddlZy ddlZWne k r\ddl ZYnXddl m Z ddl Z ddl mZddlmZedjZejZejZddlZy ejZWn"ek rddlZejZYnXyeWnek reZZYnXye Wnek r&e!Z YnXye"Wnek rJe#Z"YnXe j$rfe%Z&e&fddZ%[&e'dde(eDZ)e"fZ*dej+krddl,Z,e"e,j-j.fZ*y ej/Z0Wn<ek rddl1Z1ddl2Z2e2j3de2j4Z5ddZ0YnXd Z6d!Z7e j8rd"Z6d#Z7d$Z9e:Z;d%d&ZZ?e@e?jAeBfZCd+d,ZDdd.d/ZEd0d1ZFd2d3ZGd4d5ZHd6d7ZIdd8d9ZJd:d;ZKdd?d?e>ZMGd@dAdAe>ZNeNZOeOjPZPeOjQZReOjSZTGdBdCdCZUe@eUZVdDdEZWe@fZXe j$re@eVfZXe'd˃ZYdNdOZZGdPdQdQe[Z\dRdSZ]GdTdUdUe>Z^GdVdWdWe>Z_GdXdde_Z`dYdZZaGd[d d e_ZbGd\ddebe`Zcd]d^Zdd_d`ZedadbZfGdcdddde>ZgdedfZhePdd-dddfdgdhZiddidjZjePdd-dddfdkdZkGdldmdme>ZldndoZmdpdqZneiek_>elek_oejek_penek_qdrek_rdsZsdtZte j8r.etdu7ZtdvjudwdetjvDZwdvjudxdetjvDZxdyZye j8rpdzZynd{Zye'd̓ZzddZ{e'dddvjuesetewexeygjvDZ|e|ezBZ}e'd΃Z~dddddddddZeeeedd-dd-ddd$d$dde dddZddZddZddZeeedZddZGddde>ZGdddee`ZGdddeecZGddde>ZGddde>ZeZddZGdddeZed-dZddd ZddZddZGddÄde>Ze@ee@ejfZe@ejjfZdaddńZdddZGdddecZdS))absolute_import __version__ version_infoMock MagicMockpatchsentinelDEFAULTANYcallcreate_autospec FILTER_DIR CallableMixinNonCallableMockNonCallableMagicMock mock_open PropertyMock)partialN) ModuleType)wraps) VersionInfomockcCst|ddr|jS||S)N__next__)getattrr)obj_nextr_/private/var/folders/pf/wv4htv3x0qs2c2mp0dnn0kchsvlck3/T/pip-install-emcbgzcf/mock/mock/mock.pynextjs rccs|]}|jds|VqdS)_N) startswith).0namerrr rsr#javaz^[a-z_][a-z0-9_]*$cCs|tjkrdStj|S)NF)keywordkwlistregexmatch)stringrrr _isidentifiers r*Zim_self __builtin____self__builtinsTcCstt|tS)N) issubclasstyper)rrrr_is_instance_mocksr0cCst|tpt|tot|tS)N) isinstanceBaseExceptions ClassTypesr.)rrrr _is_exceptions r4c@seZdZdgZdS)_slottedaN)__name__ __module__ __qualname__ __slots__rrrrr5sr5cCst|tr6| r6y |j}Wntk r.dSXd}n*t|ts`y |j}Wntk r^dSX|rpt|d}n|}y |t|fStk rdSXdS)z Given an arbitrary, possibly callable object, try to create a suitable signature object. Return a (reduced func, signature) tuple, or None. NT) r1r3__init__AttributeError FunctionTypes__call__rinspectsignature ValueError)funcZ as_instanceZeat_selfZsig_funcrrr_get_signature_objects$     rBFcsDt|||dkrdS\}fdd}t|||t|_dS)Ncsj||dS)N)bind) _mock_selfargskwargs)sigrrchecksigsz"_check_signature..checksig)rB_copy_func_detailsr/_mock_check_sig)rAr skipfirstinstancerHr)rGr_check_signatures   rMc#Cs|j|_|j|_y |j|_Wntk r0YnXy |j|_Wntk rRYnXy |j|_Wntk rtYnXy |j|_Wntk rYnXtjr|j |_ dSdS)N) r7__doc____text_signature__r<r8 __defaults____kwdefaults__sixPY2Z func_defaults)rAfuncopyrrrrIs*    rIcCs&t|trdSt|dddk r"dSdS)NTr>F)r1r3r)rrrr _callables  rUcCst|ttfkS)N)r/listtuple)rrrr_is_listsrXcCst|tst|dddk StjrLx^|f|jD]}|jjddk r.dSq.Wn4|}|jjddk rddSx|jD]}t |rldSqlWdS)ztGiven an object, return True if the object is callable. For classes, return True if instances would be callable.r>NTF) r1r3rrRPY3__mro____dict__get __bases___instance_callable)rbaseklassrrrr^s   r^c st|s dSt|t}t|||}|dkr.dS|\}fdd}t|||j}t|s^d}||d}d|} tj| |||} t | || S)Ncsj||dS)N)rC)rErF)rGrrrH#sz _set_signature..checksigrT)Z _checksig_rzYdef %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs)) rUr1r3rBrIr7r*rRexec_ _setup_func) roriginalrLrKresultrArHr"contextsrcrTr)rGr_set_signatures$       rgcs_tsdSfdd}fdd}fdd}fdd}fd d }d _d _d_t_t_t_j _ j _ j _ |_ |_ |_|_|__dS) Ncs j||S)N)assert_called_with)rErF)rrrrh;sz'_setup_func..assert_called_withcs j||S)N)assert_called_once_with)rErF)rrrri=sz,_setup_func..assert_called_once_withcs j||S)N)assert_has_calls)rErF)rrrrj?sz%_setup_func..assert_has_callscs j||S)N)assert_any_call)rErF)rrrrkAsz$_setup_func..assert_any_callcs:t_t_jj}t|r6|k r6|jdS)N) _CallList method_calls mock_calls reset_mock return_valuer0)ret)rTrrrroCs z_setup_func..reset_mockFr)rr0called call_count call_argsrlcall_args_listrmrnrp side_effect_mock_childrenrhrirjrkro_mock_delegate)rTrrhrirjrkror)rTrrrb4s.    rbcCsd|dd|kS)Nz__%s__r)r"rrr _is_magic_sr{c@s eZdZdZddZddZdS)_SentinelObjectz!A unique, named, sentinel object.cCs ||_dS)N)r")selfr"rrrr;esz_SentinelObject.__init__cCs d|jS)Nz sentinel.%s)r")r}rrr__repr__hsz_SentinelObject.__repr__N)r7r8r9rNr;r~rrrrr|csr|c@s eZdZdZddZddZdS) _SentinelzAAccess attributes to return a named object, usable as a sentinel.cCs i|_dS)N) _sentinels)r}rrrr;nsz_Sentinel.__init__cCs|dkr t|jj|t|S)Nr])r<r setdefaultr|)r}r"rrr __getattr__qsz_Sentinel.__getattr__N)r7r8r9rNr;rrrrrrlsrc@s eZdZdS) OldStyleClassN)r7r8r9rrrrrsrcCs$t|ttttfkr t||S|S)N)r/dictrVrWset)valuerrr_copys rrp_mock_return_valuerv_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)rxr)r}r" _the_namerGrrr_gets z"_delegating_property.._getcSs*|j}|dkr||j|<n t|||dS)N)rxr[setattr)r}rr"rrGrrr_sets z"_delegating_property.._set)_allowed_namesaddproperty)r"rrrrrr_delegating_propertys  rc@seZdZddZddZdS)rlcCsnt|tstj||St|}t|}||kr2dSx6td||dD] }||||}||krFdSqFWdS)NFrT)r1rV __contains__lenrange)r}rZ len_valueZlen_selfiZsub_listrrrrs  z_CallList.__contains__cCstjt|S)N)pprintpformatrV)r}rrrr~sz_CallList.__repr__N)r7r8r9rr~rrrrrlsrlcCsxt|s dS|js,|js,|jdk s,|jdk r0dS|}x|dk rR||krJdS|j}q6W|rd||_||_|rt||_||_dS)NFT)r0rrrr)parentrr"new_name_parentrrr_check_and_set_parents$     rc@s$eZdZddZddZddZdS) _MockItercCst||_dS)N)iterr)r}rrrrr;sz_MockIter.__init__cCs|S)Nr)r}rrr__iter__sz_MockIter.__iter__cCs t|jS)N)rr)r}rrrrsz_MockIter.__next__N)r7r8r9r;rrrrrrrsrc@seZdZeZdZddZdS)BaseNcOsdS)Nr)r}rErFrrrr;sz Base.__init__)r7r8r9r rrr;rrrrrsrc @s@eZdZdZddZdCddZd d ZdDd d ZdEd dZddZ ddZ dZ e e e e Z e ddZedZedZedZedZedZddZddZe eeZdFdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Z d1d2Z!d3d4Z"d5d6Z#d7d8Z$d9d:Z%d;d<Z&dGd=d>Z'd?d@Z(dAdBZ)dS)Hrz A non-callable version of `Mock`cOs$t|j|fd|ji}tj|}|S)NrN)r/r7rNobject__new__)clsrEkwnewrLrrrrs 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)NrrrrTrw _mock_wrapsrxFZ _mock_calledZ_mock_call_argsrZ_mock_call_countZ_mock_call_args_listZ_mock_mock_callsrm _mock_unsafe)r[_mock_add_specrlconfigure_mock _safe_superrr;)r}specrr"spec_setr _spec_state _new_name _new_parent_spec_as_instance _eat_selfZunsaferFr[rrrr;s8      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)rrrrr)r}r 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)r}rrrrr mock_add_spec*szNonCallableMock.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)rXr1r3 _get_classrBdirr[) r}rrrrrrresr[rrrr3s  zNonCallableMock._mock_add_speccCs8|j}|jdk r|jj}|tkr4|j|dd}||_|S)Nz())rr)rrxrpr _get_child_mock)r}rqrrrZ__get_return_valueJs  z"NonCallableMock.__get_return_valuecCs,|jdk r||j_n||_t||dddS)Nz())rxrprr)r}rrrrZ__set_return_valueWs  z"NonCallableMock.__set_return_valuez1The value to be returned when the mock is called.cCs|jdkrt|S|jS)N)rr/)r}rrr __class__cs zNonCallableMock.__class__rrrsrtrurncCsT|j}|dkr|jS|j}|dk rPt| rPt|t rPt| rPt|}||_|S)N)rxrrvcallabler1rr4)r} delegatedZsfrrrZ__get_side_effectpsz!NonCallableMock.__get_side_effectcCs(t|}|j}|dkr||_n||_dS)N) _try_iterrxrrv)r}rrrrrZ__set_side_effect{s z!NonCallableMock.__set_side_effectcCs|dkr g}t||krdS|jt|d|_d|_d|_t|_t|_t|_x(|j j D]}t |t rpq`|j |q`W|j}t|r||k r|j |dS)z-Restore the mock object to its initial state.NFr)idappendrrrtrsrlrnrurmrwvaluesr1 _SpecStaterorr0)r}visitedchildrqrrrros$  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)entryrrrsz0NonCallableMock.configure_mock..)keyrN)sorteditemssplitpoprr)r}rFargvalrEfinalrrrrrrs   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)rr"rrr)rr)rr)r<r _all_magicsr{rr rwr\_deletedrrrr1rr rrrLrr")r}r"rdrrrrrs6            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()rrr().rmock.z name=%rz spec=%rz spec_set=%rz<%s%s%s id='%s'>)rr)rr)rrrrrrrVreversedrrjoinrrr7r/) r}Z _name_listrlastdotseenZ_firstr"Z name_stringZ spec_stringrrrr~sL           zNonCallableMock.__repr__cCs~tj rttddrtj|S|jp&g}tt|}t|j }tjr`dd|D}dd|D}t t |||t|j S)z8Filter the output of `dir(mock)` to only useful members.__dir__NcSsg|]}|jds|qS)r)r )r!errr sz+NonCallableMock.__dir__..cSs$g|]}|jd st|r|qS)r)r r{)r!rrrrrs) rr rrrrrr/rVr[rrrw)r}extrasZ from_typeZ from_dictrrrr s    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)rEr)rcr}rrr2sz-NonCallableMock.__setattr__..r)rr __setattr__rrr[r<_unsupported_magicsrr0rr/ _get_methodrrwr)r}r"rmsgr)rcr}rr s2       zNonCallableMock.__setattr__cCs|tkr2|t|jkr2tt||||jkr2dS||jkrHtj|||jj|t}|t krft ||tk rv|j|=t |j|<dS)N) rr/r[delattrr __delattr__rwr\_missingrr<)r}r"rrrrrBs   zNonCallableMock.__delattr__cCs|jpd}t|||S)Nr)r_format_call_signature)r}rErFr"rrr_format_mock_call_signatureUs z+NonCallableMock._format_mock_call_signaturecCsDd}|j||}|j}t|dkr.|dd}|j|}|||fS)Nz!Expected call: %s Actual call: %sr)rrtr)r}rErFmessageexpected_stringrtZ actual_stringrrr_format_mock_failure_messageZs    z,NonCallableMock._format_mock_failure_messagecCst|j}|dk rlt|dkr(d}|\}}n |\}}}y||j||fStk rh}z d|_|Sd}~XqpXn|SdS)a Given a call (or simply a (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. Nryr)rrrC TypeError __traceback__)r}_callrGr"rErFrrrr _call_matcherds   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.rN)rsrAssertionError)rDr}rrrrassert_not_calledzs  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.rN)rsrr)rDr}rrrr assert_calleds   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.rN)rsrr)rDr}rrrrassert_called_onces  z"NonCallableMock.assert_called_oncecs|jdkr(j}td|ffdd}jf}jj}||krt|trh|nd}tjt|||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.j}tjr*|dk r*d|t|f}|S)Nz%s %s)rrRrSstr)causer)rErFr}rr_error_messages z:NonCallableMock.assert_called_with.._error_message)rtrrrr1 ExceptionrR raise_from)rDrErFexpectedractualrr)rErFr}rrhs   z"NonCallableMock.assert_called_withcOs6|}|jdks*d|jpd|jf}t||j||S)zVassert that the mock was called exactly once and with the specified arguments.rz1Expected '%s' to be called once. Called %s times.r)rsrrrh)rDrErFr}rrrrris  z'NonCallableMock.assert_called_once_withc sfdd|D}t|tr |nd}tfddjD}|sj||krftjtdt|jf|dSt|}g}x:|D]2}y|j|Wq|t k r|j |Yq|Xq|W|rtjtdt |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)r!c)r}rrrsz4NonCallableMock.assert_has_calls..Nc3s|]}j|VqdS)N)r)r!r)r}rrr#sz3NonCallableMock.assert_has_calls..z(Calls not found. Expected: %r Actual: %rz%r not all found in call list) r1rrlrnrRrrrVremover@rrW)r}ZcallsZ any_orderrrZ all_calls not_foundZkallr)r}rrjs*  z NonCallableMock.assert_has_callscs`j||f}fddjD}||kr\t|tr8|nd}j||}tjtd||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)r!r)r}rrrsz3NonCallableMock.assert_any_call..Nz%s call not found)rrur1rrrRrr)r}rErFrrrrr)r}rrks zNonCallableMock.assert_any_callcKsFt|}t|ts2t|tr"t}q"s zCallableMixin.__call__cOs|}d|_|jd7_|j}|j}t||fdd}||_|jj||jjtd||ft }|dk}|j dk } |j } x|dk rDt|||f} |jrd} |rd} d}|jdkrd}|j| |}| r|| kr| } nt| ||f} |j j| |j dk } | r|j d| } |jj| |j}t |}||kr8P|j|q|Wt}|j}|dk rt|rh|t|st|}t|r||tkr|j}|S|||}|jdk r|jtkr|j||S|tkr|j}|S)NTr)tworz()rF)rrrsrr_Callrtrurrnrrrrmrrr rvr4rUrrprr)rDrErFr}rrrrZ skip_next_dotZdo_method_callsr"Zthis_mock_callrZthis_method_callZ_new_parent_idret_valZeffectrdrrrr)sp                  zCallableMixin._mock_call)r7r8r9r r;rJr>rrrrrrs  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. Alternatively `side_effect` can be an exception class or instance. In this case the exception will be raised when the mock is called. 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. N)r7r8r9rNrrrrrss4c Cs2y t||Stk r,t|t||SXdS)N)rr< __import__)thingcomp import_pathrrr _dot_lookups  rcCsF|jd}|jd}t|}x$|D]}|d|7}t|||}q"W|S)Nrrz.%s)rrr r)target componentsrr rrrr _importers    rcCs t|dS)Nis_local)hasattr)patcherrrr _is_startedsrc@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) r r@getterrr new_callablercreateZ has_localrautospecrFadditional_patchers) r}rrrrrrrrrFrrrr;s$z_patch.__init__c CsHt|j|j|j|j|j|j|j|j|j }|j |_ dd|j D|_ |S)NcSsg|] }|jqSr)copy)r!prrrrsz_patch.copy..) rrrrrrrrrrFattribute_namer)r}rrrrrsz _patch.copycCst|tr|j|S|j|S)N)r1r3decorate_classdecorate_callable)r}rArrrr>s  z_patch.__call__cCsRxLt|D]@}|jtjsq t||}t|ds2q |j}t||||q W|S)Nr>)rr r TEST_PREFIXrrrr)r}r`attr 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) rWr& __enter__rr updaterr rsysexc_infor__exit__)rEZkeywargs extra_argsZentered_patchersr*patchingr)rApatchedrrr. s*         z)_patch.decorate_callable..patched)rr&rr)r}rAr)rAr.rr"s   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) rrr r[r<KeyErrorr _builtinsr1rr)r}rr"rclocalrrr get_original,sz_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 | trt| 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.|j D]$}|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>rrr"z())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)"rrrrrFrrrrr2r r1r3rrXrUrr/r.rrr(r0r^rrpboolr temp_originalrrr rr')r}rrrrrFrrcr1ZinheritKlass_kwargsZ this_specZ not_callablenew_attrr,r-rrrrr'Ds                              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 patcherrNr8rP__annotations__rQN)rNr8rPr9rQ)r RuntimeErrorrr5r rrrrrrrrr+)r}r*rrrrr+s z_patch.__exit__cCs|j}|jj||S)z-Activate a patch, returning any created mock.)r'_active_patchesr)r}rdrrrstarts z _patch.startc Cs.y|jj|Wntk r$YnX|jS)zStop an active patch.)r;rr@r+)r}rrrstops z _patch.stop)r7r8r9r r;r;rr>r!r"r2r'r+r<r=rrrrrs (~rc sPyjdd\}Wn&ttfk r:tdfYnXfdd}||fS)Nrrz.Need a valid target to patch. You supplied: %rcstS)N)rr)rrrrsz_get_target..)rsplitrr@)rrrr)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)rrrr sz_patch_object..)r) rrrrrrrrrFrr)rr _patch_objects  r@c stttfkrfdd}n fdd}|s6tdt|j}|d\} } t|| | |||||i } | | _xB|ddD]2\} } t|| | |||||i } | | _| jj | qzW| 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)rrrr'sz!_patch_multiple..csS)Nrr)rrrr)sz=Must supply at least one keyword argument with patch.multiplerrN) r/unicoderr@rVrrr rr) rrrrrrrFrrrrrZ this_patcherr)rr_patch_multiples&       rBc 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) rrrrrrrrFrrrrrrAsE  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) r1 basestringrin_dictrrr(clear _original)r}rErrFrFrrrr;s   z_patch_dict.__init__cs.ttrjStfdd}|S)Nc s"jz ||SjXdS)N)rC _unpatch_dict)rEr)fr}rr_inners z$_patch_dict.__call__.._inner)r1r3r!r)r}rIrJr)rIr}rr>s  z_patch_dict.__call__cCs\xVt|D]J}t||}|jtjr t|dr t|j|j|j }||}t |||q W|S)Nr>) rrr rr#rrCrErrFr)r}r`r$r%Z decoratorZ decoratedrrrr!s   z_patch_dict.decorate_classcCs |jdS)zPatch the dict.N)rC)r}rrrr'sz_patch_dict.__enter__cCs|j}|j}|j}y |j}Wn2tk rPi}x|D]}||||<q8WYnX||_|rdt|y|j|Wn.tk rx|D]}||||<qWYnXdS)N)rrErFrr<rG _clear_dictr()r}rrErFrcrrrrrCs"   z_patch_dict._patch_dictc CsV|j}|j}t|y|j|Wn.tk rPx|D]}||||<q8WYnXdS)N)rErGrKr(r<)r}rErcrrrrrHs z_patch_dict._unpatch_dictcGs |jdS)zUnpatch the dict.F)rH)r}rErrrr+sz_patch_dict.__exit__N) r7r8r9rNr;r>r!r'rCrHr+r<r=rrrrrCs   rCc CsBy |jWn0tk r<t|}x|D] }||=q*WYnXdS)N)rFr<rV)rEkeysrrrrrKs   rKcCs xttjD] }|jq WdS)z7Stop all active patches. LIFO to unroll nested patches.N)rrr;r=)rrrr_patch_stopall srMtestzlt 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 z@add sub mul matmul div floordiv mod lshift rshift and xor or powz truediv ccs|]}d|VqdS)zi%sNr)r!nrrrr#*sccs|]}d|VqdS)zr%sNr)r!rPrrrr#+srz bool next z.unicode long nonzero oct hex truediv rtruediv __cmp__ __getslice__ __setslice__ __coerce____get____set__ __delete__ __reversed__ __missing__ __reduce__ __reduce_ex____getinitargs____getnewargs__ __getstate__ __setstate__ __getformat__ __setformat__r~r__subclasses__ __format__csfdd}||_|S)z:Turns a callable object (like a mock) into a real functioncs|f||S)Nr)r}rEr)rArrmethodAsz_get_method..method)r7)r"rArdr)rArr?s rccs|]}d|VqdS)z__%s__Nr)r!rdrrrr#Hsrrr;r__prepare____instancecheck____subclasscheck____del__cCs tj|S)N)r__hash__)r}rrrrVsrcCs tj|S)N)r__str__)r}rrrrWscCs tj|S)N)r __sizeof__)r}rrrrXscCsttj|S)N)rArri)r}rrrrYs)rhrirj __unicode__ry?g?1Z0x1)__lt____gt____le____ge____int__r__len__r+ __complex__ __float____bool__ __nonzero__Z__oct__Z__hex__Z__long__ __index__csfdd}|S)Ncsjj}|tk r|S|kS)N)__eq__rr )otherr )r}rrrxqsz_get_eq..__eq__r)r}rxr)r}r_get_eqps rzcsfdd}|S)Ncsjjtk rtS|k S)N)__ne__rr )ry)r}rrr{ys z_get_ne..__ne__r)r}r{r)r}r_get_nexs r|csfdd}|S)Ncs jj}|tkrtgSt|S)N)rrr r)r )r}rrrsz_get_iter..__iter__r)r}rr)r}r _get_iters r})rxr{rc Cstj|t}|tk r||_dStj|}|dk rdy ||}Wntk rXt|}YnX||_dStj|}|dk r|||_dS)N)_return_valuesr\r rp_calculate_return_valuer<_side_effect_methodsrv)rrdr"ZfixedZreturn_calulatorrpZ side_effectorrrr_set_return_values    rc@seZdZddZddZdS) MagicMixincOs&|jtt|j|||jdS)N)_mock_set_magicsrrr;)r}rErrrrr;szMagicMixin.__init__cCst}t|dddk rTtj|j}t}t|}x$|D]}|t|jkr4t||q4W|tt|j}t|}x|D]}t||t ||qtWdS)Nr) _magicsr intersectionrrr/r[rr MagicProxy)r}Z these_magicsZ remove_magicsrrrrrrs   zMagicMixin._mock_set_magicsN)r7r8r9r;rrrrrrsrc@seZdZdZdddZdS)rz-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)r}rrrrrrs z"NonCallableMagicMock.mock_add_specN)F)r7r8r9rNrrrrrrsc@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)r}rrrrrrs zMagicMock.mock_add_specN)F)r7r8r9rNrrrrrrs c@s.eZdZddZddZddZd dd ZdS) rcCs||_||_dS)N)r"r)r}r"rrrrr;szMagicProxy.__init__cOs|j}|||S)N) create_mock)r}rErFmrrrr>szMagicProxy.__call__cCs8|j}|j}|j|||d}t|||t||||S)N)r"rr)r"rrrr)r}rrrrrrrs  zMagicProxy.create_mockNcCs|jS)N)r)r}rrrrrrUszMagicProxy.__get__)N)r7r8r9r;r>rrUrrrrrs rc@s(eZdZdZddZddZddZdS) _ANYz2A helper object that compares equal to everything.cCsdS)NTr)r}ryrrrrxsz _ANY.__eq__cCsdS)NFr)r}ryrrrr{sz _ANY.__ne__cCsdS)Nzr)r}rrrr~ sz _ANY.__repr__N)r7r8r9rNrxr{r~rrrrrsrcspd|}d}djdd|D}dddjfddt|jD}|rP|}|rh|r`|d7}||7}||S) Nz%s(%%s)rz, cSsg|] }t|qSr)repr)r!rrrrrsz*_format_call_signature..cSs"tjrt|tr|jdS|SdS)Nzutf-8)rRrSr1rAencode)itemrrr encode_items z+_format_call_signature..encode_itemcs g|]\}}d||fqS)z%s=%rr)r!rr)rrrrs)rrr)r"rErFrZformatted_argsZ args_stringZ kwargs_stringr)rrrsrc@sxeZdZdZfddddfddZfddddfddZd d Zd d Zd dZddZ ddZ ddZ ddZ ddZ dS)r a 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. NFTc Csd}f}i}t|}|dkr(|\}}}nr|dkrh|\} } t| tr\| }t| trV| }qf| }q| | }}n2|dkr|\}t|tr|}nt|tr|}n|}|rtj|||fStj||||fS)Nrrryr)rr1rDrWr) rrr"rr  from_kallrErF_lenfirstsecondrrrr<s0      z _Call.__new__cCs||_||_||_dS)N)r"rr)r}rr"rr rrrrr;]sz_Call.__init__c Cs>|tkr dSy t|}Wntk r,dSXd}t|dkrH|\}}n |\}}}d}|dkrjfi}}n|dkr~|\}}}n|dkr|\} t| tr| }i}n"t| tr| }fi}}nf}| }nV|dkr|\} } t| tr | }t| tr| i}}n f| }}n | | }}ndS|r.||kr.dS||f||fkS)NTFrryrrr)r rrr1rWrD) r}ryZ len_otherZ self_nameZ self_argsZ self_kwargsZ other_nameZ other_argsZ other_kwargsrrrrrrrxdsJ               z _Call.__eq__cCs |j| S)N)rx)r}ryrrrr{sz _Call.__ne__cOs<|jdkrtd||fddS|jd}t|j||f||dS)Nrz())r")r"r)r"r )r}rErFr"rrrr>s  z_Call.__call__cCs2|jdkrt|ddSd|j|f}t||ddS)NF)r"rz%s.%s)r"rr)r"r )r}r$r"rrrrs  z_Call.__getattr__cOs|jd||S)Nr)r)r}rErFrrrrsz _Call.countcOs|jd||S)Nindex)r)r}rErFrrrrsz _Call.indexcCs||js&|jpd}|jdr"d|}|St|dkr@d}|\}}n0|\}}}|sTd}n|jdshd|}nd|}t|||S)Nr z()zcall%sryzcall.%s)rr"r rr)r}r"rErFrrrr~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)rrrrlr)r}valsr rrr call_lists   z_Call.call_list)r7r8r9rNrr;rxr{r>rrrr~rrrrrr )s  3r )rcKs.t|rt|}t|t}d|i}|r0d|i}n |dkr.rrrrr)r1bytesr) read_dataZ data_as_listliner)rr_iterate_read_data s  rcsfdd}fdd}fddtdkrjtjrfddl}ttt|jjtt|j ant a|dkr~t d t d }t td j _tdgdj_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) readlinesrprV)rErF)_statehandlerr_readlines_side_effect s z)mock_open.._readlines_side_effectcs(jjdk rjjStjdS)Nr)readrpr/r)rErF)rrrrr_read_side_effect s z$mock_open.._read_side_effectc3s8jjdk rxjjVqWxdD] }|Vq&WdS)Nr)readlinerp)r)rrrr_readline_side_effect s  z(mock_open.._readline_side_effectNropen)r"r)rrcs6td<jjdkr2d<dj_tS)Nrr)rrrvr )rErF)rrrrrr reset_data s    zmock_open..reset_data) file_specrRrY_iorVrr TextIOWrapperunionBytesIOfilerrr'rprwriterrrrv)rrrrrrr)rrrrrr s2  $     c@s(eZdZdZddZddZddZdS) 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|S)N)r)r}rFrrrr szPropertyMock._get_child_mockcCs|S)Nr)r}rZobj_typerrrrU szPropertyMock.__get__cCs ||dS)Nr)r}rrrrrrV szPropertyMock.__set__N)r7r8r9rNrrUrVrrrrr s)rrrrrrr r r r r rrrrr)F)F)rprrvrrrrr)NFNNN)rQrRrSrTrUrVrWrXrYrZr[r\r]r^r_r`rar~rrbrc)rrr;rrerfrg)FFNN)Nr) __future__r__all__ functoolsrinspectrr)r- ImportErrorr+typesrrRrZ pbr.versionrZsemantic_versionZ_vZrelease_stringrZ version_tuplerr signaturer?r<ZfuncsigsrA NameErrorrrDlongint BaseExceptionrrSrrrrr0r2platformr$langZ Throwable isidentifierr*r%recompileIr'r}builtinrYr superrr0r4rr5r/r6rrrBrMrIrUrXr^rgrbr{r|rrr ZMISSINGrZDELETEDrrZ ClassTyperr3rrrVrlrrrrrrrrrrrr?r@rBrrCrKrMrmultipleZstopallr#Z magic_methodsZnumericsrrZinplacerightextraZ _non_defaultsrrrrrNotImplementedr~rzr|r}rrrrrrrr rrWr r r rrrrxr=rUrrrrrrrrr#s               !  +  e8 ,   1Jv      *  w   F