/usr/local/lib/python3.6/site-packages/asynctest/__pycache__
NameSizeModeActions
case.cpython-36.pyc149730644editdlrm
helpers.cpython-36.pyc7310644editdlrm
mock.cpython-36.pyc398800644editdlrm
selector.cpython-36.pyc112240644editdlrm
_fail_on.cpython-36.pyc45500644editdlrm
__init__.cpython-36.pyc9070644editdlrm
Edit: /usr/local/lib/python3.6/site-packages/asynctest/__pycache__/mock.cpython-36.pyc (39880B)
3 8%Eg @sdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z y ej j Z Wne k rpdZ YnXGdddZdJZedKZd e jjd<d d Zee jjd <eeZeeZe jjeO_d dZddZddZGdddeZddZddZddZddZGdddeZ Gdd d e Z!Gd!d"d"Z"Gd#d$d$e jj#e!d%Z#Gd&d'd'e"e jj$e!d%Z$Gd(d)d)e jj%e d%Z%Gd*d+d+e"e jj&e d%Z&Gd,d-d-Z'Gd.d/d/e%Z(dLd0d1Z)dMd3d4Z*e jj+Z+e jj,j-Z-d5d6Z.ej/d7d8Z0e0j1Z1e0j2Z2d9d:Z3Gd;d<dd>e jj6Z6e-dd ddde2fd?d@Z7e-dd ddde2fdAdBZ8dd ddde2fdCdDZ9GdEdFdFe jj:Z:e jj;Z;e8e7_e jj?e7_@dGe7_Ae jj,Z,e jjBZBe jjCZCdNdHdIZDdS)Oz Module ``mock`` --------------- Wrapper to unittest.mock reducing the boilerplate when testing asyncio powered code. A mock can behave as a coroutine, as specified in the documentation of :class:`~asynctest.mock.Mock`. NTc@s(eZdZdZddZddZddZdS) _AsyncIteratorz8 Wraps an iterator in an asynchronous iterator. cCs ||_dS)N)iterator)selfrr8/usr/local/lib/python3.6/site-packages/asynctest/mock.py__init__%sz_AsyncIterator.__init__cCs|S)Nr)rrrr __aiter__(sz_AsyncIterator.__aiter__c s(y t|jStk rYnXtdS)N)nextr StopIterationStopAsyncIteration)rrrr __anext__+s  z_AsyncIterator.__anext__N)__name__ __module__ __qualname____doc__rrr rrrrr!sr __aenter__ __aexit__r rFcs&fdd}tjjr"tj|S|S)aV Factory of ``__aiter__`` magic methods for a MagicMock. It creates a function which returns an asynchronous iterator based on the return value of ``mock.__aiter__``. Since __aiter__ used could be a coroutine in Python 3.5 and 3.6, we also support this case. See: https://www.python.org/dev/peps/pep-0525/#id23 cs*jj}|tkrtg}nt|}t|S)N)rZ_mock_return_valueDEFAULTiterr) return_valuer)mockrrrKs  z"_get_async_iter..__aiter__)asyncioiscoroutinefunctionr coroutine)rrr)rr_get_async_iter?s  rcCs|dS)Nr) exceptionrrr_raisedsrcs(tjrStjfdd}|S)z^ Wrap a coroutine (or any function returning an awaitable) in a native coroutine. cs||IdHS)Nr)argskwargs)rrrwrapperqsz'_make_native_coroutine..wrapper)inspectr functoolswraps)rrr)rr_make_native_coroutinehs r#cCs t|tr|jStjj|SdS)N) isinstance _patch_dict _is_startedunittestr)patchingrrrr&xs r&cs8eZdZdZfddZeddZfddZZS)FakeInheritanceMetaz A metaclass which recreates the original inheritance model from unittest.mock. - NonCallableMock > NonCallableMagicMock - NonCallable > Mock - Mock > MagicMock cs&tj|j||d<tj|||dS)N__new__)types MethodType_FakeInheritanceMeta__newsuperr)rnamebasesattrs) __class__rrrszFakeInheritanceMeta.__init__cOs(t|j|fd|ji}tj|f||S)Nr)typer robjectr*)clsrrnewrrrZ__newszFakeInheritanceMeta.__newcs^tj|rdSt|}t|tr4t|ttfr4dSt|trZt|t rZt|tfrZdSdS)NTF) r.__instancecheck__r3 issubclassNonCallableMockNonCallableMagicMockMock CoroutineMock MagicMock)r5obj_type)r2rrr7s   z%FakeInheritanceMeta.__instancecheck__) r rrrr staticmethodr-r7 __classcell__rr)r2rr)s  r)cCs |jdS)N_mock_is_coroutine)__dict__)rrrr_get_is_coroutinesrDcCst|r tnd}||jd<dS)NFrB)bool _is_coroutinerC)rvaluerrr_set_is_coroutinesrHcOsVtjjj||f||g}x*t|D]}tjt||r&|j|q&W||j d<dS)N_spec_coroutines) r'rr9_mock_add_specdirrrgetattrappendrC)rspecrrrIattrrrrrJs rJcOs|jd}||jdkr"t||St|}t|trB|tkrBt}nLt|trRt}ntjjtjd}d|_|jtt |dt j |||S)Nc3s|]}t|VqdS)N)r$).0 baseclass)metarr sz(MockMetaMixin.__new__..)spec_setr)rJrV__code__) anyr'rr9r+CodeTypeco_flagsupdaterJrVr.r*)rZr/base namespaceZ code_mock)r2)rZrr*s zMockMetaMixin.__new__)r rrr*rArr)r2rrWsrWcseZdZfddZZS)IsCoroutineArgMetacsptfdd|Ds^|jtttttddttd|jd|djfdd }||d<tj|||S) Nc3s|]}t|VqdS)N)r$)rXrY)rZrrr[sz-IsCoroutineArgMeta.__new__..z(True if the object mocked is a coroutine)doc)Z_asynctest_get_is_coroutine_asynctest_set_is_coroutine is_coroutinerF __setattr__rcs$|dkr|j|n |||SdS)Nrg)rf)rattrnamerG)wrapped_setattrrrrhs z/IsCoroutineArgMeta.__new__..__setattr__) r^rarDrHpropertyrRrhr.r*)rZr/rbrcrh)r2)rZrjrr*s zIsCoroutineArgMeta.__new__)r rrr*rArr)r2rrdsrdc@s0eZdZdZddZddZddZdd Zd S) AsyncMagicMixina Add support for async magic methods to :class:`MagicMock` and :class:`NonCallableMagicMock`. Actually, it's a shameless copy-paste of :class:`unittest.mock.MagicMixin`: when added to our classes, it will just do exactly what its :mod:`unittest` counterpart does, but for magic methods. It adds some behavior but should be compatible with future additions of :class:`MagicMock`. cOs*|jtjjt|j|||jdS)N)_mock_set_async_magicsr'r _safe_superrlr)rrrrrrrszAsyncMagicMixin.__init__cCst}t|dddk rNtj|j}t|}x$|D]}|t|jkr.t||q.W|tt|j}t|}x"|D]}t||t j j ||qnWdS)N _mock_methods) _async_magicsrL intersectionror3rCdelattrsetsetattrr'rZ MagicProxy)rZ these_magicsZ remove_magicsentryr?rrrrm s   z&AsyncMagicMixin._mock_set_async_magicscOs"tjjj|f|||jdS)N)r'rr= mock_add_specrm)rrrrrrrvszAsyncMagicMixin.mock_add_speccstdd}|dks||kr|tkrtjj|s^tt|tjj|||fdd}n,tjj|d|tt|||j |<t j ||Stjj t j ||dS)Nrocsf||S)Nr)rr)originalrrrrG+sz*AsyncMagicMixin.__setattr__..value)rLrpr'rZ_is_instance_mockrtr3Z _get_methodZ_check_and_set_parent_mock_childrenr4rhrnrl)rr/rGror)rwrrrh"s    zAsyncMagicMixin.__setattr__N)r rrrrrmrvrhrrrrrls  rlcs"eZdZdZdfdd ZZS)r9aH Enhance :class:`unittest.mock.NonCallableMock` with features allowing to mock a coroutine function. If ``is_coroutine`` is set to ``True``, the :class:`NonCallableMock` object will behave so :func:`asyncio.iscoroutinefunction` will return ``True`` with ``mock`` as parameter. If ``spec`` or ``spec_set`` is defined and an attribute is get, :class:`~asynctest.CoroutineMock` is returned instead of :class:`~asynctest.Mock` when the matching spec attribute is a coroutine function. The test author can also specify a wrapped object with ``wraps``. In this case, the :class:`~asynctest.Mock` object behavior is the same as with an :class:`unittest.mock.Mock` object: the wrapped object may have methods defined as coroutine functions. See :class:`unittest.mock.NonCallableMock` Nc s,tjf|||||d||j|dS)N)rNr"r/r\parent)r.rrf)rrNr"r/r\rgryr)r2rrrTszNonCallableMock.__init__)NNNNNN)r rrrrrArr)r2rr9>sr9) metaclasscs"eZdZdZdfdd ZZS)r:zI A version of :class:`~asynctest.MagicMock` that isn't callable. Nc s,tjf|||||d||j|dS)N)rNr"r/r\ry)r.rrf)rrNr"r/r\rgryr)r2rrraszNonCallableMagicMock.__init__)NNNNNN)r rrrrrArr)r2rr:\sr:c@seZdZdZdS)r;aL Enhance :class:`unittest.mock.Mock` so it returns a :class:`~asynctest.CoroutineMock` object instead of a :class:`~asynctest.Mock` object where a method on a ``spec`` or ``spec_set`` object is a coroutine. For instance: >>> class Foo: ... @asyncio.coroutine ... def foo(self): ... pass ... ... def bar(self): ... pass >>> type(asynctest.mock.Mock(Foo()).foo) >>> type(asynctest.mock.Mock(Foo()).bar) The test author can also specify a wrapped object with ``wraps``. In this case, the :class:`~asynctest.Mock` object behavior is the same as with an :class:`unittest.mock.Mock` object: the wrapped object may have methods defined as coroutine functions. If you want to mock a coroutine function, use :class:`CoroutineMock` instead. See :class:`~asynctest.NonCallableMock` for details about :mod:`asynctest` features, and :mod:`unittest.mock` for the comprehensive documentation about mocking. N)r rrrrrrrr;js"r;c@seZdZdZdS)r=a{ Enhance :class:`unittest.mock.MagicMock` so it returns a :class:`~asynctest.CoroutineMock` object instead of a :class:`~asynctest.Mock` object where a method on a ``spec`` or ``spec_set`` object is a coroutine. If you want to mock a coroutine function, use :class:`CoroutineMock` instead. :class:`MagicMock` allows to mock ``__aenter__``, ``__aexit__``, ``__aiter__`` and ``__anext__``. When mocking an asynchronous iterator, you can set the ``return_value`` of ``__aiter__`` to an iterable to define the list of values to be returned during iteration. You can not mock ``__await__``. If you want to mock an object implementing __await__, :class:`CoroutineMock` will likely be sufficient. see :class:`~asynctest.Mock`. .. versionadded:: 0.11 support of asynchronous iterators and asynchronous context managers. N)r rrrrrrrr=sr=c@s`eZdZddZejdddZejdddZejdd Zejd d Z d d Z ddZ dS) _AwaitEventcCs||_d|_dS)N)_mock _condition)rrrrrrsz_AwaitEvent.__init__rc#sfdd}|j|EdHS)z Wait for await. :param skip: How many awaits will be skipped. As a result, the mock should be awaited at least ``skip + 1`` times. cs |jkS)N) await_count)r)skiprr predicatesz#_AwaitEvent.wait..predicateN)wait_for)rrrr)rrwaits z_AwaitEvent.waitc#s&|jjfdd}|j|EdHS)a Wait for the next await. Unlike :meth:`wait` that counts any await, mock has to be awaited once more, disregarding to the current :attr:`asynctest.CoroutineMock.await_count`. :param skip: How many awaits will be skipped. As a result, the mock should be awaited at least ``skip + 1`` more times. cs|jkS)N)r~)r)r~rrrrsz(_AwaitEvent.wait_next..predicateN)r|r~r)rrrr)r~rr wait_nexts z_AwaitEvent.wait_nextc #sDj}z,|jEdHfdd}|j|EdHS|jXdS)a  Wait for a given predicate to become True. :param predicate: A callable that receives mock which result will be interpreted as a boolean value. The final predicate value is the return value. Ncs jS)N)r|r)rrrr _predicatesz(_AwaitEvent.wait_for.._predicate)_get_conditionacquirerrelease)rr conditionrr)rrrrs z_AwaitEvent.wait_forc cs2|j}z|jEdH|jWd|jXdS)N)rr notify_allr)rrrrr_notifys  z_AwaitEvent._notifycCs|jdkrtj|_|jS)ag Creation of condition is delayed, to minimize the change of using the wrong loop. A user may create a mock with _AwaitEvent before selecting the execution loop. Requiring a user to delay creation is error-prone and inflexible. Instead, condition is created when user actually starts to use the mock. N)r}r Condition)rrrrrs  z_AwaitEvent._get_conditioncCs |jjdkS)Nr)r|r~)rrrr__bool__sz_AwaitEvent.__bool__N)r)r) r rrrrrrrrrrrrrrrr{s   r{cseZdZdZejjdZejjdZejjdZ ejjdZ fddZ fdd Z d d Z d d ZddZddZddZdddZddZfddZZS)r<a8 Enhance :class:`~asynctest.mock.Mock` with features allowing to mock a coroutine function. The :class:`~asynctest.CoroutineMock` object will behave so the object is recognized as coroutine function, and the result of a call as a coroutine: >>> mock = CoroutineMock() >>> asyncio.iscoroutinefunction(mock) True >>> asyncio.iscoroutine(mock()) True The result of ``mock()`` is a coroutine which will have the outcome of ``side_effect`` or ``return_value``: - if ``side_effect`` is a function, the coroutine will return the result of that function, - if ``side_effect`` is an exception, the coroutine will raise the exception, - if ``side_effect`` is an iterable, the coroutine will return the next value of the iterable, however, if the sequence of result is exhausted, ``StopIteration`` is raised immediately, - if ``side_effect`` is not defined, the coroutine will return the value defined by ``return_value``, hence, by default, the coroutine returns a new :class:`~asynctest.CoroutineMock` object. If the outcome of ``side_effect`` or ``return_value`` is a coroutine, the mock coroutine obtained when the mock object is called will be this coroutine itself (and not a coroutine returning a coroutine). The test author can also specify a wrapped object with ``wraps``. In this case, the :class:`~asynctest.Mock` object behavior is the same as with an :class:`unittest.mock.Mock` object: the wrapped object may have methods defined as coroutine functions. awaitedr~ await_argsawait_args_listcsNtj||t|jd<t||jd<d|jd<d|jd<tjj|jd<dS)NrFZ _mock_awaitedrZ_mock_await_countZ_mock_await_argsZ_mock_await_args_list)r.rrFrCr{r'r _CallList)rrr)r2rrr;s    zCoroutineMock.__init__csytj||Wnxtk r\}z.j}|dk r>t| r>tjt|WYdd}~Xn0tk r}ztjt|WYdd}~XnXj tjfdd}|S)Nc 3sTztjrEdHSSWdjd7__jjjjEdHXdS)NrQ)r isawaitabler~rrrMrrr)_call _mock_selfresultrrproxyVs   z'CoroutineMock._mock_call..proxy) r. _mock_callr side_effectcallablerrr BaseException call_args)rrrerr)r2)rrrrrHs  zCoroutineMock._mock_callcCs(|}|jdkr$d|jpd}t|dS)za Assert that the mock was awaited at least once. .. versionadded:: 0.12 rz#Expected '%s' to have been awaited.rN)r~ _mock_nameAssertionError)rrmsgrrrassert_awaitedes   zCoroutineMock.assert_awaitedcOs.|}|jdks*d|jpd|jf}t|dS)z` Assert that the mock was awaited exactly once. .. versionadded:: 0.12 rQz:Expected '%s' to have been awaited once. Awaited %s times.rN)r~rr)rrrrrrrrassert_awaited_onceqs  z!CoroutineMock.assert_awaited_oncecs||jdkr(j}td|ffdd}jf}jj}||krxt|trh|nd}t||dS)zn Assert that the last await was with the specified arguments. .. versionadded:: 0.12 NzExpected await: %s Not awaitedcsj}|S)N)Z_format_mock_failure_message)r)rrrrr_error_messages z9CoroutineMock.assert_awaited_with.._error_message)r_format_mock_call_signaturer _call_matcherr$ Exception)rrrexpectedractualcauser)rrrrassert_awaited_with}s   z!CoroutineMock.assert_awaited_withcOs6|}|jdks*d|jpd|jf}t||j||S)z Assert that the mock was awaited exactly once and with the specified arguments. .. versionadded:: 0.12 rQz3Expected '%s' to be awaited once. Awaited %s times.r)r~rrr)rrrrrrrrassert_awaited_once_withs  z&CoroutineMock.assert_awaited_once_withcs^|j||f}fddjD}||krZt|tr<|nd}j||}td||dS)zu Assert the mock has ever been awaited with the specified arguments. .. versionadded:: 0.12 csg|]}j|qSr)r)rXc)rrr sz2CoroutineMock.assert_any_await..Nz%s await not found)rrr$rrr)rrrrrrZexpected_stringr)rrassert_any_awaits zCoroutineMock.assert_any_awaitFc s|fdd|D}t|tr$|nd}tjjfddjD}|sp||krltdtjj|jf|dSt|}g}x:|D]2}y|j|Wqt k r|j |YqXqW|rtdt |f|dS)a Assert the mock has been awaited with the specified calls. The :attr:`await_args_list` list is checked for the awaits. If `any_order` is False (the default) then the awaits must be sequential. There can be extra calls before or after the specified awaits. If `any_order` is True then the awaits can be in any order, but they must all appear in :attr:`await_args_list`. .. versionadded:: 0.12 csg|]}j|qSr)r)rXr)rrrrsz3CoroutineMock.assert_has_awaits..Nc3s|]}j|VqdS)N)r)rXr)rrrr[sz2CoroutineMock.assert_has_awaits..z)Awaits not found. Expected: %r Actual: %rz%r not all found in await list) r$rr'rrrrlistremove ValueErrorrMtuple)rZcallsZ any_orderrrZ all_awaits not_foundZkallr)rrassert_has_awaitss, zCoroutineMock.assert_has_awaitscCs.|}|jdkr*d|jpd|jf}t|dS)zY Assert that the mock was never awaited. .. versionadded:: 0.12 rz9Expected '%s' to not have been awaited. Awaited %s times.rN)r~rr)rrrrrrassert_not_awaiteds  z CoroutineMock.assert_not_awaitedcs4tj||t||_d|_d|_tjj|_ dS)z= See :func:`unittest.mock.Mock.reset_mock()` rN) r. reset_mockr{rr~rr'rrr)rrr)r2rrrs  zCoroutineMock.reset_mock)F)r rrrr'rZ_delegating_propertyrr~rrrrrrrrrrrrrArr)r2rr< s%         ' r<cKstjj|rt|}t|t}tj|}d|i}|r>d|i}n |dkrJi}|rZ|rZd|d<|j|t} t j |rxi}nB|r|rt dt } n,tjj |st} n|r|rtjj| rt} |jd|}|} |dkrd} | f||| |d |} t|tjjrb| } tjj| |} |rtt| _t| | _d | _d| _tjj| _x4dD]} t| | t| | qDWntjj|| |||dk r| r| |j|<|r| rd|krt||dd| d| _x.t |D] }tjj!|rqyt||}Wnt"k rwYnXd|i}|r d|i}t|tjjsPtjj#||| ||}|| j|<n|| }t|tjjrj| j}tjj$|||}||d<tj|rt }nt}|f||||d|}|| j|<tjj|||dt|tjjrt| ||qW| S)a Create a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the spec object as their spec. ``spec`` can be a coroutine function, a class or object with coroutine functions as attributes. If ``spec`` is a coroutine function, and ``instance`` is not ``False``, a :exc:`RuntimeError` is raised. .. versionadded:: 0.12 rNr\NTZ_spec_as_instancezMInstance can not be True when create_autospec is mocking a coroutine functionr/)ry _new_parentrPr/rrrrrrrrrz())instance_name_parentZ _eat_self)ryr/rPr) skipfirst)rrrrrrr)%r'rZ_is_listr3r$rrrar=r isdatadescriptor RuntimeErrorr<Z _callabler:Z_instance_callablepopZ FunctionTypesZ_set_signaturerFr{rr~rrrrtrLZ_check_signaturerxcreate_autospecrrKZ _is_magicAttributeErrorZ _SpecStateZ _must_skip)rNr\rrrrZis_typeis_coroutine_func_kwargsZKlassrPrZ wrapped_mockarurwr6ryrZ child_klassrrrrs                  rrcCs"|dkrtdtd}tjj||S)aI A helper function to create a mock to replace the use of :func:`open()`. It works for :func:`open()` called directly or used as a context manager. :param mock: mock object to configure, by default a :class:`~asynctest.MagicMock` object is created with the API limited to methods or attributes available on standard file handles. :param read_data: string for the :func:`read()` and :func:`readlines()` of the file handle to return. This is an empty string by default. Nopen)r/rN)r=rr'r mock_open)r read_datarrrrks rcCsP|tkrL| rL|jd}t|ttfr4|jdt}tj|rFt |_ nt |_ |S)Nr) r get_originalr$ classmethodr@__get__r4rrr< new_callabler=)patcherr6rrwrrr_update_new_callables   r PatchScopezLIMITED GLOBALc stdrjj|Stj}tj}ytj}Wntk rTd}YnX|p\|sbdS|gfdd|rt}n(|rfdd}|}|rtj |}n}|_t j |S)N patchingsFc s\g}g}g}t}z"yxD]}|j}|jtkr>|j|t|tr|jtkrxx.|D]}|j|jkrX|j |qXWq|j|q|j dk r|j ||j t kr||j |_ q|j t kr||_|j|qW|t|7}||} t| tjStk r2||kr$t|r$|j|tj}YnXWdxt|D]}|j|qBWXdS)N)r __enter__scopeLIMITEDrMr$r%GLOBALin_dict_keep_global_patchattribute_namerar6r mock_to_reuse_PatchedGeneratorrrrr&sysexc_inforeversed__exit__) rr extra_argsZpatchers_to_exitZpatch_dict_with_limited_scoperr(argZlimited_patchinggen)funcrrrpatched_factorysB                 z5_decorate_coroutine_callable..patched_factoryc?s||EdHS)Nr)rr)rrrpatched_generatorsz7_decorate_coroutine_callable..patched_generator) hasattrrrMr isgeneratorfunctionrrrr#rr!r")rZ new_patchingZis_generator_funcrZis_native_coroutine_funcZpatchedrr)rrrr_decorate_coroutine_callables.     .   rcs^eZdZddZddZddZddZd d Zfd d ZdddZ ddZ ddZ Z S)rcCsR||_||_t|dd|_t|dd|_||_dd|D|_dd|D|_dS)Nr rcSsg|]}|jtkr|qSr)rr)rXprrrrsz._PatchedGenerator.__init__..cSsg|]}|jtkr|qSr)rr)rXrrrrrs)rrFrLr rrglobal_patchingslimited_patchings)rrrrgrrrrsz_PatchedGenerator.__init__c Cs6tj$}x|jD]}|j|qW|jSQRXdS)N) contextlib ExitStackr enter_contextpop_all)rstackr(rrr_limited_patchings_stacks  z*_PatchedGenerator._limited_patchings_stackcCs(x"t|jD]}t|r |jq WdS)N)rrr&stop)rr(rrr_stop_global_patchingssz(_PatchedGenerator._stop_global_patchingscCs t|jS)N)repr generator)rrrr__repr__ sz_PatchedGenerator.__repr__cCsDy |j|jjdSQRXWntk r>|jYnXdS)N)rrsendrr)rrrr__next__s  z_PatchedGenerator.__next__c s |jtj|SQRXdS)N)rr.r)rrG)r2rrrs z_PatchedGenerator.sendNc Cs$|j|jj|||SQRXdS)N)rrthrow)rexcrG tracebackrrrrs z_PatchedGenerator.throwcCs.z|j |jjSQRXWd|jXdS)N)rrcloser)rrrrrs z_PatchedGenerator.closecCs |jdS)N)r)rrrr__del__&sz_PatchedGenerator.__del__)NN) r rrrrrrrrrrrrArr)r2rrs   rcsJeZdZedfdd ZddZddZfdd Zfd d ZZ S) _patch)rcstj||||_d|_dS)N)r.rrr)rrrr)r2rrr-sz_patch.__init__c CsNt|j|j|j|j|j|j|j|j|j |j d }|j |_ dd|j D|_ |S)N)rcSsg|] }|jqSr)copy)rXrrrrr:sz_patch.copy..) rgetter attributer6rNcreater\autospecrrrradditional_patchers)rrrrrr2s  z _patch.copycCsj|jdk r^|j|_|j\|_|_t|j|j|j|jdk rXx|j D] }|j qHW|jS|j SdS)N) rrtargetr temp_originalis_localrtrrrr_perform_patch)rr(rrrr>s     z_patch.__enter__cs|j\}}tj}|jdks(|j r,|S|jdkr<|}n|j}t|ft|j|jd|j}||_ ||_ t |j |j||j dk r|jtkr|||j <|S|S)NT)r\r)rr.rrrrEr\rrrrrtrrr6r)rrwlocalrrr6)r2rrrKs"      z_patch._perform_patchcs&t||}|dkrtj|S|SdS)N)rr.decorate_callable)rrwrapped)r2rrrhs  z_patch.decorate_callable) r rrrrrrrrrArr)r2rr,s   rc Ks8tjj|\} } t| | ||||||||d } t| ||S)ao A context manager, function decorator or class decorator which patches the target with the value given by the ``new`` argument. ``new`` specifies which object will replace the ``target`` when the patch is applied. By default, the target will be patched with an instance of :class:`~asynctest.CoroutineMock` if it is a coroutine, or a :class:`~asynctest.MagicMock` object. It is a replacement to :func:`unittest.mock.patch`, but using :mod:`asynctest.mock` objects. When a generator or a coroutine is patched using the decorator, the patch is activated or deactivated according to the ``scope`` argument value: * :const:`asynctest.GLOBAL`: the default, enables the patch until the generator or the coroutine finishes (returns or raises an exception), * :const:`asynctest.LIMITED`: the patch will be activated when the generator or coroutine is being executed, and deactivated when it yields a value and pauses its execution (with ``yield``, ``yield from`` or ``await``). The behavior differs from :func:`unittest.mock.patch` for generators. When used as a context manager, the patch is still active even if the generator or coroutine is paused, which may affect concurrent tasks:: @asyncio.coroutine def coro(): with asynctest.mock.patch("module.function"): yield from asyncio.get_event_loop().sleep(1) @asyncio.coroutine def independent_coro(): assert not isinstance(module.function, asynctest.mock.Mock) asyncio.create_task(coro()) asyncio.create_task(independent_coro()) # this will raise an AssertionError(coro() is scheduled first)! loop.run_forever() :param scope: :const:`asynctest.GLOBAL` or :const:`asynctest.LIMITED`, controls when the patch is activated on generators and coroutines When used as a decorator with a generator based coroutine, the order of the decorators matters. The order of the ``@patch()`` decorators is in the reverse order of the parameters produced by these patches for the patched function. And the ``@asyncio.coroutine`` decorator should be the last since ``@patch()`` conceptually patches the coroutine, not the function:: @patch("module.function2") @patch("module.function1") @asyncio.coroutine def test_coro(self, mock_function1, mock_function2): yield from asyncio.get_event_loop().sleep(1) see :func:`unittest.mock.patch()`. .. versionadded:: 0.6 patch into generators and coroutines with a decorator. )r)r'rZ _get_targetrr) rr6rNrr\rrrrrrrrrrpatchpsA rc s0tfdd|||||||| |d } t| ||S)NcsS)Nrr)rrrsz_patch_object..)r)rr) rrr6rNrr\rrrrrr)rr _patch_objectsr c sttkrfdd}n fdd}|s2tdt|j} | d\} } t|| | ||||i|d } | | _xF| ddD]6\} } t|| | ||||i|d } | | _| jj| qzWfdd }|| } tt || j| _| S) Ncs tjjS)N)r'r _importerr)rrrrsz_patch_multiple..gettercsS)Nrr)rrrrsz=Must supply at least one keyword argument with patch.multipler)rrQcst||jS)N)rr6)r)rrr_updatesz _patch_multiple.._update) r3strrritemsrrrrMmap)rrNrr\rrrrrr rr6rZ this_patcherr r)rrr_patch_multiples(       rcsPeZdZfdeffdd ZddZddZfdd Zd d Zd d Z Z S)r%Fc s*tj|||f|||_d|_g|_dS)NF)r.rrr&_global_patchings)rrvaluesclearrr)r2rrrsz_patch_dict.__init__cCs|jj|dS)N)rrM)rZother_patchingrrrrsz_patch_dict._keep_global_patchcCs\xVt|D]J}t||}|jtjr t|dr t|j|j|j }||}t |||q W|S)N__call__) rKrL startswithr TEST_PREFIXrr%rrrrt)rrUrO attr_value decoratorZ decoratedrrrdecorate_classs   z_patch_dict.decorate_classcs:t|tr|j|St||}|dkr2tj|S|SdS)N)r$r3rrr.r)rrr)r2rrrs     z_patch_dict.__call__cCsd|_t|jtr"tjj|j|_y|jj|_Wn:t k rli|_x|jD]}|j||j|<qPWYnX|j r~t |jy|jj |j Wn4t k rx|j D]}|j ||j|<qWYnXdS)NT)r&r$rr r'rr r _originalrr _clear_dictrar)rkeyrrrr%s     z_patch_dict._patch_dictc Csd|_|jtkrNx<|jD]2}||jks:|j||j|k r|j||j|<qWt|j|jg}x |jD]}|jrh|j|jqhWxN|D]F}y|jj |Wqt k rx|D]}|||j|<qWYqXqWdS)NF) r&rrrrrrrrMrar)rrZ originalsr(rwrrr _unpatch_dicts"       z_patch_dict._unpatch_dict) r rrrrrrrr%rrArr)r2rr%s  r%testccs|Vx |VqWdS)a Helper to use with ``side_effect``, so a mock will return a given value only once, then return another value. When used as a ``side_effect`` value, if one of ``value`` or ``then`` is an :class:`Exception` type, an instance of this exception will be raised. >>> mock.recv = Mock(side_effect=return_once(b"data")) >>> mock.recv() b"data" >>> repr(mock.recv()) 'None' >>> repr(mock.recv()) 'None' >>> mock.recv = Mock(side_effect=return_once(b"data", then=BlockingIOError)) >>> mock.recv() b"data" >>> mock.recv() Traceback BlockingIOError :param value: value to be returned once by the mock when called. :param then: value returned for any subsequent call. .. versionadded:: 0.4 Nr)rGZthenrrr return_onceHsr)rrr )r)FFNN)Nr)N)ErrZasyncio.coroutinesrenumr!r rr+Z unittest.mockr' coroutinesrFrrrSrprZ_return_valuesrZ_side_effect_methodsrsZ _all_magicsrr#r&r3r)rDrHrJrVrWrdrlr9r:r;r=r{r<rrANYsentinelrrEnumrrrr CoroWrapperrrrr rr%rr4dictmultipleZ_patch_stopallZstopallrcallZ PropertyMockrrrrr s    $  E %]e }   X;DG "V