o
    h
F                     @   s   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 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 ddlmZ ddlmZ ejd  ZG dd deeZG dd deZdS )    )AnyOptional)mock)settings)AbstractBaseUser)Http404)TestCase)reverse)	urlencode)slugify)get_dummy_request)Page   )querydict_from_html)WagtailTestUtilsc                       s^  e Zd ZdZe fddZdd Zd&ddZd&d	d
Zd'ddZ	d&ddZ
d&ddZ		d(dedee dee fddZ							d)dedee deeeef  deeeef  dee dee dee dee fddZ			d*dedeeeef  dee dee fd d!Z	"			d+ded#ee deeeef  dee dee f
d$d%Z  ZS ),WagtailPageTestCasezO
    A set of assertions to help write tests for custom Wagtail page types
    c                    s   t    t | _d S N)super
setUpClassr   dummy_request)cls	__class__ ]/var/www/html/ndineBlogger/venv/lib/python3.10/site-packages/wagtail/test/utils/page_tests.pyr      s   
zWagtailPageTestCase.setUpClassc                 C   s   ||  v S r   )allowed_subpage_models)selfparent_modelchild_modelr   r   r   _testCanCreateAt   s   z$WagtailPageTestCase._testCanCreateAtNc                 C   sB   |  ||s| |d|jj|jj|jj|jjf }| |dS )z
        Assert a particular child Page type can be created under a parent
        Page type. ``parent_model`` and ``child_model`` should be the Page
        classes being tested.
        z$Can not create a %s.%s under a %s.%sNr   _formatMessage_meta	app_label
model_namefailureExceptionr   r   r   msgr   r   r   assertCanCreateAt"      

z%WagtailPageTestCase.assertCanCreateAtc                 C   sB   |  ||r| |d|jj|jj|jj|jjf }| |dS )z
        Assert a particular child Page type can not be created under a parent
        Page type. ``parent_model`` and ``child_model`` should be the Page
        classes being tested.
        z Can create a %s.%s under a %s.%sNr    r&   r   r   r   assertCanNotCreateAt5   r)   z(WagtailPageTestCase.assertCanNotCreateAtTc                 C   s  |  |j| d|vrd|v rt|d |d< |rd|d< td|jj|jj|jgd}| jj	||dd}|j
dkrN| |d	|jj|jj|j
f }| ||jg krd
|jvrc| |d}| ||jd
 }|jsv| |d}| |ddd t|j D }	| |d|jj|jj|	f }| ||rtd|jgd}
ntdtjd jgd}
|j|
dfgkr| |d|jj|jj|
|jf }| |dS )aJ  
        Assert that a child of the given Page type can be created under the
        parent, using the supplied POST data.

        ``parent`` should be a Page instance, and ``child_model`` should be a
        Page subclass. ``data`` should be a dict that will be POSTed at the
        Wagtail admin Page creation method.
        slugtitleaction-publishzwagtailadmin_pages:add)argsT)follow   zCreating a %s.%s returned a %dformz Creating a page failed unusuallyz,Creating a page failed for an unknown reason
c                 s   s&    | ]\}}d  |d|V  qdS )z  {}:
    {}z
    N)formatjoin).0fielderrorsr   r   r   	<genexpr>u   s
    
z6WagtailPageTestCase.assertCanCreate.<locals>.<genexpr>z1Validation errors found when creating a %s.%s:
%swagtailadmin_explorewagtailadmin_pages:editpk.  zQCreating a page %s.%s didn't redirect the user to the expected page %s, but to %sN)r(   specific_classr   r	   r"   r#   r$   r;   clientpoststatus_coder!   r%   redirect_chaincontextr7   r4   sorteditemsr   objectsorder_bylast)r   parentr   datar'   publishadd_urlresponser1   r7   expected_urlr   r   r   assertCanCreateH   sv   	

	








z#WagtailPageTestCase.assertCanCreatec                 C       | j t| t||d dS )a   
        Test that the only page types that can be created under
        ``parent_model`` are ``child_models``.

        The list of allowed child models may differ from those set in
        ``Page.subpage_types``, if the child models have set
        ``Page.parent_page_types``.
        r'   N)assertEqualsetr   )r   r   child_modelsr'   r   r   r   assertAllowedSubpageTypes      	
z-WagtailPageTestCase.assertAllowedSubpageTypesc                 C   rO   )a"  
        Test that the only page types that ``child_model`` can be created under
        are ``parent_models``.

        The list of allowed parent models may differ from those set in
        ``Page.parent_page_types``, if the parent models have set
        ``Page.subpage_types``.
        rP   N)rQ   rR   allowed_parent_page_models)r   r   parent_modelsr'   r   r   r   assertAllowedParentPageTypes   rU   z0WagtailPageTestCase.assertAllowedParentPageTypes/page
route_pathr'   c           	      C   s   | | j}|dkr|dd |d }| }|du r1| |dt|j||f }| |dd |	dD }z|j
jj| j|\}}}W dS  tyg   | |d|t|j||d }| |w )z
        Asserts that ``page`` can be routed to without raising a ``Http404`` error.

        For page types with multiple routes, you can use ``route_path`` to specify an alternate route to test.
        rY   NzKFailed to route to "%s" for %s "%s". The page does not belong to any sites.c                 S   s   g | ]}|r|qS r   r   )r5   	componentr   r   r   
<listcomp>   s    z<WagtailPageTestCase.assertPageIsRoutable.<locals>.<listcomp>zqFailed to route to "%(route_path)s" for %(page_type)s "%(page)s". A Http404 was raised for path: "%(full_path)s".)r[   	page_typerZ   	full_path)get_urlr   rstriplstripget_siter!   type__name__r%   split	root_page	localizedspecificrouter   )	r   rZ   r[   r'   pathsitepath_componentsr.   kwargsr   r   r   assertPageIsRoutable   s<   



z(WagtailPageTestCase.assertPageIsRoutableF
query_data	post_datauser
accept_404accept_redirectc	                 C   sf  |r	| j |t || j}	|dkr|	dd |d }	i }
|dur3d|i}
|r3t|dd|
d< zDz|du rB| j j|	|d}n
| j j	|	fi |
}W n! t
yn } z| |d|t|j||d	 }| |d}~ww W |rw| j   n	|r| j   w w |jd
ks|r|jdks|r|jdv st|tjrdS | |d|t|j||j|	d }| |)aE  
        Asserts that ``page`` can be rendered without raising a fatal error.

        For page types with multiple routes, you can use ``route_path`` to specify an alternate route to test.

        When ``post_data`` is provided, the test makes a ``POST`` request with ``post_data`` in the request body. Otherwise, a ``GET`` request is made.

        When supplied, ``query_data`` is converted to a querystring and added to the request URL (regardless of whether ``post_data`` is provided).

        When ``user`` is provided, the test is conducted with them as the active user.

        By default, the assertion will fail if the request to the page URL results in a 301, 302 or 404 HTTP response. If you are testing a page/route
        where a 404 response is expected, you can use ``accept_404=True`` to indicate this, and the assertion will pass when encountering a 404. Likewise,
        if you are testing a page/route where a redirect response is expected, you can use `accept_redirect=True` to indicate this, and the assertion will
        pass when encountering 301 or 302.
        rY   NrI   T)doseqQUERYSTRINGrI   zMFailed to render route "%(route_path)s" for %(page_type)s "%(page)s":
%(exc)s)r[   r^   rZ   excr0   i  )i-  r<   zFailed to render route "%(route_path)s" for %(page_type)s "%(page)s":
A HTTP %(code)s response was received for path: "%(full_path)s".)r[   r^   rZ   coder_   )r>   force_loginAUTH_BACKENDr`   r   ra   rb   r
   getr?   	Exceptionr!   rd   re   r%   logoutr@   
isinstancer   	MagicMock)r   rZ   r[   rp   rq   rr   rs   rt   r'   rk   post_kwargsresper   r   r   assertPageIsRenderable   st   







z*WagtailPageTestCase.assertPageIsRenderablec           	      C   s  |r| | s| |dt|j||d  | |nt| ds)| d| _| j}| j	
|t tdd|jid}z| j	|}W n% tyi } z| j	  | |dt|j||d	 }| |d
}~ww |jdkr| j	  | |dt|j||jd }| ||d
ur|}nt|j dd}d|d< z6z	| j	|| W n  ty } z| |dt|j||d	 }| |d
}~ww W |  | j	  d
S |  | j	  w )a  
        Asserts that the page edit view works for ``page`` without raising a fatal error.

        When ``user`` is provided, the test is conducted with them as the active user. Otherwise, a superuser is created and used for the test.

        After a successful ``GET`` request, a ``POST`` request is made with field data in the request body. If ``post_data`` is provided, that will be used for this purpose. If not, this data will be extracted from the ``GET`` response HTML.
        zeFailed to load edit view for %(page_type)s "%(page)s":
User "%(user)s" have insufficient permissions.)r^   rZ   rr   _pageiseditable_superuserassertpageiseditabler:   page_idrn   zFFailed to load edit view via GET for %(page_type)s "%(page)s":
%(exc)s)r^   rZ   rx   Nr0   zqFailed to load edit view via GET for %(page_type)s "%(page)s":
Received response with HTTP status code: %(code)s.)r^   rZ   ry   page-edit-formform_id r-   zGFailed to load edit view via POST for %(page_type)s "%(page)s":
%(exc)s)permissions_for_usercan_editr!   rd   re   r%   hasattrcreate_superuserr   r>   rz   r{   r	   idr|   r}   r~   r@   r   contentdecoder?   save)	r   rZ   rq   rr   r'   rk   rL   r   data_to_postr   r   r   assertPageIsEditable)  s   
	





	

	z(WagtailPageTestCase.assertPageIsEditabler   modec                 C   s  |st | ds| d| _| j}| j|t |du r3tdd|jid}| j|j	
 }t|dd}td	d|jid}z!| jj||d
| d}	| |	jd | |	j	
 ddd W n& ty }
 z| j  | |dt|j|||
d }| |d}
~
ww z6z| jj|d|id W n! ty }
 z| |dt|j|||
d }| |d}
~
ww W | j  dS | j  w )a  
        Asserts that the page preview view can be loaded for ``page`` without raising a fatal error.

        For page types that support multiple preview modes, ``mode`` can be used to specify the preview mode to be tested.

        When ``user`` is provided, the test is conducted with them as the active user. Otherwise, a superuser is created and used for the test.

        To load the preview, the test client needs to make a ``POST`` request including all required field data in the request body.
        If ``post_data`` is provided, that will be used for this purpose. If not, the method will attempt to extract this data from the page edit view.
        _pageispreviewable_superuserassertpageispreviewableNr:   r   r   r   r   z"wagtailadmin_pages:preview_on_editzmode=)rI   rv   r0   T)is_validis_availablezQFailed to load preview for %(page_type)s "%(page)s" with mode="%(mode)s":
%(exc)s)r^   rZ   r   rx   r   rw   )r   r   r   r>   rz   r{   r	   r   r|   r   r   r   r?   rQ   r@   assertJSONEqualr}   r~   r!   rd   re   r%   )r   rZ   r   rq   rr   r'   	edit_pathhtmlpreview_pathrL   r   r   r   r   assertPageIsPreviewablez  sp   






z+WagtailPageTestCase.assertPageIsPreviewabler   )NT)rY   N)rY   NNNFFN)NNN)r   NNN)re   
__module____qualname____doc__classmethodr   r   r(   r*   rN   rT   rX   r   r   strro   dictr   r   boolr   r   r   __classcell__r   r   r   r   r      s    



L

-	
T
Tr   c                       s   e Zd Z fddZ  ZS )WagtailPageTestsc                    s   t    |   d S r   )r   setUplogin)r   r   r   r   r     s   
zWagtailPageTests.setUp)re   r   r   r   r   r   r   r   r   r     s    r   N)typingr   r   unittestr   django.confr   django.contrib.auth.base_userr   django.httpr   django.testr   django.urlsr	   django.utils.httpr
   django.utils.textr   wagtail.coreutilsr   wagtail.modelsr   	form_datar   wagtail_testsr   AUTHENTICATION_BACKENDSr{   r   r   r   r   r   r   <module>   s&    
   4