U \=Q@sddlmZdZddlmZddlZddlZddlZddlZz ddl Z Wne k rdddl Z YnXddl m Z mZddlmZddlZddlmZdZed d ed DZddlZz ejZWn"ek rddlZejZYnXzeWnek reZZYnXze Wnek r2e!Z YnXej"rNe#Z$e$fd d Z#[$dde%e DZ&z ej'Z(Wn<ek rddl)Z)ddl*Z*e*+de*j,Z-ddZ(YnXdZ.e/Z0ddZ1ddZ2Gddde3Z4e5e4j6e7fZ8ddZ9dddZ:dd Z;d!d"Zdd'd(Z?d)d*Z@d+d,ZAGd-d.d.e3ZBd/d0ZCGd1d2d2e3ZDeDZEeEjFZFeEjGZHeEjIZJGd3d4d4ZKe5eKZLe5fZMej"re5eLfZMd5d6d7d8d9d:d;dZOGd?d@d@ePZQdAdBZRGdCdDdDe3ZSGdEdFdFe3ZTGdGdHdHeTZUdIdJZVGdKdLdLeTZWGdMdNdNeWeUZXdOdPZYdQdRZZdSdTZ[GdUdVdVe3Z\dWdXZ]eFdddddfdYdZZ^dd[d\Z_eFdddddfd]d^Z`Gd_d`d`e3ZadadbZbdcddZce^e`_3eae`_de_e`_eece`_fdee`_gdfZhdgZiejjreidh7Zidikdjd eiDZldikdkd eiDZmdlZnejjr6dmZnejdnkr:endo7ZnndpZndqdrdsdtdudvdwdxdydzd{d|d}d~ddddddddhZoddZpdddikeheielemengDZqeqeoBZrddddddddhZsdddddddddddZteueueueudddddddddde dddZvddZwddZxddZyewexeydZzddZ{Gddde3Z|Gddde|eUZ}Gddde|eXZ~Gddde3ZGddde3ZeZddZGdddeZeddZdddZddZGddde3Ze5ee5ejfZe5ejjfZdaddZdddZGdd„deXZddĄZdS))absolute_import) __version__ version_infoMock MagicMockpatchsentinelDEFAULTANYcallcreate_autospec FILTER_DIR CallableMixinNonCallableMockNonCallableMagicMock mock_open PropertyMockseal)partialN) ModuleType MethodType) safe_repr)wrapsz3.0.5ccs|]}t|VqdSN)int.0pr/mock.py Isr .cCst|ddr|S||S)N__next__)getattrr")obj_nextrrrnextds r&cCsh|]}|ds|qS_ startswith)rnamerrr ls r,z^[a-z_][a-z0-9_]*$cCs|tjkrdSt|SNF)keywordkwlistregexmatch)stringrrr _isidentifierus r3TcCstt|tSr) issubclasstyperr$rrr_is_instance_mocksr7cCst|tpt|tot|tSr) isinstance BaseException ClassTypesr4r6rrr _is_exceptions r;c@seZdZdgZdS)_slottedaN)__name__ __module__ __qualname__ __slots__rrrrr<sr<cCst|tr6|s6z |j}Wntk r.YdSXd}n,t|tsbz |j}Wntk r`YdSX|rrt|d}n|}z|t|fWStk rYdSXdS)z Given an arbitrary, possibly callable object, try to create a suitable signature object. Return a (reduced func, signature) tuple, or None. NT) r8r:__init__AttributeError FunctionTypes__call__rinspectsignature ValueError)funcZ as_instanceZeat_selfZsig_funcrrr_get_signature_objects$    rIFcsNt|||dkrdS\}fdd}t|||t|_t|_dS)Ncsj||dSrbind _mock_selfargskwargssigrrchecksigsz"_check_signature..checksig)rI_copy_func_detailsr5_mock_check_sig __signature__)rHmock skipfirstinstancerRrrPr_check_signatures    rYc CsbdD]0}zt||t||Wqtk r2YqXqtjr^z |j|_Wntk r\YnXdS)N)r>__doc____text_signature__r? __defaults____kwdefaults__)setattrr#rCsixPY2Z func_defaults)rHfuncopy attributerrrrSs rScCs@t|trdSt|tttfr(t|jSt|dddk r.checksigra)Z _checksig_rVzYdef %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs)) r8r:rIrSr>r3r_Zexec_ _setup_func) rVoriginalrXrWresultrHrRr+contextsrcrarrPr_set_signatures$       rxc s_fdd}fdd}fdd}fdd}fd d }fd d }fd d} fdd} d_d_d_t_t_t_j_j _ j _ |_ |_ |_ | _| _|_|_|_|__dS)Ncs j||Sr) assert_calledrrrVrrry!sz"_setup_func..assert_calledcs j||Sr)assert_not_calledrrrzrrr{#sz&_setup_func..assert_not_calledcs j||Sr)assert_called_oncerrrzrrr|%sz'_setup_func..assert_called_oncecs j||Sr)assert_called_withrrrzrrr}'sz'_setup_func..assert_called_withcs j||Sr)assert_called_once_withrrrzrrr~)sz,_setup_func..assert_called_once_withcs j||Sr)assert_has_callsrrrzrrr+sz%_setup_func..assert_has_callscs j||Sr)assert_any_callrrrzrrr-sz$_setup_func..assert_any_callcs:t_t_j}t|r6|k r6|dSr) _CallList method_calls mock_calls reset_mock return_valuer7)retrarVrrr/s z_setup_func..reset_mockFr)rVcalled call_count call_argsrcall_args_listrrr side_effect_mock_childrenr}r~rrrryr{r|rU_mock_delegate) rarVrQryr{r|r}r~rrrrrrrss8       rscCsd|dd|kS)N__%s__rr+rrr _is_magicOsrc@s(eZdZdZddZddZddZdS) _SentinelObjectz!A unique, named, sentinel object.cCs ||_dSrrselfr+rrrrBUsz_SentinelObject.__init__cCs d|jS)Nz sentinel.%srrrrr__repr__Xsz_SentinelObject.__repr__cCs t|jffSr)_unpickle_sentinelr+rrrr __reduce__[sz_SentinelObject.__reduce__N)r>r?r@rZrBrrrrrrrSsrcCs tt|Sr)r#rrrrrr_src@s eZdZdZddZddZdS) _SentinelzAAccess attributes to return a named object, usable as a sentinel.cCs i|_dSr) _sentinelsrrrrrBesz_Sentinel.__init__cCs|dkr t|j|t|S)Nrn)rCr setdefaultrrrrr __getattr__hsz_Sentinel.__getattr__N)r>r?r@rZrBrrrrrrcsrc@s eZdZdS) OldStyleClassN)r>r?r@rrrrrvsrr_mock_return_valuer_mock_side_effect _mock_parent_mock_new_parent _mock_name_mock_new_namecCs8t|d|}||fdd}||fdd}t||S)NZ_mock_cSs"|j}|dkrt||St||Sr)rr#)rr+ _the_namerQrrr_gets z"_delegating_property.._getcSs*|j}|dkr||j|<n t|||dSr)rrlr^)rvaluer+rrQrrr_sets z"_delegating_property.._set)_allowed_namesaddproperty)r+rrrrrr_delegating_propertys  rc@seZdZddZddZdS)rcCslt|tst||St|}t|}||kr2dStd||dD]"}||||}||krDdSqDdS)NFrT)r8rg __contains__lenrange)rrZ len_valueZlen_selfiZsub_listrrrrs  z_CallList.__contains__cCstt|Sr)pprintZpformatrgrrrrrsz_CallList.__repr__N)r>r?r@rrrrrrrsrcCst|tr*z |j}Wntk r(YnXt|s6dS|jsV|jsV|jdk sV|jdk rZdS|}|dk rz||krrdS|j}q^|r||_||_|r||_||_dS)NFT) r8rDrVrCr7rrrr)parentrr+new_name_parentrrr_check_and_set_parents2   rc@seZdZddZddZdS) _MockItercCst||_dSr)iterr$)rr$rrrrBsz_MockIter.__init__cCs t|jSr)r&r$rrrrr"sz_MockIter.__next__N)r>r?r@rBr"rrrrrsrc@seZdZeZdZddZdS)BaseNcOsdSrrrrNrOrrrrBsz Base.__init__)r>r?r@r rrrBrrrrrsrc @sReZdZdZddZdHddZd d ZdId d ZdJd dZddZ ddZ dZ e e e e Z e ddZedZedZedZedZedZddZddZe eeZdKdd 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&d=d>Z'dLd?d@Z(dAdBZ)dCdDZ*dMdFdGZ+dS)Nrz A non-callable version of `Mock`cOs$t|j|fd|ji}t|}|S)NrZ)r5r>rZobject__new__)clsrNkwnewrXrrrrs zNonCallableMock.__new__NFc Ks|dkr |}|j} || d<|| d<|| d<|| d<d| d<|dk rJ|}d}| dkrZ|dk } |||| | i| d<|| d <d| d <d| d <d| d <d | d<t| d<t| d<t| d<| | d<| r|jf| tt|||||||dS)NrrrrF _mock_sealedTr _mock_wrapsrZ _mock_calledZ_mock_call_argsrZ_mock_call_countZ_mock_call_args_listZ_mock_mock_callsr _mock_unsafe)rl_mock_add_specrconfigure_mock _safe_superrrB)rspecrr+spec_setr _spec_state _new_name _new_parent_spec_as_instance _eat_selfZunsaferOrlrrrrBsD     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^)rrVrbrrr attach_mocks zNonCallableMock.attach_mockcCs|||dSzAdd a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.N)rrrrrrr mock_add_spec"szNonCallableMock.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)rir8r:r5rIdirrl) rrrrrrrresrlrrrr+s"  zNonCallableMock._mock_add_speccCs8|j}|jdk r|jj}|tkr4|j|dd}||_|S)N()rr)rrrr _get_child_mock)rrrrrZ__get_return_valueBs z"NonCallableMock.__get_return_valuecCs,|jdk r||j_n||_t||dddS)Nr)rrrr)rrrrrZ__set_return_valueOs  z"NonCallableMock.__set_return_valuez1The value to be returned when the mock is called.cCs|jdkrt|S|jSr)rr5rrrr __class__[s zNonCallableMock.__class__rrrrrcCsN|j}|dkr|jS|j}|dk rJt|sJt|tsJt|sJt|}||_|Sr)rrrcallabler8rr;)r delegatedZsfrrrZ__get_side_effecthsz!NonCallableMock.__get_side_effectcCs(t|}|j}|dkr||_n||_dSr) _try_iterrrr)rrrrrrZ__set_side_effectss z!NonCallableMock.__set_side_effectcCs|dkr g}t||krdS|t|d|_d|_d|_t|_t|_t|_|r^t |_ |rhd|_ |j D]"}t|tsr|tkrqr||qr|j }t|r||k r||dS)z-Restore the mock object to its initial state.NFr)idappendrrrrrrrr rrrvaluesr8 _SpecState_deletedrr7)rZvisitedrrZchildrrrrr~s,  zNonCallableMock.reset_mockcKsXt|dddD]>\}}|d}|}|}|D]}t||}q6t|||qdS)aZSet attributes on the mock through keyword arguments. Attributes plus return values and side effects can be set on child mocks using standard dot notation and unpacking a dictionary in the method call: >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} >>> mock.configure_mock(**attrs)cSs|ddS)Nrr!)count)entryrrrz0NonCallableMock.configure_mock..)keyr!N)sorteditemssplitpopr#r^)rrOargvalrNfinalr$rrrrrs   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)rr+rrr)rCr _all_magicsrrr*rrmrrr#rr8rr rrrXrr+)rr+rurrrrrsF          zNonCallableMock.__getattr__cCs|jg}|j}|}d}|dgkr$d}|dk rZ|}||j|d}|jdkrRd}|j}q$tt|}|jpnd}t|dkr|ddkr|d7}||d<d|S)Nr!rrrVr)rz().r)rrrrgreversedrrjoin)rZ _name_listrZlastdotZ_firstrrr_extract_mock_names(      z"NonCallableMock._extract_mock_namecCs^|}d}|dkrd|}d}|jdk rDd}|jr8d}||jj}dt|j||t|S)Nr)rVzmock.z name=%rz spec=%rz spec_set=%rz<{}{}{} id='{}'>)rrrr>formatr5r)rr+Z name_stringZ spec_stringrrrrs   zNonCallableMock.__repr__cCstjsttddrt|S|jp$g}tt|}t|j }dd|j D}tjrrdd|D}dd|D}t t ||||S)z8Filter the output of `dir(mock)` to only useful members.__dir__NcSsg|]\}}|tk r|qSr)r)rZm_nameZm_valuerrr sz+NonCallableMock.__dir__..cSsg|]}|ds|qSr'r)rerrrrs cSs"g|]}|drt|r|qSr')r*rrrrrrs )rVr r#rrrrr5rgrlrrrset)rZextrasZ from_typeZ from_dictZfrom_child_mocksrrrrs    zNonCallableMock.__dir__csP|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|<jrBt|sBd|}td|t||S)Nz!Mock object has no attribute '%s'z.Attempting to set unsupported magic method %r.csf||SrrrNrrtrrrr0rz-NonCallableMock.__setattr__..rr!z Cannot set )rr __setattr__rrrlrC_unsupported_magicsrr7r^r5 _get_methodrrrrhasattrr)rr+rmsg mock_namerrrrs<     zNonCallableMock.__setattr__cCs|tkr2|t|jkr2tt||||jkr2dS|j|t}||jkr\tt| |n|t krlt ||tk r||j|=t |j|<dSr) rr5rldelattrrrm_missingrr __delattr__rrC)rr+r$rrrrEs  zNonCallableMock.__delattr__cCs|jpd}t|||S)NrV)r_format_call_signaturerrNrOr+rrr_format_mock_call_signatureWs z+NonCallableMock._format_mock_call_signaturecCs,d}|||}|j}|j|}|||fS)N0expected call not found. Expected: %s Actual: %s)r r)rrNrOmessageexpected_stringrZ actual_stringrrr_format_mock_failure_message\s   z,NonCallableMock._format_mock_failure_messagec Cs|j}|dk rxt|dkr(d}|\}}n |\}}}z||j||fWStk rt}zd|_|WYSd}~XYq|Xn|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. Nrr)rrrK TypeError __traceback__)r_callrQr+rNrOrrrr _call_matcherds   zNonCallableMock._call_matchercCs4|}|jdkr0d|jpd|j|f}t|dS)z/assert that the mock was never called. rz9Expected '%s' to not have been called. Called %s times.%srVNrr _calls_reprAssertionErrorrMrrrrrr{zs 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.rVN)rrrrrrrrys zNonCallableMock.assert_calledcCs4|}|jdks0d|jpd|j|f}t|dS)z3assert that the mock was called only once. rz:Expected '%s' to have been called once. Called %s times.%srVNrrrrrr|s z"NonCallableMock.assert_called_oncecs|jdkr2}d}d||f}t|fdd}f}j}||krt|trr|nd}tt|||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.Nz not called.r cs.}tjr*|dk r*d|t|}|S)Nz{} {})rr_r`rstr)causerrNrOrrr_error_messages z:NonCallableMock.assert_called_with.._error_message)rr rrr8 Exceptionr_ raise_from)rMrNrOexpectedactualZ error_messagerrrrrr}s   z"NonCallableMock.assert_called_withcOs<|}|jdks0d|jpd|j|f}t||j||S)ziassert that the mock was called exactly once and that that call was with the specified arguments.rz3Expected '%s' to be called once. Called %s times.%srV)rrrrr})rMrNrOrrrrrr~s z'NonCallableMock.assert_called_once_withc sfdd|D}t|tr |nd}tfddjD}|sp||krlttdt|jddf|dSt|}g}|D]2}z| |Wqt k r| |YqXq|rttd j pd 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|]}|qSrrrcrrrrsz4NonCallableMock.assert_has_calls..Nc3s|]}|VqdSrrr rrrr sz3NonCallableMock.assert_has_calls..zCalls not found. Expected: %r%sZActual)prefixz@%r does not contain all of %r in its call list, found %r insteadrV)r8rrrr_rrrrgremoverGrrrh)rZcallsZ any_orderrrZ all_callsZ not_foundZkallrrrrs> z NonCallableMock.assert_has_callscs`||f}fddjD}||kr\t|tr8|nd}||}ttd||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|]}|qSrrr rrrrsz3NonCallableMock.assert_any_call..Nz%s call not found)rrr8rr r_rr)rrNrOrrrr rrrrs zNonCallableMock.assert_any_callcKsxt|}t|ts2t|tr"t}qr?r@rZrrBrrrZ"_NonCallableMock__get_return_valueZ"_NonCallableMock__set_return_valueZ"_NonCallableMock__return_value_docrrrrrrrrrZ!_NonCallableMock__get_side_effectZ!_NonCallableMock__set_side_effectrrrrrrrrrr rrr{ryr|r}r~rrrrrrrrrsn  -       &'    %rcCsL|dkr |St|r|St|r$|Sz t|WStk rF|YSXdSr)r;rerrr6rrrrs rc @sBeZdZddedddddddf ddZddZddZd d ZdS) rNrc Ks6||jd<tt|j||||||| | f| ||_dS)Nr)rlrrrBr) rrrrrr+rrrrrrOrrrrB.s  zCallableMixin.__init__cOsdSrrrrrrrT;szCallableMixin._mock_check_sigcOs|j|||j||Sr)rT _mock_callrLrrrrE@s zCallableMixin.__call__cOs|}d|_|jd7_t||fdd}||_|j||jdk }|j}|j}|dk}|j td||f|j } | dk r|r| j t|||f| jdk }|r| jd|}t|||f} | j | | jr|rd} nd} | jdk}| j| |}| j } qt|j } | dk r\t | r"| n,t| sDt| } t | rN| n | ||} | tk r\| S|jtk rn|jS|jdk r|j||S|jS)NTr)tworrr!)rr_Callrrrrrrrrrrr;rer&r rrr)rMrNrOrrZdo_method_callsZmethod_call_nameZmock_call_nameZ is_a_callrZthis_mock_callrZeffectrurrrr'GsV               zCallableMixin._mock_call)r>r?r@r rBrTrEr'rrrrr,s rc@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)r>r?r@rZrrrrrsrcCs8z t||WStk r2t|t||YSXdSr)r#rC __import__)thingcomp import_pathrrr _dot_lookups  r.cCsB|d}|d}t|}|D]}|d|7}t|||}q |S)Nr!rz.%s)rrr*r.)targetZ componentsr-r+r,rrr _importers   r0cCs t|dS)Nis_local)r)patcherrrr _is_startedsr3c@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 rGgetterrbr new_callablercreateZ has_localrautospecrOadditional_patchers) rr5rbrrr7rr8r6rOrrrrBs(z_patch.__init__c CsHt|j|j|j|j|j|j|j|j|j }|j |_ dd|j D|_ |S)NcSsg|] }|qSr)copyrrrrrsz_patch.copy..) r4r5rbrrr7rr8r6rOattribute_namer9)rr2rrrr:s z _patch.copycCst|tr||S||Sr)r8r:decorate_classdecorate_callablerrHrrrrE s  z_patch.__call__cCsNt|D]@}|tjsqt||}t|ds0q|}t||||q|SNrE)rr*r TEST_PREFIXr#rr:r^)rrqattr attr_valuer2rrrr<s    z_patch.decorate_classcs<tdrj|Stfdd|g_S)N patchingsc sg}g}t}zzdjD]@}|}|||jdk rD||q|jt kr||q|t|7}||WW6S||krt |r||t }YnXW5t|D]}|j|qXdSr) rhr__exit__rC __enter__rr;updaterr r3sysexc_info)rNZkeywargs extra_argsZentered_patchersrHpatchingrrHpatchedrrrL"s,          z)_patch.decorate_callable..patched)rrCrrr>rrKrr=s  z_patch.decorate_callablec Cs|}|j}t}d}z|j|}Wn$ttfk rHt||t}YnXd}|tkrft|t rfd|_ |j s|tkrtd ||||fS)NFTz#{} does not have the attribute {!r}) r5rbr rlrCKeyErrorr# _builtinsr8rr7r)rr/r+rtlocalrrr get_originalEs  z_patch.get_originalcCs8|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 | trt| tr|jr|j| d <| || f| }| rt|r|} |dk r|} t| s0t| s0t} | d | f|d d | |_nl|dk r|t k rntd|t krtdt|}|dkr|}t|f||jd|}n|rtd|}||_||_t|j|j||jdk r4i}|jt kr|||j<|j D]$}|!}|jt kr ||q |S|S)zPerform the patch.FNzCan't specify spec and autospec)TNz6Can't provide explicit spec_set *and* spec or autospecTz!Can't use 'spec' with create=TruerErrr+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)"rrrr8rOr6r5r/rrPr r8r:rrirerr5r4rrbrFr7rorrboolr temp_originalr1r^r;r9rE)rrrrr8rOr6rtrOZinheritKlass_kwargsZ this_specZ not_callableZnew_attrrIrJrrrrrE]s                             z_patch.__enter__cGst|s dS|jr0|jtk r0t|j|j|jn>t|j|j|jsnt |j|jr\|jdkrnt|j|j|j|`|`|`t |j D]}t|r|j |qdS)zUndo the patch.N)rZr?r\__annotations__r]) r3r1rSr r^r/rbrr7rrr9rD)rrHr2rrrrDsz_patch.__exit__cCs|}|j||S)z-Activate a patch, returning any created mock.)rE_active_patchesr)rrurrrstarts z _patch.startcCs.z|j|Wntk r$YnX|S)zStop an active patch.)rWr#rGrDrrrrstops z _patch.stop)r>r?r@r;rWrBr:rEr<r=rPrErDrXrYrrrrr4s (~r4c sPzdd\}Wn&ttfk r:tdfYnXfdd}||fS)Nr!rz.Need a valid target to patch. You supplied: %rcstSrr0rr/rrr rz_get_target..)rsplitrrG)r/rbr5rr[r _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. csSrrrr[rrr"rz_patch_object..)r4) r/rbrrr7rr8r6rOr5rr[r _patch_objects r^c stttfkrfdd}n fdd}|s6tdt|}|d\} } t|| | |||||i } | | _|ddD]2\} } t|| | |||||i } | | _| j | qx| 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. cstSrrZrr[rrr@rz!_patch_multiple..csSrrrr[rrrBrz=Must supply at least one keyword argument with patch.multiplerrN) r5unicoderrGrgrr4r;r9r) r/rr7rr8r6rOr5rrbrr2Z this_patcherrr[r_patch_multiple)sH   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]r4) r/rrr7rr8r6rOr5rbrrrrZsE rc@sReZdZdZdddZddZdd Zd d Zd d ZddZ ddZ eZ e Z dS) _patch_dicta# Patch a dictionary, or dictionary like object, and restore the dictionary to its original state after the test. `in_dict` can be a dictionary or a mapping like container. If it is a mapping then it must at least support getting, setting and deleting items plus iterating over keys. `in_dict` can also be a string specifying the name of the dictionary, which will then be fetched by importing it. `values` can be a dictionary of values to set in the dictionary. `values` can also be an iterable of `(key, value)` pairs. If `clear` is True then the dictionary will be cleared before the new values are set. `patch.dict` can also be called with arbitrary keyword arguments to set values in the dictionary:: with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()): ... `patch.dict` can be used as a context manager, decorator or class decorator. When used as a class decorator `patch.dict` honours `patch.TEST_PREFIX` for choosing which methods to wrap. rFcKs,||_t||_|j|||_d|_dSr)in_dictdictrrFclear _original)rrbrrdrOrrrrBs   z_patch_dict.__init__cs.ttrStfdd}|S)Ncs&z||WSXdSr)ra _unpatch_dictrfrrr_innersz$_patch_dict.__call__.._inner)r8r:r<r)rrhrirrgrrEs   z_patch_dict.__call__cCsXt|D]J}t||}|tjrt|drt|j|j|j }||}t |||q|Sr?) rr#r*rr@rrarbrrdr^)rrqrArBZ decoratorZ decoratedrrrr<s   z_patch_dict.decorate_classcCs |dS)zPatch the dict.N)rarrrrrEsz_patch_dict.__enter__cCs|j}t|jtrt|j|_|j}|j}z |}Wn.tk rdi}|D]}||||<qNYnX||_|rxt |z| |Wn*tk r|D]}||||<qYnXdSr) rr8rb basestringr0rdr:rCre _clear_dictrF)rrrbrdrtrrrrras&   z_patch_dict._patch_dictcCsR|j}|j}t|z||Wn*tk rL|D]}||||<q6YnXdSr)rbrerkrFrC)rrbrtrrrrrfsz_patch_dict._unpatch_dictcGs |dS)zUnpatch the dict.F)rf)rrNrrrrDsz_patch_dict.__exit__N)rF) r>r?r@rZrBrEr<rErarfrDrXrYrrrrras   racCs>z |Wn,tk r8t|}|D] }||=q(YnXdSr)rdrCrg)rbkeysrrrrrks  rkcCsttjD] }|q dS)z7Stop all active patches. LIFO to unroll nested patches.N)rr4rWrY)rrrr_patch_stopall%srmZtestzlt le gt ge eq ne getitem setitem delitem len contains iter hash str sizeof enter exit divmod rdivmod neg pos abs invert complex int float index round trunc floor ceil z@add sub mul matmul div floordiv mod lshift rshift and xor or powz truediv ccs|]}d|VqdS)zi%sNrrnrrrr Csccs|]}d|VqdS)zr%sNrrorrrr Dsrz bool next )zfspath z.unicode long nonzero oct hex truediv rtruediv Z__cmp__Z __getslice__Z __setslice__Z __coerce____get____set__ __delete__ __reversed__ __missing__r __reduce_ex__Z__getinitargs____getnewargs__ __getstate__ __setstate__ __getformat__Z __setformat__rr__subclasses__ __format____getnewargs_ex__csfdd}||_|S)z:Turns a callable object (like a mock) into a real functioncs|f||SrrrrNrrHrrmethod]sz_get_method..method)r>)r+rHrrrrr[s rcCsh|] }d|qS)rr)rrrrrr,csrrrBr __prepare____instancecheck____subclasscheck____del__cCs t|Sr)r__hash__rrrrrrrrcCs t|Sr)r__str__rrrrrsrcCs t|Sr)r __sizeof__rrrrrtrcCstt|Sr)r_rrrrrrrurcCs&t|jd|dtt|S)N/)r5r>rrrrrrrrvr)rrrZ __unicode__ __fspath__ry?g?1Z0x1)__lt____gt____le____ge____int__r__len__rD __complex__ __float____bool__Z __nonzero__Z__oct__Z__hex__Z__long__ __index__csfdd}|S)Ncs$jj}|tk r|S|kr dStSNT)__eq__rr NotImplemented)otherret_valrrrrs z_get_eq..__eq__r)rrrrr_get_eqs rcsfdd}|S)Ncs jjtk rtS|krdStSr-)__ne__rr r)rrrrrs  z_get_ne..__ne__r)rrrrr_get_nes rcsfdd}|S)Ncs jj}|tkrtgSt|Sr)__iter__rr r)rrrrrsz_get_iter..__iter__r)rrrrr _get_iters r)rrrcCst|t}|tk r||_dSt|}|dk rdz ||}Wntk rXt|}YnX||_dSt|}|dk r|||_dSr)_return_valuesrmr r_calculate_return_valuerC_side_effect_methodsr)rVrr+ZfixedZreturn_calulatorrZ side_effectorrrr_set_return_values    rc@seZdZddZddZdS) MagicMixincOs&|tt|j|||dSr)_mock_set_magicsrrrBrrrrrBszMagicMixin.__init__cCst}t|dddk rPt|j}t}t|}|D]}|t|jkr2t||q2|tt|j}t|}|D]}t||t ||qndS)Nr) _magicsr# intersectionrrr5rlrr^ MagicProxy)rZ these_magicsZ remove_magicsrr$rrrrs  zMagicMixin._mock_set_magicsN)r>r?r@rBrrrrrrsrc@seZdZdZdddZdS)rz-A version of `MagicMock` that isn't callable.FcCs||||dSrrrrrrrrs z"NonCallableMagicMock.mock_add_specN)Fr>r?r@rZrrrrrrsrc@seZdZdZdddZdS)ra MagicMock is a subclass of Mock with default implementations of most of the magic methods. You can use MagicMock without having to configure the magic methods yourself. If you use the `spec` or `spec_set` arguments then *only* magic methods that exist in the spec will be created. Attributes and the return value of a `MagicMock` will also be `MagicMocks`. FcCs||||dSrrrrrrrs zMagicMock.mock_add_specN)Frrrrrrs rc@s&eZdZddZddZdddZdS) rcCs||_||_dSrr+r)rr+rrrrrB szMagicProxy.__init__cCs8|j}|j}|j|||d}t|||t||||S)N)r+rr)r+rrr^r)rrrmrrr create_mocks  zMagicProxy.create_mockNcCs|Sr)r)rr$r$rrrrsszMagicProxy.__get__)N)r>r?r@rBrrsrrrrr s rc@s,eZdZdZddZddZddZdZdS) _ANYz2A helper object that compares equal to everything.cCsdSrrrrrrrr!sz _ANY.__eq__cCsdSr-rrrrrr$sz _ANY.__ne__cCsdS)Nzrrrrrr'sz _ANY.__repr__N)r>r?r@rZrrrrrrrrrs rcspd|}d}ddd|D}dddfddt|D}|rP|}|rh|r`|d7}||7}||S) Nz%s(%%s)rz, cSsg|] }t|qSr)repr)rrrrrr3sz*_format_call_signature..cSs"tjrt|tr|dS|SdS)Nzutf-8)r_r`r8r_encode)itemrrr encode_item5s z+_format_call_signature..encode_itemcs g|]\}}d||qS)z{}={!r})r)rrrrrrr;s)rrr)r+rNrOr Zformatted_argsZ args_stringZ kwargs_stringrrrr0s rc@seZdZdZd!ddZd"d d Zd d Zd dZdZddZ ddZ ddZ ddZ ddZ eddZeddZddZdd ZdS)#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. rrNFTc Csd}i}t|}|dkr$|\}}}nr|dkrd|\} } t| trX| }t| trR| }qb| }q| | }}n2|dkr|\}t|tr|}nt|tr|}n|}|rt|||fSt||||fS)Nrrqrr)rr8rjrhr) rrr+rr( from_kallrNrO_lenfirstsecondrrrr\s.      z _Call.__new__cCs||_||_||_dSr)rr_mock_from_kall)rrr+rr(rrrrrB|sz_Call.__init__c Csh|tkr dSz t|}Wntk r.YdSXd}t|dkrJ|\}}n |\}}}t|ddr|t|ddr||j|jkr|dSd}|dkrdi}}n|dkr|\}}}n|d kr|\} t| tr| }i}n"t| tr| }di}}nd}| }nV|dkr@|\} } t| tr4| }t| tr(| i}}n d| }}n | | }}ndS|rX||krXdS||f||fkS) NTFrrrrrrqr)r rrr#rr8rhrj) rrZ len_otherZ self_nameZ self_argsZ self_kwargsZ other_nameZ other_argsZ other_kwargsrrrrrrrsR                z _Call.__eq__cCs || Sr)rrrrrrsz _Call.__ne__cOs<|jdkrtd||fddS|jd}t|j||f||dS)Nrrrr)rr)r rrrrEs  z_Call.__call__cCs2|jdkrt|ddSd|j|}t||ddS)NF)r+rz{}.{})r+rr)rr)r)rrAr+rrrrs  z_Call.__getattr__cOs|d||S)Nrrrrrrrsz _Call.countcOs|d||S)Nindexrrrrrrsz _Call.indexcCs(t|dkr|\}}n |\}}}||fS)Nr)rr rrr_get_call_argumentss   z_Call._get_call_argumentscCs |dSNrrrrrrrNsz _Call.argscCs |dS)NrrrrrrrOsz _Call.kwargscCs||js&|jpd}|dr"d|}|St|dkr@d}|\}}n0|\}}}|sTd}n|dshd|}nd|}t|||S)Nr rzcall%srzcall.%s)rrr*rr)rr+rNrOrrrrs       z_Call.__repr__cCs4g}|}|dk r(|jr |||j}qtt|S)zFor a call object that represents multiple calls, `call_list` returns a list of all the intermediate calls as well as the final call.N)rrrrr)rZvalsr+rrr call_lists z_Call.call_list)rrNFT)rNNFT)r>r?r@rZrrBrrrrErrrrrrNrOrrrrrrr)Is*  7  r))rc KsHt|rt|}t|t}d|i}|r0d|i}n |dkrr?r@rBrrrrr s rcCs"t|trt|St|SdSr)r8bytesioBytesIOStringIO) read_datarrr _to_stream s  rcst}|dgfdd}fdd}fddfdd tdkrtjrd dl}ttt|j tt|j ant a|dkrt d t d }t td j_dj_dj_dj_dj_|j_d<dj_|j_j_fdd}||_|_|S)a A helper function to create a mock to replace the use of `open`. It works for `open` called directly or used as a context manager. The `mock` argument is the mock object to configure. If `None` (the default) then a `MagicMock` will be created for you, with the API limited to methods or attributes available on standard file handles. `read_data` is a string for the `read`, `readline` and `readlines` of the file handle to return. This is an empty string by default. Ncs$jjdk rjjSdj||Sr) readlinesrrr_statehandlerr_readlines_side_effect s z)mock_open.._readlines_side_effectcs$jjdk rjjSdj||Sr)readrrrrrr_read_side_effect s z$mock_open.._read_side_effectc?s*D] }|Vqdj||VqdSr)readline)rNrOr)_iter_side_effectrrr_readline_side_effect s z(mock_open.._readline_side_effectc3s0jjdk rjjVq dD] }|Vq dSr)rr)linerrrr s   z$mock_open.._iter_side_effectropen)r+r)rrcs6td<jjdkr2d<dj_tS)Nrr)rrrr rr)rrrrrr reset_data s    zmock_open..reset_data)r file_specr_rj_iorgrr TextIOWrapperunionrfilerrrErwriterrrrr)rVrZ _read_datarrrrr)rrrrrrr s8 $    rc@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|Sr)r)rrOrrrr szPropertyMock._get_child_mockcCs|Srr)rr$Zobj_typerrrrs" szPropertyMock.__get__cCs ||dSrr)rr$rrrrrt$ szPropertyMock.__set__N)r>r?r@rZrrsrtrrrrr src Cs^d|_t|D]J}zt||}Wntk r8YqYnXt|tsFq|j|krt|qdS)aDisable the automatic generation of child mocks. Given an input Mock, seals it to ensure no further mocks will be generated when accessing an attribute that was not already defined. The operation recursively seals the mock passed in, meaning that the mock itself, any mocks generated by accessing one of its attributes, and all assigned mocks without a name or spec will be sealed. TN)rrr#rCr8rrr)rVrArrrrr( s     r)F)F)NFNNN)FFNN)Nr)Z __future__r__all__ functoolsrrrrrGbuiltins ImportErrorZ __builtin__typesrrZ unittest.utilrr_rrrhrrrVZ signaturerFrCZfuncsigsr_ NameErrorrrjZlongrr`r&r%rrN isidentifierr3r.recompileIr0r superrr7r;rr<r5r=rZDescriptorTypesrIrYrSrerirorxrsrrrrrr MISSINGrZDELETEDrrZ ClassTyper:rrrgrrrrrrrrr.r0r3r4r]r^r`rrarkrmrcZmultipleZstopallr@Z magic_methodsZnumericsrjrZinplacerightZextraZ _non_defaultsrrrrrrrrrrrrrrrrrr rr)r r rrrrDrsrrrrrrrrrr"s          !   1  !D`8 ,   2 Lv         >  ~  M