B
    `\V                 @   s  d dl mZ d dlZd dlZd dlmZ d dlmZmZ d dl	m
Z
 d dlmZ d dlmZ d dlmZmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZmZ d dlmZmZ d dl m!Z! d dl"m#Z#m$Z$ d dl%m&Z& e' Z(G dd dZ)G dd dZ*G dd dZ+G dd dZ,e,Z-eeG dd de.Z/eeG dd de!ee$eeee&	Z0da1d-dd Z2d.d!d"Z3d#d$ Z4G d%d& d&Z5G d'd( d(Z6d)d* Z7ej8e7_9ed/d+d,Z:dS )0    )contextmanagerN)create_accept_header)alsoProvidesimplementer)Configurator)reify)LocalizerRequestMixin)IRequestISession)caller_package)Registry)CallbackMethodsMixin)_get_response_factory)AuthenticationAPIMixinSecurityAPIMixin)get_current_registrymanager)URLMethodsMixin)PYPYInstancePropertyMixin)ViewMethodsMixinc               @   s   e Zd ZdZdZ dd ZdS )DummyRootFactoryNc             C   s   d|kr| j |d  d S )Nzbfg.routes.matchdict)__dict__update)selfrequest r   W/home/kop/projects/devel/pgwui/test_venv/lib/python3.7/site-packages/pyramid/testing.py__init__   s    zDummyRootFactory.__init__)__name__
__module____qualname__
__parent__r   r   r   r   r   r      s   r   c               @   sB   e Zd ZdZdddZdd Zdd	 Zd
d Zdd Zdd Z	dS )DummySecurityPolicyz) A standin for a :term:`security policy`.NTc             C   s:   || _ || _|| _|d krg }|d kr*g }|| _|| _d S )N)userid	_identity
permissiveremember_resultforget_result)r   r$   identityr&   r'   r(   r   r   r   r   $   s    zDummySecurityPolicy.__init__c             C   s   | j S )N)r%   )r   r   r   r   r   r)   6   s    zDummySecurityPolicy.identityc             C   s   | j S )N)r$   )r   r   r   r   r   authenticated_userid9   s    z(DummySecurityPolicy.authenticated_useridc             C   s   | j S )N)r&   )r   r   contextZ
permissionr   r   r   permits<   s    zDummySecurityPolicy.permitsc             K   s   || _ | jS )N)Z
rememberedr'   )r   r   r$   kwr   r   r   remember?   s    zDummySecurityPolicy.rememberc             K   s   d| _ | jS )NT)Z	forgottenr(   )r   r   r-   r   r   r   forgetC   s    zDummySecurityPolicy.forget)NNTNN)
r   r    r!   __doc__r   r)   r*   r,   r.   r/   r   r   r   r   r#   !   s       
r#   c               @   sV   e Zd ZdZdddZdd Zdd ZeeeZd	d
 Z	dddZ
dd Zdd ZdS )DummyTemplateRenderera4  
    An instance of this class is returned from
    :meth:`pyramid.config.Configurator.testing_add_renderer`.  It has a
    helper function (``assert_``) that makes it possible to make an
    assertion which compares data passed to the renderer by the view
    function against expected key/value pairs.
     c             C   s   i | _ || _t|| _d S )N)	_received_string_responseMockTemplate_implementation)r   string_responser   r   r   r   Q   s    zDummyTemplateRenderer.__init__c             C   s   | j S )N)r4   )r   r   r   r   _get_string_responseY   s    z*DummyTemplateRenderer._get_string_responsec             C   s   || _ || j_d S )N)r4   r6   response)r   r9   r   r   r   _set_string_response\   s    z*DummyTemplateRenderer._set_string_responsec             C   s   | j S )N)r6   )r   r   r   r   implementationb   s    z$DummyTemplateRenderer.implementationNc             C   s"   |r| j | | j | | jS )N)r3   r   r7   )r   r-   systemr   r   r   __call__e   s    zDummyTemplateRenderer.__call__c             C   s:   | j |t}|tkr6| jj |t}|tkr6t||S )z Backwards compatibility )r3   get_markerr6   AttributeError)r   kvalr   r   r   __getattr__k   s    z!DummyTemplateRenderer.__getattr__c             K   sn   xh|  D ]\\}}| j|t}|tkrL| jj|t}|tkrLtd| ||kr
td|||f q
W dS )a  Accept an arbitrary set of assertion key/value pairs.  For
        each assertion key/value pair assert that the renderer
        (eg. :func:`pyramid.renderers.render_to_response`)
        received the key with a value that equals the asserted
        value. If the renderer did not receive the key at all, or the
        value received by the renderer doesn't match the assertion
        value, raise an :exc:`AssertionError`.z3A value for key "%s" was not passed to the rendererz+
asserted value for %s: %r
actual value: %rT)itemsr3   r>   r?   r6   AssertionError)r   r-   rA   vmyvalr   r   r   assert_t   s    zDummyTemplateRenderer.assert_)r2   )N)r   r    r!   r0   r   r8   r:   propertyr7   r;   r=   rC   rH   r   r   r   r   r1   H   s   


	r1   c               @   s~   e Zd ZdZdddZdd Zdd Zd	d
 ZdddZdd Z	dd Z
dd ZeZdd Zdd Zdd ZeefddZdS )DummyResourcez0 A dummy :app:`Pyramid` :term:`resource` object.Nc             K   s<   || _ || _|dk	rt| | || _| jjf | i | _dS )a  The resource's ``__name__`` attribute will be set to the
        value of the ``__name__`` argument, and the resource's
        ``__parent__`` attribute will be set to the value of the
        ``__parent__`` argument.  If ``__provides__`` is specified, it
        should be an interface object or tuple of interface objects
        that will be attached to the resulting resource via
        :func:`zope.interface.alsoProvides`. Any extra keywords passed
        in the ``kw`` argument will be set as direct attributes of
        the resource object.

        .. note:: For backwards compatibility purposes, this class can also
                  be imported as :class:`pyramid.testing.DummyModel`.

        N)r   r"   r   r-   r   r   subs)r   r   r"   Z__provides__r-   r   r   r   r      s    
zDummyResource.__init__c             C   s   ||_ | |_|| j|< dS )ai  When the ``__setitem__`` method is called, the object
        passed in as ``val`` will be decorated with a ``__parent__``
        attribute pointing at the dummy resource and a ``__name__``
        attribute that is the value of ``name``.  The value will then
        be returned when dummy resource's ``__getitem__`` is called with
        the name ``name```.N)r   r"   rK   )r   namerB   r   r   r   __setitem__   s    zDummyResource.__setitem__c             C   s   | j | }|S )z/ Return a named subobject (see ``__setitem__``))rK   )r   rL   obr   r   r   __getitem__   s    
zDummyResource.__getitem__c             C   s   | j |= d S )N)rK   )r   rL   r   r   r   __delitem__   s    zDummyResource.__delitem__c             C   s   | j ||S )N)rK   r>   )r   rL   defaultr   r   r   r>      s    zDummyResource.getc             C   s
   | j  S )z& Return the values set by __setitem__ )rK   values)r   r   r   r   rR      s    zDummyResource.valuesc             C   s
   | j  S )z% Return the items set by __setitem__ )rK   rD   )r   r   r   r   rD      s    zDummyResource.itemsc             C   s
   | j  S )z$ Return the keys set by __setitem__ )rK   keys)r   r   r   r   rS      s    zDummyResource.keysc             C   s   dS )NTr   )r   r   r   r   __bool__   s    zDummyResource.__bool__c             C   s
   t | jS )N)lenrK   )r   r   r   r   __len__   s    zDummyResource.__len__c             C   s
   || j kS )N)rK   )r   rL   r   r   r   __contains__   s    zDummyResource.__contains__c             K   sV   | j  }|| | j| j| jf|}t| j|_|tk	rD||_|tk	rR||_|S )au  Create a clone of the resource object.  If ``__name__`` or
        ``__parent__`` arguments are passed, use these values to
        override the existing ``__name__`` or ``__parent__`` of the
        resource.  If any extra keyword args are passed in via the ``kw``
        argument, use these keywords to add to or override existing
        resource keywords (attributes).)	r-   copyr   	__class__r   r"   deepcopyrK   r?   )r   r   r"   r-   Zoldkwinstr   r   r   clone   s    

zDummyResource.clone)NNN)N)r   r    r!   r0   r   rM   rO   rP   r>   rR   rD   rS   __iter__rT   rV   rW   r?   r\   r   r   r   r   rJ      s   

rJ   c               @   sR   e Zd ZdZdZdd Zdd Zddd	Zdd
dZdddZ	dd Z
dd ZdS )DummySessionNTc             C   s   d S )Nr   )r   r   r   r   changed   s    zDummySession.changedc             C   s   |    d S )N)clear)r   r   r   r   
invalidate   s    zDummySession.invalidater2   c             C   s*   |  d| g }|s||kr&|| d S )N_f_)
setdefaultappend)r   msgqueueZallow_duplicatestorager   r   r   flash   s    zDummySession.flashc             C   s   |  d| g }|S )Nrb   )pop)r   rf   rg   r   r   r   	pop_flash   s    zDummySession.pop_flashc             C   s   |  d| g }|S )Nrb   )r>   )r   rf   rg   r   r   r   
peek_flash   s    zDummySession.peek_flashc             C   s   d}|| d< |S )NZ(0123456789012345678901234567890123456789_csrft_r   )r   tokenr   r   r   new_csrf_token  s    zDummySession.new_csrf_tokenc             C   s    |  dd }|d kr|  }|S )Nrl   )r>   rn   )r   rm   r   r   r   get_csrf_token	  s    zDummySession.get_csrf_token)r2   T)r2   )r2   )r   r    r!   creatednewr_   ra   rh   rj   rk   rn   ro   r   r   r   r   r^      s   


r^   c               @   s   e Zd ZdZdZdZdZdZdZdZ	dZ
dZd	Zd	ZeZdddZdd Zdd Zdd ZeeeeZdd Zdd Zdd ZeeeeZedd Zd	S )DummyRequesta  A DummyRequest object (incompletely) imitates a :term:`request` object.

    The ``params``, ``environ``, ``headers``, ``path``, and
    ``cookies`` arguments correspond to their :term:`WebOb`
    equivalents.

    The ``post`` argument,  if passed, populates the request's
    ``POST`` attribute, but *not* ``params``, in order to allow testing
    that the app accepts data for a given view only from POST requests.
    This argument also sets ``self.method`` to "POST".

    Extra keyword arguments are assigned as attributes of the request
    itself.

    Note that DummyRequest does not have complete fidelity with a "real"
    request.  For example, by default, the DummyRequest ``GET`` and ``POST``
    attributes are of type ``dict``, unlike a normal Request's GET and POST,
    which are of type ``MultiDict``. If your code uses the features of
    MultiDict, you should either use a real :class:`pyramid.request.Request`
    or adapt your DummyRequest by replacing the attributes with ``MultiDict``
    instances.

    Other similar incompatibilities exist.  If you need all the features of
    a Request, use the :class:`pyramid.request.Request` class itself rather
    than this class while writing tests.
    GETzhttp://example.comzexample.com:80zexample.comr   r2   zUTF-8N/c       	      K   s   |d kri }|d kri }|d kr$i }|d kr0i }|| _ || _|| _|| _i | _|| _|d k	rjd| _|| _n|| _| j| _	| j| _
| j| _|| _|| _d| _d| _d| _d| _d| _d| _d| _d | _d | _d | _|| _t | _|| _| j| d S )NPOSTr2   r   )environheadersparamscookiesZ	matchdictrs   methodru   application_urlZhost_urlpath_urlurlpathZ	path_infoscript_nameZpath_qsbodyZ	view_namesubpathZ	traversedZvirtual_root_pathr+   rootZvirtual_rootZ
marshalledr^   sessionacceptr   r   )	r   rx   rv   rw   r~   ry   postr   r-   r   r   r   r   A  sJ    zDummyRequest.__init__c             C   s   | j d krt S | j S )N)	_registryr   )r   r   r   r   _get_registrys  s    
zDummyRequest._get_registryc             C   s
   || _ d S )N)r   )r   registryr   r   r   _set_registryx  s    zDummyRequest._set_registryc             C   s
   d | _ d S )N)r   )r   r   r   r   _del_registry{  s    zDummyRequest._del_registryc             C   s   t || _d S )N)r   _accept)r   valuer   r   r   _set_accept  s    zDummyRequest._set_acceptc             C   s   | j d krtd | _ | j S )N)r   r   )r   r   r   r   _get_accept  s    

zDummyRequest._get_acceptc             C   s
   d | _ d S )N)r   )r   r   r   r   _del_accept  s    zDummyRequest._del_acceptc             C   s   t | j}|| S )N)r   r   )r   fr   r   r   r9     s    
zDummyRequest.response)NNNrt   NNN)r   r    r!   r0   rz   r{   hostdomaincontent_lengthZquery_stringcharsetr   r   r   r	   Zrequest_ifacer   r   r   r   rI   r   r   r   r   r   r   r9   r   r   r   r   rr     s8   #      
*rr   Tc             C   s   t   | dkrtd} |dkr&t }t| ||d}|dkr@i }|  t| dddkrb|| t| dr|	  |
  |  |  |  |  |  |  |  yto|o|  W n tk
r   daY nX |j|d |S )a  
    Set :app:`Pyramid` registry and request thread locals for the
    duration of a single unit test.

    Use this function in the ``setUp`` method of a unittest test case
    which directly or indirectly uses:

    - any method of the :class:`pyramid.config.Configurator`
      object returned by this function.

    - the :func:`pyramid.threadlocal.get_current_registry` or
      :func:`pyramid.threadlocal.get_current_request` functions.

    If you use the ``get_current_*`` functions (or call :app:`Pyramid` code
    that uses these functions) without calling ``setUp``,
    :func:`pyramid.threadlocal.get_current_registry` will return a *global*
    :term:`application registry`, which may cause unit tests to not be
    isolated with respect to registrations they perform.

    If the ``registry`` argument is ``None``, a new empty
    :term:`application registry` will be created (an instance of the
    :class:`pyramid.registry.Registry` class).  If the ``registry``
    argument is not ``None``, the value passed in should be an
    instance of the :class:`pyramid.registry.Registry` class or a
    suitable testing analogue.

    After ``setUp`` is finished, the registry returned by the
    :func:`pyramid.threadlocal.get_current_registry` function will
    be the passed (or constructed) registry until
    :func:`pyramid.testing.tearDown` is called (or
    :func:`pyramid.testing.setUp` is called again) .

    If the ``hook_zca`` argument is ``True``, ``setUp`` will attempt
    to perform the operation ``zope.component.getSiteManager.sethook(
    pyramid.threadlocal.get_current_registry)``, which will cause
    the :term:`Zope Component Architecture` global API
    (e.g. :func:`zope.component.getSiteManager`,
    :func:`zope.component.getAdapter`, and so on) to use the registry
    constructed by ``setUp`` as the value it returns from
    :func:`zope.component.getSiteManager`.  If the
    :mod:`zope.component` package cannot be imported, or if
    ``hook_zca`` is ``False``, the hook will not be set.

    If ``settings`` is not ``None``, it must be a dictionary representing the
    values passed to a Configurator as its ``settings=`` argument.

    If ``package`` is ``None`` it will be set to the caller's package. The
    ``package`` setting in the :class:`pyramid.config.Configurator` will
    affect any relative imports made via
    :meth:`pyramid.config.Configurator.include` or
    :meth:`pyramid.config.Configurator.maybe_dotted`.

    This function returns an instance of the
    :class:`pyramid.config.Configurator` class, which can be
    used for further configuration to set up an environment suitable
    for a unit or integration test.  The ``registry`` attribute
    attached to the Configurator instance represents the 'current'
    :term:`application registry`; the same registry will be returned
    by :func:`pyramid.threadlocal.get_current_registry` during the
    execution of the test.
    NZtesting)r   
autocommitpackagesettingsZregisterUtilityF)r   )r   r`   r   r   r   Z_fix_registrygetattrZ_set_settingshasattrZadd_default_response_adaptersZadd_default_renderersZadd_default_accept_view_orderZadd_default_view_predicatesZadd_default_view_deriversZadd_default_route_predicatesZadd_default_tweensZadd_default_securitycommithave_zcahook_zcaImportErrorbegin)r   r   r   r   r   r   configr   r   r   setUp  s8    E


r   c             C   s   | r:t r:yddlm} |  W n tk
r8   da Y nX t }t  |dk	r|d }t|drt|dry|	|j
 W n tk
r   Y nX dS )a  Undo the effects of :func:`pyramid.testing.setUp`.  Use this
    function in the ``tearDown`` method of a unit test that uses
    :func:`pyramid.testing.setUp` in its ``setUp`` method.

    If the ``unhook_zca`` argument is ``True`` (the default), call
    :func:`zope.component.getSiteManager.reset`.  This undoes the
    action of :func:`pyramid.testing.setUp` when called with the
    argument ``hook_zca=True``.  If :mod:`zope.component` cannot be
    imported, ``unhook_zca`` is set to ``False``.
    r   )getSiteManagerFNr   r   r   )r   Zzope.componentr   resetr   r   ri   r`   r   r   r   	TypeError)
unhook_zcar   infor   r   r   r   tearDown  s    
r   c              O   s,   | dd}|dkr"t }||d< t| |S )z- An alias for :func:`pyramid.testing.setUp`. r   N)r>   r   r   )argr-   r   r   r   r   cleanUp#  s
    r   c               @   s(   e Zd ZdZdd Zdd Zdd ZdS )	DummyRendererFactorya  Registered by
    :meth:`pyramid.config.Configurator.testing_add_renderer` as
    a dummy renderer factory.  The indecision about what to use as a
    key (a spec vs. a relative name) is caused by test suites in the
    wild believing they can register either.  The ``factory`` argument
    passed to this constructor is usually the *real* template renderer
    factory, found when ``testing_add_renderer`` is called.c             C   s   || _ || _i | _d S )N)rL   factory	renderers)r   rL   r   r   r   r   r   5  s    zDummyRendererFactory.__init__c             C   s0   || j |< d|kr,|dd\}}|| j |< d S )N:   )r   split)r   specrendererr   relativer   r   r   add:  s    
zDummyRendererFactory.addc             C   sh   |j }| j|}|d krdd|kr>|dd\}}| j|}|d krd| jrX| |}ntd| |S )Nr   r   z%No testing renderer registered for %r)rL   r   r>   r   r   KeyError)r   r   r   r   r   r   r   r   r   r=   @  s    
zDummyRendererFactory.__call__N)r   r    r!   r0   r   r   r=   r   r   r   r   r   ,  s   r   c               @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
r5   c             C   s   i | _ || _d S )N)r3   r9   )r   r9   r   r   r   r   R  s    zMockTemplate.__init__c             C   s   | S )Nr   )r   attrnamer   r   r   rC   V  s    zMockTemplate.__getattr__c             C   s   | S )Nr   )r   r   r   r   r   rO   Y  s    zMockTemplate.__getitem__c             O   s   | j | | jS )N)r3   r   r9   )r   r   r-   r   r   r   r=   \  s    zMockTemplate.__call__N)r   r    r!   r   rC   rO   r=   r   r   r   r   r5   Q  s   r5   c                 sB   d x,| D ]$}t j|rd |dkr
tr
d q
W  fdd}|S )NFTpypyc                s>   t  trrd S  S n" fdd} j|_ j|_|S d S )Nc                 s   rd S  | |S )Nr   )argsr-   )funcskipr   r   wrapperq  s    z+skip_on.<locals>.decorator.<locals>.wrapper)
isinstancetyper   r0   )r   r   )r   )r   r   	decoratori  s    
zskip_on.<locals>.decorator)skip_onos_name
startswithr   )	platformsplatformr   r   )r   r   r   a  s    
r   c          	   c   s.   t | ||||d}z
|V  W dt|d X dS )aF  Returns a context manager for test set up.

    This context manager calls :func:`pyramid.testing.setUp` when
    entering and :func:`pyramid.testing.tearDown` when exiting.

    All arguments are passed directly to :func:`pyramid.testing.setUp`.
    If the ZCA is hooked, it will always be un-hooked in tearDown.

    This context manager allows you to write test code like this:

    .. code-block:: python
        :linenos:

        with testConfig() as config:
            config.add_route('bar', '/bar/{id}')
            req = DummyRequest()
            resp = myview(req)
    )r   r   r   r   r   N)r   )r   r   )r   r   r   r   r   r   r   r   r   
testConfig  s    
r   )NNTTNN)T)NNTTN);
contextlibr   rX   osZwebob.acceptparser   Zzope.interfacer   r   Zpyramid.configr   Zpyramid.decoratorr   Zpyramid.i18nr   Zpyramid.interfacesr	   r
   Zpyramid.pathr   Zpyramid.registryr   Zpyramid.requestr   Zpyramid.responser   Zpyramid.securityr   r   Zpyramid.threadlocalr   r   Zpyramid.urlr   Zpyramid.utilr   r   Zpyramid.viewr   objectr?   r   r#   r1   rJ   Z
DummyModeldictr^   rr   r   r   r   r   r   r5   r   rL   r   r   r   r   r   r   <module>   s`   	'F[#{     
e
"	%