hc99 commited on
Commit
b451e00
·
verified ·
1 Parent(s): 3610c01

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. testbed/wagtail__wagtail/wagtail/admin/admin_url_finder.py +107 -0
  2. testbed/wagtail__wagtail/wagtail/admin/templates/wagtailadmin/home.html +33 -0
  3. testbed/wagtail__wagtail/wagtail/admin/templatetags/wagtailadmin_tags.py +1130 -0
  4. testbed/wagtail__wagtail/wagtail/admin/tests/__init__.py +0 -0
  5. testbed/wagtail__wagtail/wagtail/admin/tests/api/__init__.py +0 -0
  6. testbed/wagtail__wagtail/wagtail/admin/tests/benches.py +98 -0
  7. testbed/wagtail__wagtail/wagtail/admin/tests/pages/__init__.py +0 -0
  8. testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_bulk_actions/__init__.py +0 -0
  9. testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_bulk_actions/test_bulk_action.py +23 -0
  10. testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_bulk_actions/test_bulk_unpublish.py +311 -0
  11. testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_create_page.py +1762 -0
  12. testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_delete_page.py +349 -0
  13. testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_move_page.py +243 -0
  14. testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_page_locking.py +348 -0
  15. testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_preview.py +641 -0
  16. testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_reorder_page.py +142 -0
  17. testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_revisions.py +631 -0
  18. testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_view_draft.py +102 -0
  19. testbed/wagtail__wagtail/wagtail/admin/tests/test_account_management.py +952 -0
  20. testbed/wagtail__wagtail/wagtail/admin/tests/test_admin_search.py +109 -0
  21. testbed/wagtail__wagtail/wagtail/admin/tests/test_audit_log.py +257 -0
  22. testbed/wagtail__wagtail/wagtail/admin/tests/test_buttons_hooks.py +295 -0
  23. testbed/wagtail__wagtail/wagtail/admin/tests/test_collections_views.py +688 -0
  24. testbed/wagtail__wagtail/wagtail/admin/tests/test_compare.py +1553 -0
  25. testbed/wagtail__wagtail/wagtail/admin/tests/test_contentstate.py +2085 -0
  26. testbed/wagtail__wagtail/wagtail/admin/tests/test_dbwhitelister.py +136 -0
  27. testbed/wagtail__wagtail/wagtail/admin/tests/test_dismissibles.py +65 -0
  28. testbed/wagtail__wagtail/wagtail/admin/tests/test_edit_handlers.py +1746 -0
  29. testbed/wagtail__wagtail/wagtail/admin/tests/test_filters.py +100 -0
  30. testbed/wagtail__wagtail/wagtail/admin/tests/test_forms.py +24 -0
  31. testbed/wagtail__wagtail/wagtail/admin/tests/test_html_ruleset.py +47 -0
  32. testbed/wagtail__wagtail/wagtail/admin/tests/test_icon_sprite.py +26 -0
  33. testbed/wagtail__wagtail/wagtail/admin/tests/test_jinja2.py +49 -0
  34. testbed/wagtail__wagtail/wagtail/admin/tests/test_menu.py +317 -0
  35. testbed/wagtail__wagtail/wagtail/admin/tests/test_messages.py +27 -0
  36. testbed/wagtail__wagtail/wagtail/admin/tests/test_moderation_list.py +104 -0
  37. testbed/wagtail__wagtail/wagtail/admin/tests/test_navigation.py +87 -0
  38. testbed/wagtail__wagtail/wagtail/admin/tests/test_page_chooser.py +1204 -0
  39. testbed/wagtail__wagtail/wagtail/admin/tests/test_password_reset.py +103 -0
  40. testbed/wagtail__wagtail/wagtail/admin/tests/test_privacy.py +476 -0
  41. testbed/wagtail__wagtail/wagtail/admin/tests/test_reports_views.py +467 -0
  42. testbed/wagtail__wagtail/wagtail/admin/tests/test_rich_text.py +474 -0
  43. testbed/wagtail__wagtail/wagtail/admin/tests/test_site_summary.py +83 -0
  44. testbed/wagtail__wagtail/wagtail/admin/tests/test_templatetags.py +485 -0
  45. testbed/wagtail__wagtail/wagtail/admin/tests/test_upgrade_notification.py +93 -0
  46. testbed/wagtail__wagtail/wagtail/admin/tests/test_userbar.py +271 -0
  47. testbed/wagtail__wagtail/wagtail/admin/tests/test_views.py +126 -0
  48. testbed/wagtail__wagtail/wagtail/admin/tests/test_views_generic.py +77 -0
  49. testbed/wagtail__wagtail/wagtail/admin/tests/test_whats_new.py +107 -0
  50. testbed/wagtail__wagtail/wagtail/admin/tests/test_widgets.py +643 -0
testbed/wagtail__wagtail/wagtail/admin/admin_url_finder.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.contrib.admin.utils import quote
2
+ from django.core.exceptions import ImproperlyConfigured
3
+ from django.urls import reverse
4
+
5
+ from wagtail.hooks import search_for_hooks
6
+ from wagtail.utils.registry import ObjectTypeRegistry
7
+
8
+ """
9
+ A mechanism for finding the admin edit URL for an arbitrary object instance, optionally applying
10
+ permission checks.
11
+
12
+ url_finder = AdminURLFinder(request.user)
13
+ url_finder.get_edit_url(some_page) # => "/admin/pages/123/edit/"
14
+ url_finder.get_edit_url(some_image) # => "/admin/images/456/"
15
+ url_finder.get_edit_url(some_site) # => None (user does not have edit permission for sites)
16
+
17
+ If the user parameter is omitted, edit URLs are returned without considering permissions.
18
+
19
+ Handlers for new models can be registered via register_admin_url_finder:
20
+
21
+ class SprocketAdminURLFinder(ModelAdminURLFinder):
22
+ edit_url_name = 'wagtailsprockets:edit'
23
+
24
+ register_admin_url_finder(Sprocket, SprocketAdminURLFinder)
25
+ """
26
+
27
+
28
+ class ModelAdminURLFinder:
29
+ """
30
+ Handles admin edit URL lookups for an individual model
31
+ """
32
+
33
+ edit_url_name = None
34
+ permission_policy = None
35
+
36
+ def __init__(self, user=None):
37
+ self.user = user
38
+
39
+ def construct_edit_url(self, instance):
40
+ """
41
+ Return the edit URL for the given instance - regardless of whether the user can access it -
42
+ or None if no edit URL is available.
43
+ """
44
+ if self.edit_url_name is None:
45
+ raise ImproperlyConfigured(
46
+ "%r must define edit_url_name or override construct_edit_url"
47
+ % type(self)
48
+ )
49
+ return reverse(self.edit_url_name, args=(quote(instance.pk),))
50
+
51
+ def get_edit_url(self, instance):
52
+ """
53
+ Return the edit URL for the given instance if one exists and the user has permission for it,
54
+ or None otherwise.
55
+ """
56
+ if (
57
+ self.user
58
+ and self.permission_policy
59
+ and not self.permission_policy.user_has_permission_for_instance(
60
+ self.user, "change", instance
61
+ )
62
+ ):
63
+ return None
64
+ else:
65
+ return self.construct_edit_url(instance)
66
+
67
+
68
+ class NullAdminURLFinder:
69
+ """
70
+ A dummy AdminURLFinder that always returns None
71
+ """
72
+
73
+ def __init__(self, user=None):
74
+ pass
75
+
76
+ def get_edit_url(self, instance):
77
+ return None
78
+
79
+
80
+ finder_classes = ObjectTypeRegistry()
81
+
82
+
83
+ def register_admin_url_finder(model, handler):
84
+ finder_classes.register(model, value=handler)
85
+
86
+
87
+ class AdminURLFinder:
88
+ """
89
+ The 'main' admin URL finder, which searches across all registered models
90
+ """
91
+
92
+ def __init__(self, user=None):
93
+ search_for_hooks() # ensure wagtail_hooks files have been loaded
94
+ self.user = user
95
+ self.finders_by_model = {}
96
+
97
+ def get_edit_url(self, instance):
98
+ model = type(instance)
99
+ try:
100
+ # do we already have a finder for this model and user?
101
+ finder = self.finders_by_model[model]
102
+ except KeyError:
103
+ finder_class = finder_classes.get(instance) or NullAdminURLFinder
104
+ finder = finder_class(self.user)
105
+ self.finders_by_model[model] = finder
106
+
107
+ return finder.get_edit_url(instance)
testbed/wagtail__wagtail/wagtail/admin/templates/wagtailadmin/home.html ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "wagtailadmin/generic/base.html" %}
2
+ {% load wagtailadmin_tags i18n %}
3
+ {% block bodyclass %}homepage{% endblock %}
4
+
5
+ {% block extra_css %}
6
+ {{ block.super }}
7
+ {{ media.css }}
8
+ {% endblock %}
9
+
10
+ {% block content %}
11
+ {% fragment as header_title %}
12
+ {% block branding_welcome %}{% blocktrans trimmed %}Welcome to the {{ site_name }} Wagtail CMS{% endblocktrans %}{% endblock %}
13
+ {% endfragment %}
14
+
15
+
16
+ <div class="nice-padding w-mt-14">
17
+ {% avatar_url user 70 as avatar %}
18
+ {% include "wagtailadmin/shared/header.html" with title=header_title description=user|user_display_name avatar=avatar merged=1 %}
19
+
20
+ {% if panels %}
21
+ {% for panel in panels %}
22
+ {% component panel fallback_render_method=True %}
23
+ {% endfor %}
24
+ {% else %}
25
+ <p>{% trans "This is your dashboard on which helpful information about content you've created will be displayed." %}</p>
26
+ {% endif %}
27
+ </div>
28
+ {% endblock %}
29
+
30
+ {% block extra_js %}
31
+ {{ block.super }}
32
+ {{ media.js }}
33
+ {% endblock %}
testbed/wagtail__wagtail/wagtail/admin/templatetags/wagtailadmin_tags.py ADDED
@@ -0,0 +1,1130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from datetime import datetime
3
+ from urllib.parse import urljoin
4
+
5
+ from django import template
6
+ from django.conf import settings
7
+ from django.contrib.admin.utils import quote
8
+ from django.contrib.humanize.templatetags.humanize import intcomma, naturaltime
9
+ from django.contrib.messages.constants import DEFAULT_TAGS as MESSAGE_TAGS
10
+ from django.http.request import HttpHeaders
11
+ from django.middleware.csrf import get_token
12
+ from django.shortcuts import resolve_url as resolve_url_func
13
+ from django.template import Context
14
+ from django.template.base import token_kwargs
15
+ from django.template.defaultfilters import stringfilter
16
+ from django.templatetags.static import static
17
+ from django.urls import reverse
18
+ from django.urls.exceptions import NoReverseMatch
19
+ from django.utils import timezone
20
+ from django.utils.encoding import force_str
21
+ from django.utils.html import avoid_wrapping, format_html, format_html_join, json_script
22
+ from django.utils.http import urlencode
23
+ from django.utils.safestring import mark_safe
24
+ from django.utils.timesince import timesince
25
+ from django.utils.translation import gettext_lazy as _
26
+
27
+ from wagtail import hooks
28
+ from wagtail.admin.localization import get_js_translation_strings
29
+ from wagtail.admin.menu import admin_menu
30
+ from wagtail.admin.navigation import get_explorable_root_page
31
+ from wagtail.admin.search import admin_search_areas
32
+ from wagtail.admin.staticfiles import versioned_static as versioned_static_func
33
+ from wagtail.admin.ui import sidebar
34
+ from wagtail.admin.utils import get_admin_base_url, get_valid_next_url_from_request
35
+ from wagtail.admin.views.bulk_action.registry import bulk_action_registry
36
+ from wagtail.admin.widgets import ButtonWithDropdown, PageListingButton
37
+ from wagtail.coreutils import camelcase_to_underscore
38
+ from wagtail.coreutils import cautious_slugify as _cautious_slugify
39
+ from wagtail.coreutils import (
40
+ escape_script,
41
+ get_content_type_label,
42
+ get_locales_display_names,
43
+ )
44
+ from wagtail.models import (
45
+ CollectionViewRestriction,
46
+ Locale,
47
+ Page,
48
+ PageViewRestriction,
49
+ UserPagePermissionsProxy,
50
+ )
51
+ from wagtail.telepath import JSContext
52
+ from wagtail.users.utils import get_gravatar_url
53
+
54
+ register = template.Library()
55
+
56
+ register.filter("intcomma", intcomma)
57
+ register.filter("naturaltime", naturaltime)
58
+
59
+
60
+ @register.inclusion_tag("wagtailadmin/shared/breadcrumbs.html", takes_context=True)
61
+ def breadcrumbs(
62
+ context,
63
+ page,
64
+ url_name,
65
+ url_root_name=None,
66
+ include_self=True,
67
+ is_expanded=False,
68
+ page_perms=None,
69
+ querystring_value=None,
70
+ trailing_breadcrumb_title=None,
71
+ classname=None,
72
+ ):
73
+ user = context["request"].user
74
+
75
+ # find the closest common ancestor of the pages that this user has direct explore permission
76
+ # (i.e. add/edit/publish/lock) over; this will be the root of the breadcrumb
77
+ cca = get_explorable_root_page(user)
78
+ if not cca:
79
+ return {"pages": Page.objects.none()}
80
+
81
+ return {
82
+ "pages": page.get_ancestors(inclusive=include_self)
83
+ .descendant_of(cca, inclusive=True)
84
+ .specific(),
85
+ "current_page": page,
86
+ "is_expanded": is_expanded,
87
+ "page_perms": page_perms,
88
+ "querystring_value": querystring_value or "",
89
+ "trailing_breadcrumb_title": trailing_breadcrumb_title, # Only used in collapsible breadcrumb templates
90
+ "url_name": url_name,
91
+ "url_root_name": url_root_name,
92
+ "classname": classname,
93
+ }
94
+
95
+
96
+ @register.inclusion_tag("wagtailadmin/shared/search_other.html", takes_context=True)
97
+ def search_other(context, current=None):
98
+ request = context["request"]
99
+
100
+ return {
101
+ "options_html": admin_search_areas.render_html(request, current),
102
+ "request": request,
103
+ }
104
+
105
+
106
+ @register.filter("ellipsistrim")
107
+ def ellipsistrim(value, max_length):
108
+ if len(value) > max_length:
109
+ truncd_val = value[:max_length]
110
+ if not len(value) == (max_length + 1) and value[max_length + 1] != " ":
111
+ truncd_val = truncd_val[: truncd_val.rfind(" ")]
112
+ return truncd_val + "…"
113
+ return value
114
+
115
+
116
+ @register.filter
117
+ def fieldtype(bound_field):
118
+ try:
119
+ return camelcase_to_underscore(bound_field.field.__class__.__name__)
120
+ except AttributeError:
121
+ try:
122
+ return camelcase_to_underscore(bound_field.__class__.__name__)
123
+ except AttributeError:
124
+ return ""
125
+
126
+
127
+ @register.filter
128
+ def widgettype(bound_field):
129
+ try:
130
+ return camelcase_to_underscore(bound_field.field.widget.__class__.__name__)
131
+ except AttributeError:
132
+ try:
133
+ return camelcase_to_underscore(bound_field.widget.__class__.__name__)
134
+ except AttributeError:
135
+ return ""
136
+
137
+
138
+ def _get_user_page_permissions(context):
139
+ # Create a UserPagePermissionsProxy object to represent the user's global permissions, and
140
+ # cache it in the context for the duration of the page request, if one does not exist already
141
+ if "user_page_permissions" not in context:
142
+ context["user_page_permissions"] = UserPagePermissionsProxy(
143
+ context["request"].user
144
+ )
145
+
146
+ return context["user_page_permissions"]
147
+
148
+
149
+ @register.simple_tag(takes_context=True)
150
+ def page_permissions(context, page):
151
+ """
152
+ Usage: {% page_permissions page as page_perms %}
153
+ Sets the variable 'page_perms' to a PagePermissionTester object that can be queried to find out
154
+ what actions the current logged-in user can perform on the given page.
155
+ """
156
+ return _get_user_page_permissions(context).for_page(page)
157
+
158
+
159
+ @register.simple_tag
160
+ def classnames(*classes):
161
+ """
162
+ Usage <div class="{% classnames "w-base" classname active|yesno:"w-base--active," any_other_var %}"></div>
163
+ Returns any args as a space-separated joined string for using in HTML class names.
164
+ """
165
+ return " ".join([classname.strip() for classname in classes if classname])
166
+
167
+
168
+ @register.simple_tag(takes_context=True)
169
+ def test_collection_is_public(context, collection):
170
+ """
171
+ Usage: {% test_collection_is_public collection as is_public %}
172
+ Sets 'is_public' to True iff there are no collection view restrictions in place
173
+ on this collection.
174
+ Caches the list of collection view restrictions in the context, to avoid repeated
175
+ DB queries on repeated calls.
176
+ """
177
+ if "all_collection_view_restrictions" not in context:
178
+ context[
179
+ "all_collection_view_restrictions"
180
+ ] = CollectionViewRestriction.objects.select_related("collection").values_list(
181
+ "collection__name", flat=True
182
+ )
183
+
184
+ is_private = collection.name in context["all_collection_view_restrictions"]
185
+
186
+ return not is_private
187
+
188
+
189
+ @register.simple_tag(takes_context=True)
190
+ def test_page_is_public(context, page):
191
+ """
192
+ Usage: {% test_page_is_public page as is_public %}
193
+ Sets 'is_public' to True iff there are no page view restrictions in place on
194
+ this page.
195
+ Caches the list of page view restrictions on the request, to avoid repeated
196
+ DB queries on repeated calls.
197
+ """
198
+ if not hasattr(context["request"], "all_page_view_restriction_paths"):
199
+ context[
200
+ "request"
201
+ ].all_page_view_restriction_paths = PageViewRestriction.objects.select_related(
202
+ "page"
203
+ ).values_list(
204
+ "page__path", flat=True
205
+ )
206
+
207
+ is_private = any(
208
+ [
209
+ page.path.startswith(restricted_path)
210
+ for restricted_path in context["request"].all_page_view_restriction_paths
211
+ ]
212
+ )
213
+
214
+ return not is_private
215
+
216
+
217
+ @register.simple_tag
218
+ def hook_output(hook_name):
219
+ """
220
+ Example: {% hook_output 'insert_editor_css' %}
221
+ Whenever we have a hook whose functions take no parameters and return a string, this tag can be used
222
+ to output the concatenation of all of those return values onto the page.
223
+ Note that the output is not escaped - it is the hook function's responsibility to escape unsafe content.
224
+ """
225
+ snippets = [fn() for fn in hooks.get_hooks(hook_name)]
226
+ return mark_safe("".join(snippets))
227
+
228
+
229
+ @register.simple_tag
230
+ def base_url_setting(default=None):
231
+ return get_admin_base_url() or default
232
+
233
+
234
+ @register.simple_tag
235
+ def allow_unicode_slugs():
236
+ return getattr(settings, "WAGTAIL_ALLOW_UNICODE_SLUGS", True)
237
+
238
+
239
+ class EscapeScriptNode(template.Node):
240
+ TAG_NAME = "escapescript"
241
+
242
+ def __init__(self, nodelist):
243
+ super().__init__()
244
+ self.nodelist = nodelist
245
+
246
+ def render(self, context):
247
+ out = self.nodelist.render(context)
248
+ return escape_script(out)
249
+
250
+ @classmethod
251
+ def handle(cls, parser, token):
252
+ nodelist = parser.parse(("end" + EscapeScriptNode.TAG_NAME,))
253
+ parser.delete_first_token()
254
+ return cls(nodelist)
255
+
256
+
257
+ register.tag(EscapeScriptNode.TAG_NAME, EscapeScriptNode.handle)
258
+
259
+
260
+ # Helpers for Widget.render_with_errors, our extension to the Django widget API that allows widgets to
261
+ # take on the responsibility of rendering their own error messages
262
+ @register.filter
263
+ def render_with_errors(bound_field):
264
+ """
265
+ Usage: {{ field|render_with_errors }} as opposed to {{ field }}.
266
+ If the field (a BoundField instance) has errors on it, and the associated widget implements
267
+ a render_with_errors method, call that; otherwise, call the regular widget rendering mechanism.
268
+ """
269
+ widget = bound_field.field.widget
270
+ if bound_field.errors and hasattr(widget, "render_with_errors"):
271
+ return widget.render_with_errors(
272
+ bound_field.html_name,
273
+ bound_field.value(),
274
+ attrs={"id": bound_field.auto_id},
275
+ errors=bound_field.errors,
276
+ )
277
+ else:
278
+ return bound_field.as_widget()
279
+
280
+
281
+ @register.filter
282
+ def has_unrendered_errors(bound_field):
283
+ """
284
+ Return true if this field has errors that were not accounted for by render_with_errors, because
285
+ the widget does not support the render_with_errors method
286
+ """
287
+ return bound_field.errors and not hasattr(
288
+ bound_field.field.widget, "render_with_errors"
289
+ )
290
+
291
+
292
+ @register.filter(is_safe=True)
293
+ @stringfilter
294
+ def cautious_slugify(value):
295
+ return _cautious_slugify(value)
296
+
297
+
298
+ @register.simple_tag(takes_context=True)
299
+ def querystring(context, **kwargs):
300
+ """
301
+ Print out the current querystring. Any keyword arguments to this template
302
+ tag will be added to the querystring before it is printed out.
303
+
304
+ <a href="/page/{% querystring key='value' %}">
305
+
306
+ Will result in something like:
307
+
308
+ <a href="/page/?foo=bar&key=value">
309
+ """
310
+ request = context["request"]
311
+ querydict = request.GET.copy()
312
+ # Can't do querydict.update(kwargs), because QueryDict.update() appends to
313
+ # the list of values, instead of replacing the values.
314
+ for key, value in kwargs.items():
315
+ if value is None:
316
+ # Remove the key if the value is None
317
+ querydict.pop(key, None)
318
+ else:
319
+ # Set the key otherwise
320
+ querydict[key] = str(value)
321
+
322
+ return "?" + querydict.urlencode()
323
+
324
+
325
+ @register.simple_tag(takes_context=True)
326
+ def page_table_header_label(context, label=None, parent_page_title=None, **kwargs):
327
+ """
328
+ Wraps table_header_label to add a title attribute based on the parent page title and the column label
329
+ """
330
+ if label:
331
+ translation_context = {"parent": parent_page_title, "label": label}
332
+ ascending_title_text = (
333
+ _(
334
+ "Sort the order of child pages within '%(parent)s' by '%(label)s' in ascending order."
335
+ )
336
+ % translation_context
337
+ )
338
+ descending_title_text = (
339
+ _(
340
+ "Sort the order of child pages within '%(parent)s' by '%(label)s' in descending order."
341
+ )
342
+ % translation_context
343
+ )
344
+ else:
345
+ ascending_title_text = None
346
+ descending_title_text = None
347
+
348
+ return table_header_label(
349
+ context,
350
+ label=label,
351
+ ascending_title_text=ascending_title_text,
352
+ descending_title_text=descending_title_text,
353
+ **kwargs,
354
+ )
355
+
356
+
357
+ @register.simple_tag(takes_context=True)
358
+ def table_header_label(
359
+ context,
360
+ label=None,
361
+ sortable=True,
362
+ ordering=None,
363
+ sort_context_var="ordering",
364
+ sort_param="ordering",
365
+ sort_field=None,
366
+ ascending_title_text=None,
367
+ descending_title_text=None,
368
+ ):
369
+ """
370
+ A label to go in a table header cell, optionally with a 'sort' link that alternates between
371
+ forward and reverse sorting
372
+
373
+ label = label text
374
+ ordering = current active ordering. If not specified, we will fetch it from the template context variable
375
+ given by sort_context_var. (We don't fetch it from the URL because that wouldn't give the view method
376
+ the opportunity to set a default)
377
+ sort_param = URL parameter that indicates the current active ordering
378
+ sort_field = the value for sort_param that indicates that sorting is currently on this column.
379
+ For example, if sort_param='ordering' and sort_field='title', then a URL parameter of
380
+ ordering=title indicates that the listing is ordered forwards on this column, and a URL parameter
381
+ of ordering=-title indicated that the listing is ordered in reverse on this column
382
+ ascending_title_text = title attribute to use on the link when the link action will sort in ascending order
383
+ descending_title_text = title attribute to use on the link when the link action will sort in descending order
384
+
385
+ To disable sorting on this column, set sortable=False or leave sort_field unspecified.
386
+ """
387
+ if not sortable or not sort_field:
388
+ # render label without a sort link
389
+ return label
390
+
391
+ if ordering is None:
392
+ ordering = context.get(sort_context_var)
393
+ reverse_sort_field = "-%s" % sort_field
394
+
395
+ if ordering == sort_field:
396
+ # currently ordering forwards on this column; link should change to reverse ordering
397
+ attrs = {
398
+ "href": querystring(context, **{sort_param: reverse_sort_field}),
399
+ "class": "icon icon-arrow-down-after teal",
400
+ }
401
+ if descending_title_text is not None:
402
+ attrs["title"] = descending_title_text
403
+
404
+ elif ordering == reverse_sort_field:
405
+ # currently ordering backwards on this column; link should change to forward ordering
406
+ attrs = {
407
+ "href": querystring(context, **{sort_param: sort_field}),
408
+ "class": "icon icon-arrow-up-after teal",
409
+ }
410
+ if ascending_title_text is not None:
411
+ attrs["title"] = ascending_title_text
412
+
413
+ else:
414
+ # not currently ordering on this column; link should change to forward ordering
415
+ attrs = {
416
+ "href": querystring(context, **{sort_param: sort_field}),
417
+ "class": "icon icon-arrow-down-after",
418
+ }
419
+ if ascending_title_text is not None:
420
+ attrs["title"] = ascending_title_text
421
+
422
+ attrs_string = format_html_join(" ", '{}="{}"', attrs.items())
423
+
424
+ return format_html(
425
+ # need whitespace around label for correct positioning of arrow icon
426
+ "<a {attrs}> {label} </a>",
427
+ attrs=attrs_string,
428
+ label=label,
429
+ )
430
+
431
+
432
+ @register.simple_tag(takes_context=True)
433
+ def pagination_querystring(context, page_number, page_key="p"):
434
+ """
435
+ Print out a querystring with an updated page number:
436
+
437
+ {% if page.has_next_page %}
438
+ <a href="{% pagination_link page.next_page_number %}">Next page</a>
439
+ {% endif %}
440
+ """
441
+ return querystring(context, **{page_key: page_number})
442
+
443
+
444
+ @register.inclusion_tag(
445
+ "wagtailadmin/pages/listing/_pagination.html", takes_context=True
446
+ )
447
+ def paginate(context, page, base_url="", page_key="p", classname=""):
448
+ """
449
+ Print pagination previous/next links, and the page count. Take the
450
+ following arguments:
451
+
452
+ page
453
+ The current page of results. This should be a Django pagination `Page`
454
+ instance
455
+
456
+ base_url
457
+ The base URL of the next/previous page, with no querystring.
458
+ This is optional, and defaults to the current page by just printing the
459
+ querystring for the next/previous page.
460
+
461
+ page_key
462
+ The name of the page variable in the query string. Defaults to 'p'.
463
+
464
+ classname
465
+ Extra classes to add to the next/previous links.
466
+ """
467
+ request = context["request"]
468
+ return {
469
+ "base_url": base_url,
470
+ "classname": classname,
471
+ "request": request,
472
+ "page": page,
473
+ "page_key": page_key,
474
+ "paginator": page.paginator,
475
+ }
476
+
477
+
478
+ @register.inclusion_tag("wagtailadmin/pages/listing/_buttons.html", takes_context=True)
479
+ def page_listing_buttons(context, page, page_perms):
480
+ next_url = context.request.path
481
+ button_hooks = hooks.get_hooks("register_page_listing_buttons")
482
+
483
+ buttons = []
484
+ for hook in button_hooks:
485
+ buttons.extend(hook(page, page_perms, next_url))
486
+
487
+ buttons.sort()
488
+
489
+ for hook in hooks.get_hooks("construct_page_listing_buttons"):
490
+ hook(buttons, page, page_perms, context)
491
+
492
+ return {"page": page, "buttons": buttons}
493
+
494
+
495
+ @register.inclusion_tag(
496
+ "wagtailadmin/pages/listing/_modern_dropdown.html", takes_context=True
497
+ )
498
+ def page_header_buttons(context, page, page_perms):
499
+ next_url = context.request.path
500
+ button_hooks = hooks.get_hooks("register_page_header_buttons")
501
+
502
+ buttons = []
503
+ for hook in button_hooks:
504
+ buttons.extend(hook(page, page_perms, next_url))
505
+
506
+ buttons.sort()
507
+ return {
508
+ "page": page,
509
+ "buttons": buttons,
510
+ "title": _("Actions"),
511
+ "icon_name": "dots-horizontal",
512
+ "classes": [
513
+ "w-flex",
514
+ "w-justify-center",
515
+ "w-items-center",
516
+ "w-h-slim-header",
517
+ ],
518
+ "button_classes": [
519
+ "w-p-0",
520
+ "w-w-12",
521
+ "w-h-full",
522
+ "w-text-primary",
523
+ "w-bg-transparent",
524
+ "hover:w-scale-110",
525
+ "w-transition",
526
+ "w-outline-offset-inside",
527
+ "w-relative",
528
+ "w-z-30",
529
+ ],
530
+ "hide_title": True,
531
+ }
532
+
533
+
534
+ @register.inclusion_tag("wagtailadmin/pages/listing/_buttons.html", takes_context=True)
535
+ def bulk_action_choices(context, app_label, model_name):
536
+ bulk_actions_list = list(
537
+ bulk_action_registry.get_bulk_actions_for_model(app_label, model_name)
538
+ )
539
+ bulk_actions_list.sort(key=lambda x: x.action_priority)
540
+
541
+ bulk_action_more_list = []
542
+ if len(bulk_actions_list) > 4:
543
+ bulk_action_more_list = bulk_actions_list[4:]
544
+ bulk_actions_list = bulk_actions_list[:4]
545
+
546
+ next_url = get_valid_next_url_from_request(context["request"])
547
+ if not next_url:
548
+ next_url = context["request"].path
549
+
550
+ bulk_action_buttons = [
551
+ PageListingButton(
552
+ action.display_name,
553
+ reverse(
554
+ "wagtail_bulk_action", args=[app_label, model_name, action.action_type]
555
+ )
556
+ + "?"
557
+ + urlencode({"next": next_url}),
558
+ attrs={"aria-label": action.aria_label},
559
+ priority=action.action_priority,
560
+ classes=action.classes | {"bulk-action-btn"},
561
+ )
562
+ for action in bulk_actions_list
563
+ ]
564
+
565
+ if bulk_action_more_list:
566
+ more_button = ButtonWithDropdown(
567
+ label=_("More"),
568
+ attrs={"title": _("View more bulk actions")},
569
+ classes={"bulk-actions-more", "dropup"},
570
+ button_classes={"button", "button-small"},
571
+ buttons_data=[
572
+ {
573
+ "label": action.display_name,
574
+ "url": reverse(
575
+ "wagtail_bulk_action",
576
+ args=[app_label, model_name, action.action_type],
577
+ )
578
+ + "?"
579
+ + urlencode({"next": next_url}),
580
+ "attrs": {"aria-label": action.aria_label},
581
+ "priority": action.action_priority,
582
+ "classes": {"bulk-action-btn"},
583
+ }
584
+ for action in bulk_action_more_list
585
+ ],
586
+ )
587
+ bulk_action_buttons.append(more_button)
588
+
589
+ return {"buttons": bulk_action_buttons}
590
+
591
+
592
+ @register.simple_tag
593
+ def message_level_tag(message):
594
+ """
595
+ Return the tag for this message's level as defined in
596
+ django.contrib.messages.constants.DEFAULT_TAGS, ignoring the project-level
597
+ MESSAGE_TAGS setting (which end-users might customise).
598
+ """
599
+ return MESSAGE_TAGS.get(message.level)
600
+
601
+
602
+ @register.simple_tag
603
+ def message_tags(message):
604
+ level_tag = message_level_tag(message)
605
+ if message.extra_tags and level_tag:
606
+ return message.extra_tags + " " + level_tag
607
+ elif message.extra_tags:
608
+ return message.extra_tags
609
+ elif level_tag:
610
+ return level_tag
611
+ else:
612
+ return ""
613
+
614
+
615
+ @register.filter("abs")
616
+ def _abs(val):
617
+ return abs(val)
618
+
619
+
620
+ @register.filter
621
+ def admin_urlquote(value):
622
+ return quote(value)
623
+
624
+
625
+ @register.simple_tag
626
+ def avatar_url(user, size=50, gravatar_only=False):
627
+ """
628
+ A template tag that receives a user and size and return
629
+ the appropriate avatar url for that user.
630
+ Example usage: {% avatar_url request.user 50 %}
631
+ """
632
+
633
+ if (
634
+ not gravatar_only
635
+ and hasattr(user, "wagtail_userprofile")
636
+ and user.wagtail_userprofile.avatar
637
+ ):
638
+ return user.wagtail_userprofile.avatar.url
639
+
640
+ if hasattr(user, "email"):
641
+ gravatar_url = get_gravatar_url(user.email, size=size)
642
+ if gravatar_url is not None:
643
+ return gravatar_url
644
+
645
+ return versioned_static_func("wagtailadmin/images/default-user-avatar.png")
646
+
647
+
648
+ @register.simple_tag
649
+ def js_translation_strings():
650
+ return mark_safe(json.dumps(get_js_translation_strings()))
651
+
652
+
653
+ @register.simple_tag
654
+ def notification_static(path):
655
+ """
656
+ Variant of the {% static %}` tag for use in notification emails - tries to form
657
+ a full URL using WAGTAILADMIN_BASE_URL if the static URL isn't already a full URL.
658
+ """
659
+ return urljoin(base_url_setting(), static(path))
660
+
661
+
662
+ @register.simple_tag
663
+ def versioned_static(path):
664
+ """
665
+ Wrapper for Django's static file finder to append a cache-busting query parameter
666
+ that updates on each Wagtail version
667
+ """
668
+ return versioned_static_func(path)
669
+
670
+
671
+ @register.inclusion_tag("wagtailadmin/shared/icon.html", takes_context=False)
672
+ def icon(name=None, classname=None, title=None, wrapped=False, class_name=None):
673
+ """
674
+ Abstracts away the actual icon implementation.
675
+
676
+ Usage:
677
+ {% load wagtailadmin_tags %}
678
+ ...
679
+ {% icon name="cogs" classname="icon--red" title="Settings" %}
680
+
681
+ :param name: the icon name/id, required (string)
682
+ :param classname: defaults to 'icon' if not provided (string)
683
+ :param title: accessible label intended for screen readers (string)
684
+ :return: Rendered template snippet (string)
685
+ """
686
+ if not name:
687
+ raise ValueError("You must supply an icon name")
688
+
689
+ return {
690
+ "name": name,
691
+ # supporting class_name for backwards compatibility
692
+ "classname": classname or class_name or "icon",
693
+ "title": title,
694
+ "wrapped": wrapped,
695
+ }
696
+
697
+
698
+ @register.filter()
699
+ def timesince_simple(d):
700
+ """
701
+ Returns a simplified timesince:
702
+ 19 hours, 48 minutes ago -> 19 hours ago
703
+ 1 week, 1 day ago -> 1 week ago
704
+ 0 minutes ago -> just now
705
+ """
706
+ # Note: Duplicate code in timesince_last_update()
707
+ time_period = timesince(d).split(",")[0]
708
+ if time_period == avoid_wrapping(_("0 minutes")):
709
+ return _("just now")
710
+ return _("%(time_period)s ago") % {"time_period": time_period}
711
+
712
+
713
+ @register.simple_tag
714
+ def timesince_last_update(
715
+ last_update, show_time_prefix=False, user_display_name="", use_shorthand=True
716
+ ):
717
+ """
718
+ Returns:
719
+ - the time of update if last_update is today, if show_time_prefix=True, the output will be prefixed with "at "
720
+ - time since last update otherwise. Defaults to the simplified timesince,
721
+ but can return the full string if needed
722
+ """
723
+ # translation usage below is intentionally verbose to be easier to work with translations
724
+
725
+ if last_update.date() == datetime.today().date():
726
+ if timezone.is_aware(last_update):
727
+ time_str = timezone.localtime(last_update).strftime("%H:%M")
728
+ else:
729
+ time_str = last_update.strftime("%H:%M")
730
+
731
+ if show_time_prefix:
732
+ if user_display_name:
733
+ return _("at %(time)s by %(user_display_name)s") % {
734
+ "time": time_str,
735
+ "user_display_name": user_display_name,
736
+ }
737
+ else:
738
+ return _("at %(time)s") % {"time": time_str}
739
+ else:
740
+ if user_display_name:
741
+ return _("%(time)s by %(user_display_name)s") % {
742
+ "time": time_str,
743
+ "user_display_name": user_display_name,
744
+ }
745
+ else:
746
+ return time_str
747
+ else:
748
+ if use_shorthand:
749
+ # Note: Duplicate code in timesince_simple()
750
+ time_period = timesince(last_update).split(",")[0]
751
+ if time_period == avoid_wrapping(_("0 minutes")):
752
+ if user_display_name:
753
+ return _("just now by %(user_display_name)s") % {
754
+ "user_display_name": user_display_name
755
+ }
756
+ else:
757
+ return _("just now")
758
+ else:
759
+ time_period = timesince(last_update)
760
+
761
+ if user_display_name:
762
+ return _("%(time_period)s ago by %(user_display_name)s") % {
763
+ "time_period": time_period,
764
+ "user_display_name": user_display_name,
765
+ }
766
+ else:
767
+ return _("%(time_period)s ago") % {"time_period": time_period}
768
+
769
+
770
+ @register.filter
771
+ def user_display_name(user):
772
+ """
773
+ Returns the preferred display name for the given user object: the result of
774
+ user.get_full_name() if implemented and non-empty, or user.get_username() otherwise.
775
+ """
776
+ try:
777
+ full_name = user.get_full_name().strip()
778
+ if full_name:
779
+ return full_name
780
+ except AttributeError:
781
+ pass
782
+
783
+ try:
784
+ return user.get_username()
785
+ except AttributeError:
786
+ # we were passed None or something else that isn't a valid user object; return
787
+ # empty string to replicate the behaviour of {{ user.get_full_name|default:user.get_username }}
788
+ return ""
789
+
790
+
791
+ @register.filter
792
+ def format_content_type(content_type):
793
+ return get_content_type_label(content_type)
794
+
795
+
796
+ @register.simple_tag
797
+ def i18n_enabled():
798
+ return getattr(settings, "WAGTAIL_I18N_ENABLED", False)
799
+
800
+
801
+ @register.simple_tag
802
+ def locales():
803
+ return json.dumps(
804
+ [
805
+ {
806
+ "code": locale.language_code,
807
+ "display_name": force_str(locale.get_display_name()),
808
+ }
809
+ for locale in Locale.objects.all()
810
+ ]
811
+ )
812
+
813
+
814
+ @register.simple_tag
815
+ def locale_label_from_id(locale_id):
816
+ """
817
+ Returns the Locale display name given its id.
818
+ """
819
+ return get_locales_display_names().get(locale_id)
820
+
821
+
822
+ @register.simple_tag(takes_context=True)
823
+ def sidebar_collapsed(context):
824
+ request = context.get("request")
825
+ collapsed = request.COOKIES.get("wagtail_sidebar_collapsed", "0")
826
+ if collapsed == "0":
827
+ return False
828
+ return True
829
+
830
+
831
+ @register.simple_tag(takes_context=True)
832
+ def sidebar_props(context):
833
+ request = context["request"]
834
+ search_areas = admin_search_areas.search_items_for_request(request)
835
+ if search_areas:
836
+ search_area = search_areas[0]
837
+ else:
838
+ search_area = None
839
+
840
+ account_menu = [
841
+ sidebar.LinkMenuItem(
842
+ "account", _("Account"), reverse("wagtailadmin_account"), icon_name="user"
843
+ ),
844
+ sidebar.LinkMenuItem(
845
+ "logout", _("Log out"), reverse("wagtailadmin_logout"), icon_name="logout"
846
+ ),
847
+ ]
848
+
849
+ modules = [
850
+ sidebar.WagtailBrandingModule(),
851
+ sidebar.SearchModule(search_area) if search_area else None,
852
+ sidebar.MainMenuModule(
853
+ admin_menu.render_component(request), account_menu, request.user
854
+ ),
855
+ ]
856
+ modules = [module for module in modules if module is not None]
857
+
858
+ return json_script(
859
+ {
860
+ "modules": JSContext().pack(modules),
861
+ },
862
+ element_id="wagtail-sidebar-props",
863
+ )
864
+
865
+
866
+ @register.simple_tag
867
+ def get_comments_enabled():
868
+ return getattr(settings, "WAGTAILADMIN_COMMENTS_ENABLED", True)
869
+
870
+
871
+ @register.simple_tag(takes_context=True)
872
+ def wagtail_config(context):
873
+ request = context["request"]
874
+ config = {
875
+ "CSRF_TOKEN": get_token(request),
876
+ "CSRF_HEADER_NAME": HttpHeaders.parse_header_name(
877
+ getattr(settings, "CSRF_HEADER_NAME")
878
+ ),
879
+ "ADMIN_URLS": {
880
+ "DISMISSIBLES": reverse("wagtailadmin_dismissibles"),
881
+ },
882
+ }
883
+
884
+ default_settings = {
885
+ "WAGTAIL_AUTO_UPDATE_PREVIEW": True,
886
+ "WAGTAIL_AUTO_UPDATE_PREVIEW_INTERVAL": 500,
887
+ }
888
+ config.update(
889
+ {
890
+ option: getattr(settings, option, default)
891
+ for option, default in default_settings.items()
892
+ }
893
+ )
894
+
895
+ return config
896
+
897
+
898
+ @register.simple_tag
899
+ def resolve_url(url):
900
+ # Used by wagtailadmin/shared/pagination_nav.html - given an input that may be a URL route
901
+ # name, or a direct URL path, return it as a direct URL path. On failure (or being passed
902
+ # an empty / None value), return empty string
903
+ if not url:
904
+ return ""
905
+
906
+ try:
907
+ return resolve_url_func(url)
908
+ except NoReverseMatch:
909
+ return ""
910
+
911
+
912
+ @register.simple_tag(takes_context=True)
913
+ def component(context, obj, fallback_render_method=False):
914
+ # Render a component by calling its render_html method, passing request and context from the
915
+ # calling template.
916
+ # If fallback_render_method is true, objects without a render_html method will have render()
917
+ # called instead (with no arguments) - this is to provide deprecation path for things that have
918
+ # been newly upgraded to use the component pattern.
919
+
920
+ has_render_html_method = hasattr(obj, "render_html")
921
+ if fallback_render_method and not has_render_html_method and hasattr(obj, "render"):
922
+ return obj.render()
923
+ elif not has_render_html_method:
924
+ raise ValueError("Cannot render %r as a component" % (obj,))
925
+
926
+ return obj.render_html(context)
927
+
928
+
929
+ class FragmentNode(template.Node):
930
+ def __init__(self, nodelist, target_var):
931
+ self.nodelist = nodelist
932
+ self.target_var = target_var
933
+
934
+ def render(self, context):
935
+ fragment = self.nodelist.render(context) if self.nodelist else ""
936
+ context[self.target_var] = fragment
937
+ return ""
938
+
939
+
940
+ @register.tag(name="fragment")
941
+ def fragment(parser, token):
942
+ """
943
+ Store a template fragment as a variable.
944
+
945
+ Usage:
946
+ {% fragment as header_title %}
947
+ {% blocktrans trimmed %}Welcome to the {{ site_name }} Wagtail CMS{% endblocktrans %}
948
+ {% endfragment %}
949
+
950
+ Copy-paste of slippers’ fragment template tag.
951
+ See https://github.com/mixxorz/slippers/blob/254c720e6bb02eb46ae07d104863fce41d4d3164/slippers/templatetags/slippers.py#L173.
952
+ """
953
+ error_message = "The syntax for fragment is {% fragment as variable_name %}"
954
+
955
+ try:
956
+ tag_name, _, target_var = token.split_contents()
957
+ nodelist = parser.parse(("endfragment",))
958
+ parser.delete_first_token()
959
+ except ValueError:
960
+ if settings.DEBUG:
961
+ raise template.TemplateSyntaxError(error_message)
962
+ return ""
963
+
964
+ return FragmentNode(nodelist, target_var)
965
+
966
+
967
+ class BlockInclusionNode(template.Node):
968
+ """
969
+ Create template-driven tags like Django’s inclusion_tag / InclusionNode, but for block-level tags.
970
+
971
+ Usage:
972
+ {% my_tag status="test" label="Alert" %}
973
+ Proceed with caution.
974
+ {% endmy_tag %}
975
+
976
+ Within `my_tag`’s template, the template fragment will be accessible as the {{ children }} context variable.
977
+
978
+ The output can also be stored as a variable in the parent context:
979
+
980
+ {% my_tag status="test" label="Alert" as my_variable %}
981
+ Proceed with caution.
982
+ {% endmy_tag %}
983
+
984
+ Inspired by slippers’ Component Node.
985
+ See https://github.com/mixxorz/slippers/blob/254c720e6bb02eb46ae07d104863fce41d4d3164/slippers/templatetags/slippers.py#L47.
986
+ """
987
+
988
+ def __init__(self, nodelist, template, extra_context, target_var=None):
989
+ self.nodelist = nodelist
990
+ self.template = template
991
+ self.extra_context = extra_context
992
+ self.target_var = target_var
993
+
994
+ def get_context_data(self, parent_context):
995
+ return parent_context
996
+
997
+ def render(self, context):
998
+ children = self.nodelist.render(context) if self.nodelist else ""
999
+
1000
+ values = {
1001
+ # Resolve the tag’s parameters within the current context.
1002
+ key: value.resolve(context)
1003
+ for key, value in self.extra_context.items()
1004
+ }
1005
+
1006
+ t = context.template.engine.get_template(self.template)
1007
+ # Add the `children` variable in the rendered template’s context.
1008
+ context_data = self.get_context_data({**values, "children": children})
1009
+ output = t.render(Context(context_data, autoescape=context.autoescape))
1010
+
1011
+ if self.target_var:
1012
+ context[self.target_var] = output
1013
+ return ""
1014
+
1015
+ return output
1016
+
1017
+ @classmethod
1018
+ def handle(cls, parser, token):
1019
+ tag_name, *remaining_bits = token.split_contents()
1020
+
1021
+ nodelist = parser.parse((f"end{tag_name}",))
1022
+ parser.delete_first_token()
1023
+
1024
+ extra_context = token_kwargs(remaining_bits, parser)
1025
+
1026
+ # Allow component fragment to be assigned to a variable
1027
+ target_var = None
1028
+ if len(remaining_bits) >= 2 and remaining_bits[-2] == "as":
1029
+ target_var = remaining_bits[-1]
1030
+
1031
+ return cls(nodelist, cls.template, extra_context, target_var)
1032
+
1033
+
1034
+ class DialogNode(BlockInclusionNode):
1035
+ template = "wagtailadmin/shared/dialog/dialog.html"
1036
+
1037
+ def get_context_data(self, parent_context):
1038
+ context = super().get_context_data(parent_context)
1039
+
1040
+ if "title" not in context:
1041
+ raise TypeError("You must supply a title")
1042
+ if "id" not in context:
1043
+ raise TypeError("You must supply an id")
1044
+
1045
+ # Used for determining which icon the message will use
1046
+ message_icon_name = {
1047
+ "info": "info-circle",
1048
+ "warning": "warning",
1049
+ "critical": "warning",
1050
+ "success": "circle-check",
1051
+ }
1052
+
1053
+ message_status = context.get("message_status")
1054
+
1055
+ # If there is a message status then determine which icon to use.
1056
+ if message_status:
1057
+ context["message_icon_name"] = message_icon_name[message_status]
1058
+
1059
+ return context
1060
+
1061
+
1062
+ register.tag("dialog", DialogNode.handle)
1063
+
1064
+
1065
+ class HelpBlockNode(BlockInclusionNode):
1066
+ template = "wagtailadmin/shared/help_block.html"
1067
+
1068
+
1069
+ register.tag("help_block", HelpBlockNode.handle)
1070
+
1071
+
1072
+ class PanelNode(BlockInclusionNode):
1073
+ template = "wagtailadmin/shared/panel.html"
1074
+
1075
+
1076
+ register.tag("panel", PanelNode.handle)
1077
+
1078
+
1079
+ class FieldNode(BlockInclusionNode):
1080
+ template = "wagtailadmin/shared/field.html"
1081
+
1082
+
1083
+ register.tag("field", FieldNode.handle)
1084
+
1085
+
1086
+ class FieldRowNode(BlockInclusionNode):
1087
+ template = "wagtailadmin/shared/forms/field_row.html"
1088
+
1089
+
1090
+ register.tag("field_row", FieldRowNode.handle)
1091
+
1092
+
1093
+ # Button used to open dialogs
1094
+ @register.inclusion_tag("wagtailadmin/shared/dialog/dialog_toggle.html")
1095
+ def dialog_toggle(dialog_id, classname="", text=None):
1096
+ if not dialog_id:
1097
+ raise ValueError("You must supply the dialog ID")
1098
+
1099
+ return {
1100
+ "classname": classname,
1101
+ "text": text,
1102
+ # dialog_id must match the ID of the dialog you are toggling
1103
+ "dialog_id": dialog_id,
1104
+ }
1105
+
1106
+
1107
+ @register.simple_tag()
1108
+ def workflow_status_with_date(workflow_state):
1109
+ translation_context = {
1110
+ "finished_at": naturaltime(workflow_state.current_task_state.finished_at),
1111
+ "started_at": naturaltime(workflow_state.current_task_state.started_at),
1112
+ "task_name": workflow_state.current_task_state.task.name,
1113
+ "status_display": workflow_state.get_status_display,
1114
+ }
1115
+
1116
+ if workflow_state.status == "needs_changes":
1117
+ return _("Changes requested %(finished_at)s") % translation_context
1118
+
1119
+ if workflow_state.status == "in_progress":
1120
+ return _("Sent to %(task_name)s %(started_at)s") % translation_context
1121
+
1122
+ return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context
1123
+
1124
+
1125
+ @register.inclusion_tag("wagtailadmin/shared/human_readable_date.html")
1126
+ def human_readable_date(date, description=None):
1127
+ return {
1128
+ "date": date,
1129
+ "description": description,
1130
+ }
testbed/wagtail__wagtail/wagtail/admin/tests/__init__.py ADDED
File without changes
testbed/wagtail__wagtail/wagtail/admin/tests/api/__init__.py ADDED
File without changes
testbed/wagtail__wagtail/wagtail/admin/tests/benches.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import, unicode_literals
2
+
3
+ from django.test import TestCase
4
+ from django.urls import reverse
5
+ from django.utils import timezone
6
+
7
+ from wagtail.models import Page, Site
8
+ from wagtail.test.benchmark import Benchmark
9
+ from wagtail.test.testapp.models import SingleEventPage, StreamPage
10
+ from wagtail.test.utils import WagtailTestUtils
11
+
12
+
13
+ class BenchPageExplorerWith50LargePages(Benchmark, WagtailTestUtils, TestCase):
14
+ """
15
+ Creates 50 pages with large body content and benches the explorer.
16
+ This will be slow if the body content is being loaded from the database.
17
+ """
18
+
19
+ def setUp(self):
20
+ self.root_page = Page.objects.get(id=1)
21
+
22
+ # Add a site so the URLs render correctly
23
+ Site.objects.create(is_default_site=True, root_page=self.root_page)
24
+
25
+ # Create a large piece of body text
26
+ body = (
27
+ "["
28
+ + ",".join(['{"type": "text", "value": "%s"}' % ("foo" * 2000)] * 100)
29
+ + "]"
30
+ )
31
+
32
+ # Create 50 simple pages with long content fields
33
+ for i in range(50):
34
+ self.root_page.add_child(
35
+ instance=StreamPage(
36
+ title="Page {}".format(i + 1),
37
+ slug=str(i + 1),
38
+ body=body,
39
+ )
40
+ )
41
+
42
+ self.login()
43
+
44
+ def bench(self):
45
+ response = self.client.get(
46
+ reverse("wagtailadmin_explore", args=(self.root_page.id,))
47
+ )
48
+
49
+ # Check the response was good
50
+ self.assertEqual(response.status_code, 200)
51
+
52
+ # Check every single page was rendered
53
+ self.assertContains(response, "Page 1")
54
+ self.assertContains(response, "Page 49")
55
+
56
+
57
+ class BenchPageExplorerWithCustomURLPages(Benchmark, WagtailTestUtils, TestCase):
58
+ """
59
+ Creates 50 pages of a class with a customised the .url property.
60
+ This will check how long it takes to generate URLs for all of these
61
+ pages.
62
+ """
63
+
64
+ def setUp(self):
65
+ self.root_page = Page.objects.get(id=1)
66
+
67
+ # Add a site so the URLs render correctly
68
+ Site.objects.create(is_default_site=True, root_page=self.root_page)
69
+
70
+ # Create 50 blog pages
71
+ for i in range(50):
72
+ self.root_page.add_child(
73
+ instance=SingleEventPage(
74
+ title="Event {}".format(i + 1),
75
+ slug=str(i + 1),
76
+ date_from=timezone.now(),
77
+ audience="public",
78
+ location="reykjavik",
79
+ cost="cost",
80
+ )
81
+ )
82
+
83
+ self.login()
84
+
85
+ def bench(self):
86
+ response = self.client.get(
87
+ reverse("wagtailadmin_explore", args=(self.root_page.id,))
88
+ )
89
+
90
+ # Check the response was good
91
+ self.assertEqual(response.status_code, 200)
92
+
93
+ # Check every single page was rendered
94
+ self.assertContains(response, "Event 1")
95
+ self.assertContains(response, "Event 49")
96
+
97
+ # Check the URLs were rendered correctly
98
+ self.assertContains(response, 'a href="http:///49/pointless-suffix/"')
testbed/wagtail__wagtail/wagtail/admin/tests/pages/__init__.py ADDED
File without changes
testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_bulk_actions/__init__.py ADDED
File without changes
testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_bulk_actions/test_bulk_action.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.test import TestCase
2
+ from django.urls import reverse
3
+
4
+ from wagtail.test.utils import WagtailTestUtils
5
+
6
+
7
+ class TestBulkActionDispatcher(TestCase, WagtailTestUtils):
8
+ def setUp(self):
9
+
10
+ # Login
11
+ self.user = self.login()
12
+
13
+ def test_bulk_action_invalid_action(self):
14
+ url = reverse(
15
+ "wagtail_bulk_action",
16
+ args=(
17
+ "wagtailcore",
18
+ "page",
19
+ "ships",
20
+ ),
21
+ )
22
+ response = self.client.get(url)
23
+ self.assertEqual(response.status_code, 404)
testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_bulk_actions/test_bulk_unpublish.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from unittest import mock
2
+
3
+ from django.contrib.auth.models import Permission
4
+ from django.http import HttpRequest, HttpResponse
5
+ from django.test import TestCase
6
+ from django.urls import reverse
7
+ from django.utils.translation import gettext_lazy as _
8
+
9
+ from wagtail.admin.views.pages.bulk_actions.page_bulk_action import PageBulkAction
10
+ from wagtail.models import Page
11
+ from wagtail.signals import page_unpublished
12
+ from wagtail.test.testapp.models import SimplePage
13
+ from wagtail.test.utils import WagtailTestUtils
14
+
15
+
16
+ class TestBulkUnpublish(TestCase, WagtailTestUtils):
17
+ def setUp(self):
18
+ # Create pages to unpublish
19
+ self.root_page = Page.objects.get(id=2)
20
+ self.child_pages = [
21
+ SimplePage(
22
+ title=f"Hello world!-{i}", slug=f"hello-world-{i}", content=f"hello-{i}"
23
+ )
24
+ for i in range(1, 5)
25
+ ]
26
+ # first three child pages will be unpublished
27
+ self.pages_to_be_unpublished = self.child_pages[:3]
28
+ self.pages_not_to_be_unpublished = self.child_pages[3:]
29
+ for child_page in self.child_pages:
30
+ self.root_page.add_child(instance=child_page)
31
+
32
+ self.url = (
33
+ reverse(
34
+ "wagtail_bulk_action",
35
+ args=(
36
+ "wagtailcore",
37
+ "page",
38
+ "unpublish",
39
+ ),
40
+ )
41
+ + "?"
42
+ )
43
+ for child_page in self.pages_to_be_unpublished:
44
+ self.url += f"&id={child_page.id}"
45
+ self.redirect_url = reverse("wagtailadmin_explore", args=(self.root_page.id,))
46
+
47
+ # Login
48
+ self.user = self.login()
49
+
50
+ def test_unpublish_view(self):
51
+ """
52
+ This tests that the unpublish view responds with an unpublish confirm page
53
+ """
54
+ # Request confirm unpublish page
55
+ response = self.client.get(self.url)
56
+
57
+ # Check that the user received an unpublish confirm page
58
+ self.assertEqual(response.status_code, 200)
59
+ self.assertTemplateUsed(
60
+ response, "wagtailadmin/pages/bulk_actions/confirm_bulk_unpublish.html"
61
+ )
62
+
63
+ def test_unpublish_view_invalid_page_id(self):
64
+ """
65
+ This tests that the unpublish view returns an error if the page id is invalid
66
+ """
67
+ # Request confirm unpublish page but with illegal page id
68
+ response = self.client.get(
69
+ reverse(
70
+ "wagtail_bulk_action",
71
+ args=(
72
+ "wagtailcore",
73
+ "page",
74
+ "unpublish",
75
+ ),
76
+ )
77
+ )
78
+
79
+ # Check that the user received a 404 response
80
+ self.assertEqual(response.status_code, 404)
81
+
82
+ def test_unpublish_view_bad_permissions(self):
83
+ """
84
+ This tests that the unpublish view doesn't allow users without unpublish permissions
85
+ """
86
+ # Remove privileges from user
87
+ self.user.is_superuser = False
88
+ self.user.user_permissions.add(
89
+ Permission.objects.get(
90
+ content_type__app_label="wagtailadmin", codename="access_admin"
91
+ )
92
+ )
93
+ self.user.save()
94
+
95
+ # Request confirm unpublish page
96
+ response = self.client.get(self.url)
97
+
98
+ # Check that the user received a 200 redirected response
99
+ self.assertEqual(response.status_code, 200)
100
+
101
+ html = response.content.decode()
102
+
103
+ self.assertInHTML(
104
+ "<p>You don't have permission to unpublish these pages</p>", html
105
+ )
106
+
107
+ for child_page in self.pages_to_be_unpublished:
108
+ self.assertInHTML(
109
+ "<li>{page_title}</li>".format(page_title=child_page.title), html
110
+ )
111
+
112
+ def test_unpublish_view_post(self):
113
+ """
114
+ This posts to the unpublish view and checks that the page was unpublished
115
+ """
116
+ # Connect a mock signal handler to page_unpublished signal
117
+ mock_handler = mock.MagicMock()
118
+ page_unpublished.connect(mock_handler)
119
+
120
+ # Post to the unpublish page
121
+ response = self.client.post(self.url)
122
+
123
+ # Should be redirected to explorer page
124
+ self.assertEqual(response.status_code, 302)
125
+
126
+ # Check that the child pages were unpublished
127
+ for child_page in self.pages_to_be_unpublished:
128
+ self.assertFalse(SimplePage.objects.get(id=child_page.id).live)
129
+
130
+ # Check that the child pages not to be unpublished remain
131
+ for child_page in self.pages_not_to_be_unpublished:
132
+ self.assertTrue(SimplePage.objects.get(id=child_page.id).live)
133
+
134
+ # Check that the page_unpublished signal was fired
135
+ self.assertEqual(mock_handler.call_count, len(self.pages_to_be_unpublished))
136
+
137
+ for i, child_page in enumerate(self.pages_to_be_unpublished):
138
+ mock_call = mock_handler.mock_calls[i][2]
139
+ self.assertEqual(mock_call["sender"], child_page.specific_class)
140
+ self.assertEqual(mock_call["instance"], child_page)
141
+ self.assertIsInstance(mock_call["instance"], child_page.specific_class)
142
+
143
+ def test_after_unpublish_page(self):
144
+ def hook_func(request, action_type, pages, action_class_instance):
145
+ self.assertEqual(action_type, "unpublish")
146
+ self.assertIsInstance(request, HttpRequest)
147
+ self.assertIsInstance(action_class_instance, PageBulkAction)
148
+ for i, page in enumerate(pages):
149
+ self.assertEqual(page.id, self.pages_to_be_unpublished[i].id)
150
+
151
+ return HttpResponse("Overridden!")
152
+
153
+ with self.register_hook("after_bulk_action", hook_func):
154
+ response = self.client.post(self.url)
155
+
156
+ self.assertEqual(response.status_code, 200)
157
+ self.assertEqual(response.content, b"Overridden!")
158
+
159
+ for child_page in self.pages_to_be_unpublished:
160
+ child_page.refresh_from_db()
161
+ self.assertEqual(child_page.status_string, _("draft"))
162
+
163
+ def test_before_unpublish_page(self):
164
+ def hook_func(request, action_type, pages, action_class_instance):
165
+ self.assertEqual(action_type, "unpublish")
166
+ self.assertIsInstance(request, HttpRequest)
167
+ self.assertIsInstance(action_class_instance, PageBulkAction)
168
+ for i, page in enumerate(pages):
169
+ self.assertEqual(page.id, self.pages_to_be_unpublished[i].id)
170
+
171
+ return HttpResponse("Overridden!")
172
+
173
+ with self.register_hook("before_bulk_action", hook_func):
174
+ response = self.client.post(self.url)
175
+
176
+ self.assertEqual(response.status_code, 200)
177
+ self.assertEqual(response.content, b"Overridden!")
178
+
179
+ def test_unpublish_descendants_view(self):
180
+ """
181
+ This tests that the unpublish view responds with an unpublish confirm page that does not contain the form field 'include_descendants'
182
+ """
183
+ # Get unpublish page for page with no descendants
184
+ response = self.client.get(self.url)
185
+
186
+ # Check that the user received an unpublish confirm page
187
+ self.assertEqual(response.status_code, 200)
188
+ self.assertTemplateUsed(
189
+ response, "wagtailadmin/pages/bulk_actions/confirm_bulk_unpublish.html"
190
+ )
191
+ # Check the form does not contain the checkbox field include_descendants
192
+ self.assertContains(
193
+ response,
194
+ 'name="include_descendants"',
195
+ count=0,
196
+ )
197
+
198
+
199
+ class TestBulkUnpublishIncludingDescendants(TestCase, WagtailTestUtils):
200
+ def setUp(self):
201
+ # Find root page
202
+ self.root_page = Page.objects.get(id=2)
203
+
204
+ self.child_pages = [
205
+ SimplePage(
206
+ title=f"Hello world!-{i}", slug=f"hello-world-{i}", content=f"hello-{i}"
207
+ )
208
+ for i in range(1, 5)
209
+ ]
210
+ # first three child pages will be unpublished
211
+ self.pages_to_be_unpublished = self.child_pages[:3]
212
+ self.pages_not_to_be_unpublished = self.child_pages[3:]
213
+ for child_page in self.child_pages:
214
+ self.root_page.add_child(instance=child_page)
215
+
216
+ # map of the form { page: [child_pages] } to be added
217
+ self.grandchildren_pages = {
218
+ self.pages_to_be_unpublished[0]: [
219
+ SimplePage(
220
+ title="Hello world!-a", slug="hello-world-a", content="hello-a"
221
+ )
222
+ ],
223
+ self.pages_to_be_unpublished[1]: [
224
+ SimplePage(
225
+ title="Hello world!-b", slug="hello-world-b", content="hello-b"
226
+ ),
227
+ SimplePage(
228
+ title="Hello world!-c", slug="hello-world-c", content="hello-c"
229
+ ),
230
+ ],
231
+ }
232
+
233
+ for child_page, grandchild_pages in self.grandchildren_pages.items():
234
+ for grandchild_page in grandchild_pages:
235
+ child_page.add_child(instance=grandchild_page)
236
+
237
+ self.url = (
238
+ reverse(
239
+ "wagtail_bulk_action",
240
+ args=(
241
+ "wagtailcore",
242
+ "page",
243
+ "unpublish",
244
+ ),
245
+ )
246
+ + "?"
247
+ )
248
+ for child_page in self.pages_to_be_unpublished:
249
+ self.url += f"&id={child_page.id}"
250
+ self.redirect_url = reverse("wagtailadmin_explore", args=(self.root_page.id,))
251
+
252
+ self.user = self.login()
253
+
254
+ def test_unpublish_descendants_view(self):
255
+ """
256
+ This tests that the unpublish view responds with an unpublish confirm page that contains the form field 'include_descendants'
257
+ """
258
+ # Get unpublish page
259
+ response = self.client.get(self.url)
260
+
261
+ # Check that the user received an unpublish confirm page
262
+ self.assertEqual(response.status_code, 200)
263
+ self.assertTemplateUsed(
264
+ response, "wagtailadmin/pages/bulk_actions/confirm_bulk_unpublish.html"
265
+ )
266
+ # Check the form contains the checkbox field include_descendants
267
+ self.assertContains(
268
+ response,
269
+ 'name="include_descendants"',
270
+ )
271
+
272
+ def test_unpublish_include_children_view_post(self):
273
+ """
274
+ This posts to the unpublish view and checks that the page and its descendants were unpublished
275
+ """
276
+ # Post to the unpublish page
277
+ response = self.client.post(self.url, {"include_descendants": "on"})
278
+
279
+ # Should be redirected to explorer page
280
+ self.assertEqual(response.status_code, 302)
281
+
282
+ # Check that the child pages were unpublished
283
+ for child_page in self.pages_to_be_unpublished:
284
+ self.assertFalse(SimplePage.objects.get(id=child_page.id).live)
285
+
286
+ # Check that the child pages not to be unpublished remain
287
+ for child_page in self.pages_not_to_be_unpublished:
288
+ self.assertTrue(SimplePage.objects.get(id=child_page.id).live)
289
+
290
+ for grandchild_pages in self.grandchildren_pages.values():
291
+ for grandchild_page in grandchild_pages:
292
+ self.assertFalse(SimplePage.objects.get(id=grandchild_page.id).live)
293
+
294
+ def test_unpublish_not_include_children_view_post(self):
295
+ """
296
+ This posts to the unpublish view and checks that the page was unpublished but its descendants were not
297
+ """
298
+ # Post to the unpublish page
299
+ response = self.client.post(self.url, {})
300
+
301
+ # Should be redirected to explorer page
302
+ self.assertEqual(response.status_code, 302)
303
+
304
+ # Check that the child pages were unpublished
305
+ for child_page in self.pages_to_be_unpublished:
306
+ self.assertFalse(SimplePage.objects.get(id=child_page.id).live)
307
+
308
+ # Check that the descendant pages were not unpublished
309
+ for grandchild_pages in self.grandchildren_pages.values():
310
+ for grandchild_page in grandchild_pages:
311
+ self.assertTrue(SimplePage.objects.get(id=grandchild_page.id).live)
testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_create_page.py ADDED
@@ -0,0 +1,1762 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import unittest
3
+ from unittest import mock
4
+
5
+ from django.contrib.auth.models import Group, Permission
6
+ from django.http import HttpRequest, HttpResponse
7
+ from django.test import TestCase
8
+ from django.test.utils import override_settings
9
+ from django.urls import reverse
10
+ from django.utils import timezone
11
+ from django.utils.translation import gettext_lazy as _
12
+
13
+ from wagtail.models import GroupPagePermission, Locale, Page, Revision
14
+ from wagtail.signals import page_published
15
+ from wagtail.test.testapp.models import (
16
+ BusinessChild,
17
+ BusinessIndex,
18
+ BusinessSubIndex,
19
+ DefaultStreamPage,
20
+ PersonPage,
21
+ SimpleChildPage,
22
+ SimplePage,
23
+ SimpleParentPage,
24
+ SingletonPage,
25
+ SingletonPageViaMaxCount,
26
+ StandardChild,
27
+ StandardIndex,
28
+ )
29
+ from wagtail.test.utils import WagtailTestUtils
30
+ from wagtail.test.utils.timestamps import submittable_timestamp
31
+
32
+
33
+ class TestPageCreation(TestCase, WagtailTestUtils):
34
+ def setUp(self):
35
+ # Find root page
36
+ self.root_page = Page.objects.get(id=2)
37
+
38
+ # Login
39
+ self.user = self.login()
40
+
41
+ def test_add_subpage(self):
42
+ response = self.client.get(
43
+ reverse("wagtailadmin_pages:add_subpage", args=(self.root_page.id,))
44
+ )
45
+ self.assertEqual(response.status_code, 200)
46
+
47
+ self.assertContains(response, "Simple page")
48
+ target_url = reverse(
49
+ "wagtailadmin_pages:add", args=("tests", "simplepage", self.root_page.id)
50
+ )
51
+ self.assertContains(response, 'href="%s"' % target_url)
52
+ self.assertContains(response, "A simple page description")
53
+ # List of available page types should not contain pages with is_creatable = False
54
+ self.assertNotContains(response, "MTI base page")
55
+ # List of available page types should not contain abstract pages
56
+ self.assertNotContains(response, "Abstract page")
57
+ # List of available page types should not contain pages whose parent_page_types forbid it
58
+ self.assertNotContains(response, "Business child")
59
+
60
+ def test_add_subpage_with_subpage_types(self):
61
+ # Add a BusinessIndex to test business rules in
62
+ business_index = BusinessIndex(
63
+ title="Hello world!",
64
+ slug="hello-world",
65
+ )
66
+ self.root_page.add_child(instance=business_index)
67
+
68
+ response = self.client.get(
69
+ reverse("wagtailadmin_pages:add_subpage", args=(business_index.id,))
70
+ )
71
+ self.assertEqual(response.status_code, 200)
72
+
73
+ self.assertContains(response, "Business child")
74
+ self.assertContains(response, "A lazy business child page description")
75
+ # List should not contain page types not in the subpage_types list
76
+ self.assertNotContains(response, "Simple page")
77
+
78
+ def test_no_subpage_type_available_to_create(self):
79
+ # Test if all subpages have reached their max_count_per_parent limit
80
+ simple_parent_page = SimpleParentPage(
81
+ title="Hello World!",
82
+ slug="hello-world",
83
+ )
84
+ self.root_page.add_child(instance=simple_parent_page)
85
+ simple_child_page = SimpleChildPage(
86
+ title="Hello World!",
87
+ slug="hello-world",
88
+ )
89
+ simple_parent_page.add_child(instance=simple_child_page)
90
+ response = self.client.get(
91
+ reverse("wagtailadmin_pages:add_subpage", args=(simple_parent_page.id,))
92
+ )
93
+ self.assertEqual(response.status_code, 200)
94
+ # if there is no page_type available then this message should be shown.
95
+ self.assertContains(
96
+ response, "Sorry, you cannot create a page at this location."
97
+ )
98
+ self.assertNotContains(
99
+ response, "Choose which type of page you'd like to create."
100
+ )
101
+
102
+ def test_add_subpage_with_one_valid_subpage_type(self):
103
+ # Add a BusinessSubIndex to test business rules in
104
+ business_index = BusinessIndex(
105
+ title="Hello world!",
106
+ slug="hello-world",
107
+ )
108
+ self.root_page.add_child(instance=business_index)
109
+ business_subindex = BusinessSubIndex(
110
+ title="Hello world!",
111
+ slug="hello-world",
112
+ )
113
+ business_index.add_child(instance=business_subindex)
114
+
115
+ response = self.client.get(
116
+ reverse("wagtailadmin_pages:add_subpage", args=(business_subindex.id,))
117
+ )
118
+ # Should be redirected to the 'add' page for BusinessChild, the only valid subpage type
119
+ self.assertRedirects(
120
+ response,
121
+ reverse(
122
+ "wagtailadmin_pages:add",
123
+ args=("tests", "businesschild", business_subindex.id),
124
+ ),
125
+ )
126
+
127
+ def test_add_subpage_bad_permissions(self):
128
+ # Remove privileges from user
129
+ self.user.is_superuser = False
130
+ self.user.user_permissions.add(
131
+ Permission.objects.get(
132
+ content_type__app_label="wagtailadmin", codename="access_admin"
133
+ )
134
+ )
135
+ self.user.save()
136
+
137
+ # Get add subpage page
138
+ response = self.client.get(
139
+ reverse("wagtailadmin_pages:add_subpage", args=(self.root_page.id,))
140
+ )
141
+
142
+ # Check that the user received a 403 response
143
+ self.assertEqual(response.status_code, 302)
144
+
145
+ def test_add_subpage_nonexistantparent(self):
146
+ response = self.client.get(
147
+ reverse("wagtailadmin_pages:add_subpage", args=(100000,))
148
+ )
149
+ self.assertEqual(response.status_code, 404)
150
+
151
+ def test_add_subpage_with_next_param(self):
152
+ response = self.client.get(
153
+ reverse("wagtailadmin_pages:add_subpage", args=(self.root_page.id,)),
154
+ {"next": "/admin/users/"},
155
+ )
156
+ self.assertEqual(response.status_code, 200)
157
+
158
+ self.assertContains(response, "Simple page")
159
+ target_url = reverse(
160
+ "wagtailadmin_pages:add", args=("tests", "simplepage", self.root_page.id)
161
+ )
162
+ self.assertContains(response, 'href="%s?next=/admin/users/"' % target_url)
163
+
164
+ def test_create_simplepage(self):
165
+ response = self.client.get(
166
+ reverse(
167
+ "wagtailadmin_pages:add",
168
+ args=("tests", "simplepage", self.root_page.id),
169
+ )
170
+ )
171
+ self.assertEqual(response.status_code, 200)
172
+ self.assertEqual(response["Content-Type"], "text/html; charset=utf-8")
173
+ self.assertContains(
174
+ response,
175
+ '<a id="tab-label-content" href="#tab-content" class="w-tabs__tab " role="tab" aria-selected="false" tabindex="-1">',
176
+ )
177
+ self.assertContains(
178
+ response,
179
+ '<a id="tab-label-promote" href="#tab-promote" class="w-tabs__tab " role="tab" aria-selected="false" tabindex="-1">',
180
+ )
181
+ # test register_page_action_menu_item hook
182
+ self.assertContains(
183
+ response,
184
+ '<button type="submit" name="action-panic" value="Panic!" class="button">Panic!</button>',
185
+ )
186
+ self.assertContains(response, "testapp/js/siren.js")
187
+ # test construct_page_action_menu hook
188
+ self.assertContains(
189
+ response,
190
+ '<button type="submit" name="action-relax" value="Relax." class="button">Relax.</button>',
191
+ )
192
+ # test that workflow actions are shown
193
+ self.assertContains(
194
+ response,
195
+ '<button type="submit" name="action-submit" value="Submit for moderation" class="button">',
196
+ )
197
+
198
+ @override_settings(WAGTAIL_WORKFLOW_ENABLED=False)
199
+ def test_workflow_buttons_not_shown_when_workflow_disabled(self):
200
+ response = self.client.get(
201
+ reverse(
202
+ "wagtailadmin_pages:add",
203
+ args=("tests", "simplepage", self.root_page.id),
204
+ )
205
+ )
206
+ self.assertEqual(response.status_code, 200)
207
+ self.assertNotContains(response, 'value="Submit for moderation"')
208
+
209
+ def test_create_multipart(self):
210
+ """
211
+ Test checks if 'enctype="multipart/form-data"' is added and only to forms that require multipart encoding.
212
+ """
213
+ # check for SimplePage where is no file field
214
+ response = self.client.get(
215
+ reverse(
216
+ "wagtailadmin_pages:add",
217
+ args=("tests", "simplepage", self.root_page.id),
218
+ )
219
+ )
220
+ self.assertEqual(response.status_code, 200)
221
+ self.assertNotContains(response, 'enctype="multipart/form-data"')
222
+ self.assertTemplateUsed(response, "wagtailadmin/pages/create.html")
223
+
224
+ # check for FilePage which has file field
225
+ response = self.client.get(
226
+ reverse(
227
+ "wagtailadmin_pages:add", args=("tests", "filepage", self.root_page.id)
228
+ )
229
+ )
230
+ self.assertEqual(response.status_code, 200)
231
+ self.assertContains(response, 'enctype="multipart/form-data"')
232
+
233
+ def test_create_page_without_promote_tab(self):
234
+ """
235
+ Test that the Promote tab is not rendered for page classes that define it as empty
236
+ """
237
+ response = self.client.get(
238
+ reverse(
239
+ "wagtailadmin_pages:add",
240
+ args=("tests", "standardindex", self.root_page.id),
241
+ )
242
+ )
243
+ self.assertEqual(response.status_code, 200)
244
+ self.assertContains(
245
+ response,
246
+ '<a id="tab-label-content" href="#tab-content" class="w-tabs__tab " role="tab" aria-selected="false" tabindex="-1">',
247
+ )
248
+ self.assertNotContains(response, "tab-promote")
249
+
250
+ def test_create_page_with_custom_tabs(self):
251
+ """
252
+ Test that custom edit handlers are rendered
253
+ """
254
+ response = self.client.get(
255
+ reverse(
256
+ "wagtailadmin_pages:add",
257
+ args=("tests", "standardchild", self.root_page.id),
258
+ )
259
+ )
260
+ self.assertEqual(response.status_code, 200)
261
+ self.assertContains(
262
+ response,
263
+ '<a id="tab-label-content" href="#tab-content" class="w-tabs__tab " role="tab" aria-selected="false" tabindex="-1">',
264
+ )
265
+ self.assertContains(
266
+ response,
267
+ '<a id="tab-label-promote" href="#tab-promote" class="w-tabs__tab " role="tab" aria-selected="false" tabindex="-1">',
268
+ )
269
+ self.assertContains(
270
+ response,
271
+ '<a id="tab-label-dinosaurs" href="#tab-dinosaurs" class="w-tabs__tab " role="tab" aria-selected="false" tabindex="-1">',
272
+ )
273
+
274
+ def test_create_page_with_non_model_field(self):
275
+ """
276
+ Test that additional fields defined on the form rather than the model are accepted and rendered
277
+ """
278
+ response = self.client.get(
279
+ reverse(
280
+ "wagtailadmin_pages:add",
281
+ args=("tests", "formclassadditionalfieldpage", self.root_page.id),
282
+ )
283
+ )
284
+ self.assertEqual(response.status_code, 200)
285
+ self.assertTemplateUsed(response, "wagtailadmin/pages/create.html")
286
+ self.assertContains(response, "Enter SMS authentication code")
287
+
288
+ def test_create_simplepage_bad_permissions(self):
289
+ # Remove privileges from user
290
+ self.user.is_superuser = False
291
+ self.user.user_permissions.add(
292
+ Permission.objects.get(
293
+ content_type__app_label="wagtailadmin", codename="access_admin"
294
+ )
295
+ )
296
+ self.user.save()
297
+
298
+ # Get page
299
+ response = self.client.get(
300
+ reverse(
301
+ "wagtailadmin_pages:add",
302
+ args=(
303
+ "tests",
304
+ "simplepage",
305
+ self.root_page.id,
306
+ ),
307
+ )
308
+ )
309
+
310
+ # Check that the user received a 403 response
311
+ self.assertEqual(response.status_code, 302)
312
+
313
+ def test_cannot_create_page_with_is_creatable_false(self):
314
+ # tests.MTIBasePage has is_creatable=False, so attempting to add a new one
315
+ # should fail with permission denied
316
+ response = self.client.get(
317
+ reverse(
318
+ "wagtailadmin_pages:add",
319
+ args=("tests", "mtibasepage", self.root_page.id),
320
+ )
321
+ )
322
+ self.assertRedirects(response, "/admin/")
323
+
324
+ def test_cannot_create_page_when_can_create_at_returns_false(self):
325
+ # issue #2892
326
+
327
+ # Check that creating a second SingletonPage results in a permission
328
+ # denied error.
329
+
330
+ # SingletonPage overrides the can_create_at method to make it return
331
+ # False if another SingletonPage already exists.
332
+
333
+ # The Page model now has a max_count attribute (issue 4841),
334
+ # but we are leaving this test in place to cover existing behaviour and
335
+ # ensure it does not break any code doing this in the wild.
336
+ add_url = reverse(
337
+ "wagtailadmin_pages:add",
338
+ args=[
339
+ SingletonPage._meta.app_label,
340
+ SingletonPage._meta.model_name,
341
+ self.root_page.pk,
342
+ ],
343
+ )
344
+
345
+ # A single singleton page should be creatable
346
+ self.assertTrue(SingletonPage.can_create_at(self.root_page))
347
+ response = self.client.get(add_url)
348
+ self.assertEqual(response.status_code, 200)
349
+
350
+ # Create a singleton page
351
+ self.root_page.add_child(
352
+ instance=SingletonPage(title="singleton", slug="singleton")
353
+ )
354
+
355
+ # A second singleton page should not be creatable
356
+ self.assertFalse(SingletonPage.can_create_at(self.root_page))
357
+ response = self.client.get(add_url)
358
+ self.assertRedirects(response, "/admin/")
359
+
360
+ def test_cannot_create_singleton_page_with_max_count(self):
361
+ # Check that creating a second SingletonPageViaMaxCount results in a permission
362
+ # denied error.
363
+
364
+ # SingletonPageViaMaxCount uses the max_count attribute to limit the number of
365
+ # instance it can have.
366
+
367
+ add_url = reverse(
368
+ "wagtailadmin_pages:add",
369
+ args=[
370
+ SingletonPageViaMaxCount._meta.app_label,
371
+ SingletonPageViaMaxCount._meta.model_name,
372
+ self.root_page.pk,
373
+ ],
374
+ )
375
+
376
+ # A single singleton page should be creatable
377
+ self.assertTrue(SingletonPageViaMaxCount.can_create_at(self.root_page))
378
+ response = self.client.get(add_url)
379
+ self.assertEqual(response.status_code, 200)
380
+
381
+ # Create a singleton page
382
+ self.root_page.add_child(
383
+ instance=SingletonPageViaMaxCount(title="singleton", slug="singleton")
384
+ )
385
+
386
+ # A second singleton page should not be creatable
387
+ self.assertFalse(SingletonPageViaMaxCount.can_create_at(self.root_page))
388
+ response = self.client.get(add_url)
389
+ self.assertRedirects(response, "/admin/")
390
+
391
+ def test_cannot_create_page_with_wrong_parent_page_types(self):
392
+ # tests.BusinessChild has limited parent_page_types, so attempting to add
393
+ # a new one at the root level should fail with permission denied
394
+ response = self.client.get(
395
+ reverse(
396
+ "wagtailadmin_pages:add",
397
+ args=("tests", "businesschild", self.root_page.id),
398
+ )
399
+ )
400
+ self.assertRedirects(response, "/admin/")
401
+
402
+ def test_cannot_create_page_with_wrong_subpage_types(self):
403
+ # Add a BusinessIndex to test business rules in
404
+ business_index = BusinessIndex(
405
+ title="Hello world!",
406
+ slug="hello-world",
407
+ )
408
+ self.root_page.add_child(instance=business_index)
409
+
410
+ # BusinessIndex has limited subpage_types, so attempting to add a SimplePage
411
+ # underneath it should fail with permission denied
412
+ response = self.client.get(
413
+ reverse(
414
+ "wagtailadmin_pages:add",
415
+ args=("tests", "simplepage", business_index.id),
416
+ )
417
+ )
418
+ self.assertRedirects(response, "/admin/")
419
+
420
+ def test_create_simplepage_post(self):
421
+ post_data = {
422
+ "title": "New page!",
423
+ "content": "Some content",
424
+ "slug": "hello-world",
425
+ }
426
+ response = self.client.post(
427
+ reverse(
428
+ "wagtailadmin_pages:add",
429
+ args=("tests", "simplepage", self.root_page.id),
430
+ ),
431
+ post_data,
432
+ )
433
+
434
+ # Find the page and check it
435
+ page = Page.objects.get(
436
+ path__startswith=self.root_page.path, slug="hello-world"
437
+ ).specific
438
+
439
+ # Should be redirected to edit page
440
+ self.assertRedirects(
441
+ response, reverse("wagtailadmin_pages:edit", args=(page.id,))
442
+ )
443
+
444
+ self.assertEqual(page.title, post_data["title"])
445
+ self.assertEqual(page.draft_title, post_data["title"])
446
+ self.assertIsInstance(page, SimplePage)
447
+ self.assertFalse(page.live)
448
+ self.assertFalse(page.first_published_at)
449
+
450
+ # treebeard should report no consistency problems with the tree
451
+ self.assertFalse(
452
+ any(Page.find_problems()), "treebeard found consistency problems"
453
+ )
454
+
455
+ def test_create_simplepage_scheduled(self):
456
+ go_live_at = timezone.now() + datetime.timedelta(days=1)
457
+ expire_at = timezone.now() + datetime.timedelta(days=2)
458
+ post_data = {
459
+ "title": "New page!",
460
+ "content": "Some content",
461
+ "slug": "hello-world",
462
+ "go_live_at": submittable_timestamp(go_live_at),
463
+ "expire_at": submittable_timestamp(expire_at),
464
+ }
465
+ response = self.client.post(
466
+ reverse(
467
+ "wagtailadmin_pages:add",
468
+ args=("tests", "simplepage", self.root_page.id),
469
+ ),
470
+ post_data,
471
+ )
472
+
473
+ # Should be redirected to explorer page
474
+ self.assertEqual(response.status_code, 302)
475
+
476
+ # Find the page and check the scheduled times
477
+ page = Page.objects.get(
478
+ path__startswith=self.root_page.path, slug="hello-world"
479
+ ).specific
480
+ self.assertEqual(page.go_live_at.date(), go_live_at.date())
481
+ self.assertEqual(page.expire_at.date(), expire_at.date())
482
+ self.assertIs(page.expired, False)
483
+ self.assertTrue(page.status_string, "draft")
484
+
485
+ # No revisions with approved_go_live_at
486
+ self.assertFalse(
487
+ Revision.page_revisions.filter(object_id=page.id)
488
+ .exclude(approved_go_live_at__isnull=True)
489
+ .exists()
490
+ )
491
+
492
+ def test_create_simplepage_scheduled_go_live_before_expiry(self):
493
+ post_data = {
494
+ "title": "New page!",
495
+ "content": "Some content",
496
+ "slug": "hello-world",
497
+ "go_live_at": submittable_timestamp(
498
+ timezone.now() + datetime.timedelta(days=2)
499
+ ),
500
+ "expire_at": submittable_timestamp(
501
+ timezone.now() + datetime.timedelta(days=1)
502
+ ),
503
+ }
504
+ response = self.client.post(
505
+ reverse(
506
+ "wagtailadmin_pages:add",
507
+ args=("tests", "simplepage", self.root_page.id),
508
+ ),
509
+ post_data,
510
+ )
511
+
512
+ self.assertEqual(response.status_code, 200)
513
+
514
+ # Check that a form error was raised
515
+ self.assertFormError(
516
+ response,
517
+ "form",
518
+ "go_live_at",
519
+ "Go live date/time must be before expiry date/time",
520
+ )
521
+ self.assertFormError(
522
+ response,
523
+ "form",
524
+ "expire_at",
525
+ "Go live date/time must be before expiry date/time",
526
+ )
527
+
528
+ # form should be marked as having unsaved changes for the purposes of the dirty-forms warning
529
+ self.assertContains(response, "alwaysDirty: true")
530
+
531
+ def test_create_simplepage_scheduled_expire_in_the_past(self):
532
+ post_data = {
533
+ "title": "New page!",
534
+ "content": "Some content",
535
+ "slug": "hello-world",
536
+ "expire_at": submittable_timestamp(
537
+ timezone.now() + datetime.timedelta(days=-1)
538
+ ),
539
+ }
540
+ response = self.client.post(
541
+ reverse(
542
+ "wagtailadmin_pages:add",
543
+ args=("tests", "simplepage", self.root_page.id),
544
+ ),
545
+ post_data,
546
+ )
547
+
548
+ self.assertEqual(response.status_code, 200)
549
+
550
+ # Check that a form error was raised
551
+ self.assertFormError(
552
+ response, "form", "expire_at", "Expiry date/time must be in the future"
553
+ )
554
+
555
+ # form should be marked as having unsaved changes for the purposes of the dirty-forms warning
556
+ self.assertContains(response, "alwaysDirty: true")
557
+
558
+ def test_create_simplepage_post_publish(self):
559
+ # Connect a mock signal handler to page_published signal
560
+ mock_handler = mock.MagicMock()
561
+ page_published.connect(mock_handler)
562
+
563
+ # Post
564
+ post_data = {
565
+ "title": "New page!",
566
+ "content": "Some content",
567
+ "slug": "hello-world",
568
+ "action-publish": "Publish",
569
+ }
570
+ response = self.client.post(
571
+ reverse(
572
+ "wagtailadmin_pages:add",
573
+ args=("tests", "simplepage", self.root_page.id),
574
+ ),
575
+ post_data,
576
+ )
577
+
578
+ # Find the page and check it
579
+ page = Page.objects.get(
580
+ path__startswith=self.root_page.path, slug="hello-world"
581
+ ).specific
582
+
583
+ # Should be redirected to explorer
584
+ self.assertRedirects(
585
+ response, reverse("wagtailadmin_explore", args=(self.root_page.id,))
586
+ )
587
+
588
+ self.assertEqual(page.title, post_data["title"])
589
+ self.assertEqual(page.draft_title, post_data["title"])
590
+ self.assertIsInstance(page, SimplePage)
591
+ self.assertTrue(page.live)
592
+ self.assertTrue(page.first_published_at)
593
+
594
+ # Check that the page_published signal was fired
595
+ self.assertEqual(mock_handler.call_count, 1)
596
+ mock_call = mock_handler.mock_calls[0][2]
597
+
598
+ self.assertEqual(mock_call["sender"], page.specific_class)
599
+ self.assertEqual(mock_call["instance"], page)
600
+ self.assertIsInstance(mock_call["instance"], page.specific_class)
601
+
602
+ # treebeard should report no consistency problems with the tree
603
+ self.assertFalse(
604
+ any(Page.find_problems()), "treebeard found consistency problems"
605
+ )
606
+
607
+ def test_create_simplepage_post_publish_scheduled(self):
608
+ go_live_at = timezone.now() + datetime.timedelta(days=1)
609
+ expire_at = timezone.now() + datetime.timedelta(days=2)
610
+ post_data = {
611
+ "title": "New page!",
612
+ "content": "Some content",
613
+ "slug": "hello-world",
614
+ "action-publish": "Publish",
615
+ "go_live_at": submittable_timestamp(go_live_at),
616
+ "expire_at": submittable_timestamp(expire_at),
617
+ }
618
+ response = self.client.post(
619
+ reverse(
620
+ "wagtailadmin_pages:add",
621
+ args=("tests", "simplepage", self.root_page.id),
622
+ ),
623
+ post_data,
624
+ )
625
+
626
+ # Should be redirected to explorer page
627
+ self.assertEqual(response.status_code, 302)
628
+
629
+ # Find the page and check it
630
+ page = Page.objects.get(
631
+ path__startswith=self.root_page.path, slug="hello-world"
632
+ ).specific
633
+ self.assertEqual(page.go_live_at.date(), go_live_at.date())
634
+ self.assertEqual(page.expire_at.date(), expire_at.date())
635
+ self.assertIs(page.expired, False)
636
+
637
+ # A revision with approved_go_live_at should exist now
638
+ self.assertTrue(
639
+ Revision.page_revisions.filter(object_id=page.id)
640
+ .exclude(approved_go_live_at__isnull=True)
641
+ .exists()
642
+ )
643
+ # But Page won't be live
644
+ self.assertFalse(page.live)
645
+ self.assertFalse(page.first_published_at)
646
+ self.assertTrue(page.status_string, "scheduled")
647
+
648
+ def test_create_simplepage_post_submit(self):
649
+ # Create a moderator user for testing email
650
+ self.create_superuser("moderator", "moderator@email.com", "password")
651
+
652
+ # Submit
653
+ post_data = {
654
+ "title": "New page!",
655
+ "content": "Some content",
656
+ "slug": "hello-world",
657
+ "action-submit": "Submit",
658
+ }
659
+ response = self.client.post(
660
+ reverse(
661
+ "wagtailadmin_pages:add",
662
+ args=("tests", "simplepage", self.root_page.id),
663
+ ),
664
+ post_data,
665
+ )
666
+
667
+ # Find the page and check it
668
+ page = Page.objects.get(
669
+ path__startswith=self.root_page.path, slug="hello-world"
670
+ ).specific
671
+
672
+ # Should be redirected to explorer
673
+ self.assertRedirects(
674
+ response, reverse("wagtailadmin_explore", args=(self.root_page.id,))
675
+ )
676
+
677
+ self.assertEqual(page.title, post_data["title"])
678
+ self.assertIsInstance(page, SimplePage)
679
+ self.assertFalse(page.live)
680
+ self.assertFalse(page.first_published_at)
681
+
682
+ # The page should now be in moderation
683
+ self.assertEqual(
684
+ page.current_workflow_state.status,
685
+ page.current_workflow_state.STATUS_IN_PROGRESS,
686
+ )
687
+
688
+ def test_create_simplepage_post_existing_slug(self):
689
+ # This tests the existing slug checking on page save
690
+
691
+ # Create a page
692
+ self.child_page = SimplePage(
693
+ title="Hello world!", slug="hello-world", content="hello"
694
+ )
695
+ self.root_page.add_child(instance=self.child_page)
696
+
697
+ # Attempt to create a new one with the same slug
698
+ post_data = {
699
+ "title": "New page!",
700
+ "content": "Some content",
701
+ "slug": "hello-world",
702
+ "action-publish": "Publish",
703
+ }
704
+ response = self.client.post(
705
+ reverse(
706
+ "wagtailadmin_pages:add",
707
+ args=("tests", "simplepage", self.root_page.id),
708
+ ),
709
+ post_data,
710
+ )
711
+
712
+ # Should not be redirected (as the save should fail)
713
+ self.assertEqual(response.status_code, 200)
714
+
715
+ # Check that a form error was raised
716
+ self.assertFormError(
717
+ response,
718
+ "form",
719
+ "slug",
720
+ "The slug 'hello-world' is already in use within the parent page",
721
+ )
722
+
723
+ # form should be marked as having unsaved changes for the purposes of the dirty-forms warning
724
+ self.assertContains(response, "alwaysDirty: true")
725
+
726
+ def test_create_nonexistantparent(self):
727
+ response = self.client.get(
728
+ reverse("wagtailadmin_pages:add", args=("tests", "simplepage", 100000))
729
+ )
730
+ self.assertEqual(response.status_code, 404)
731
+
732
+ def test_create_nonpagetype(self):
733
+ response = self.client.get(
734
+ reverse(
735
+ "wagtailadmin_pages:add",
736
+ args=("wagtailimages", "image", self.root_page.id),
737
+ )
738
+ )
739
+ self.assertEqual(response.status_code, 404)
740
+
741
+ def test_custom_validation(self):
742
+ response = self.client.post(
743
+ reverse(
744
+ "wagtailadmin_pages:add",
745
+ args=("tests", "validatedpage", self.root_page.id),
746
+ ),
747
+ {
748
+ "title": "New page!",
749
+ "foo": "not bar",
750
+ "slug": "hello-world",
751
+ },
752
+ )
753
+
754
+ self.assertEqual(response.status_code, 200)
755
+ self.assertFormError(response, "form", "foo", "Field foo must be bar")
756
+ self.assertFalse(
757
+ Page.objects.filter(
758
+ path__startswith=self.root_page.path, slug="hello-world"
759
+ ).exists()
760
+ )
761
+
762
+ response = self.client.post(
763
+ reverse(
764
+ "wagtailadmin_pages:add",
765
+ args=("tests", "validatedpage", self.root_page.id),
766
+ ),
767
+ {
768
+ "title": "New page!",
769
+ "foo": "superbar",
770
+ "slug": "hello-world",
771
+ },
772
+ )
773
+
774
+ page = Page.objects.get(
775
+ path__startswith=self.root_page.path, slug="hello-world"
776
+ )
777
+ # Should be redirected to edit page
778
+ self.assertRedirects(
779
+ response, reverse("wagtailadmin_pages:edit", args=(page.id,))
780
+ )
781
+
782
+ def test_preview_on_create(self):
783
+ post_data = {
784
+ "title": "New page!",
785
+ "content": "Some content",
786
+ "slug": "hello-world",
787
+ "action-submit": "Submit",
788
+ }
789
+ preview_url = reverse(
790
+ "wagtailadmin_pages:preview_on_add",
791
+ args=("tests", "simplepage", self.root_page.id),
792
+ )
793
+ response = self.client.post(preview_url, post_data)
794
+
795
+ # Check the JSON response
796
+ self.assertEqual(response.status_code, 200)
797
+ self.assertJSONEqual(
798
+ response.content.decode(),
799
+ {"is_valid": True, "is_available": True},
800
+ )
801
+
802
+ response = self.client.get(preview_url)
803
+
804
+ # Check the HTML response
805
+ self.assertEqual(response.status_code, 200)
806
+ self.assertTemplateUsed(response, "tests/simple_page.html")
807
+ self.assertContains(response, "New page!")
808
+
809
+ # Check that the treebeard attributes were set correctly on the page object
810
+ self.assertEqual(response.context["self"].depth, self.root_page.depth + 1)
811
+ self.assertTrue(response.context["self"].path.startswith(self.root_page.path))
812
+ self.assertEqual(response.context["self"].get_parent(), self.root_page)
813
+
814
+ def test_preview_with_custom_validation(self):
815
+ post_data = {
816
+ "title": "New page!",
817
+ "foo": "not bar",
818
+ "slug": "hello-world",
819
+ "action-submit": "Submit",
820
+ }
821
+ preview_url = reverse(
822
+ "wagtailadmin_pages:preview_on_add",
823
+ args=("tests", "validatedpage", self.root_page.id),
824
+ )
825
+ response = self.client.post(preview_url, post_data)
826
+
827
+ # Check the JSON response
828
+ self.assertEqual(response.status_code, 200)
829
+ self.assertJSONEqual(
830
+ response.content.decode(),
831
+ {"is_valid": False, "is_available": False},
832
+ )
833
+
834
+ post_data = {
835
+ "title": "New page!",
836
+ "foo": "superbar",
837
+ "slug": "hello-world",
838
+ "action-submit": "Submit",
839
+ }
840
+ preview_url = reverse(
841
+ "wagtailadmin_pages:preview_on_add",
842
+ args=("tests", "validatedpage", self.root_page.id),
843
+ )
844
+ response = self.client.post(preview_url, post_data)
845
+
846
+ # Check the JSON response
847
+ self.assertEqual(response.status_code, 200)
848
+ self.assertJSONEqual(
849
+ response.content.decode(),
850
+ {"is_valid": True, "is_available": True},
851
+ )
852
+
853
+ response = self.client.get(preview_url)
854
+
855
+ # Check the HTML response
856
+ self.assertEqual(response.status_code, 200)
857
+ self.assertTemplateUsed(response, "tests/validated_page.html")
858
+ self.assertContains(response, "foo = superbar")
859
+
860
+ def test_whitespace_titles(self):
861
+ post_data = {
862
+ "title": " ", # Single space on purpose
863
+ "content": "Some content",
864
+ "slug": "hello-world",
865
+ "action-submit": "Submit",
866
+ }
867
+ response = self.client.post(
868
+ reverse(
869
+ "wagtailadmin_pages:add",
870
+ args=("tests", "simplepage", self.root_page.id),
871
+ ),
872
+ post_data,
873
+ )
874
+
875
+ # Check that a form error was raised
876
+ self.assertFormError(response, "form", "title", "This field is required.")
877
+
878
+ def test_whitespace_titles_with_tab(self):
879
+ post_data = {
880
+ "title": "\t", # Single space on purpose
881
+ "content": "Some content",
882
+ "slug": "hello-world",
883
+ "action-submit": "Submit",
884
+ }
885
+ response = self.client.post(
886
+ reverse(
887
+ "wagtailadmin_pages:add",
888
+ args=("tests", "simplepage", self.root_page.id),
889
+ ),
890
+ post_data,
891
+ )
892
+
893
+ # Check that a form error was raised
894
+ self.assertFormError(response, "form", "title", "This field is required.")
895
+
896
+ def test_whitespace_titles_with_tab_in_seo_title(self):
897
+ post_data = {
898
+ "title": "Hello",
899
+ "content": "Some content",
900
+ "slug": "hello-world",
901
+ "action-submit": "Submit",
902
+ "seo_title": "\t",
903
+ }
904
+ response = self.client.post(
905
+ reverse(
906
+ "wagtailadmin_pages:add",
907
+ args=("tests", "simplepage", self.root_page.id),
908
+ ),
909
+ post_data,
910
+ )
911
+
912
+ # Should be successful, as seo_title is not required
913
+ self.assertEqual(response.status_code, 302)
914
+
915
+ # The tab should be automatically stripped from the seo_title
916
+ page = Page.objects.order_by("-id").first()
917
+ self.assertEqual(page.seo_title, "")
918
+
919
+ def test_whitespace_is_stripped_from_titles(self):
920
+ post_data = {
921
+ "title": " Hello ",
922
+ "content": "Some content",
923
+ "slug": "hello-world",
924
+ "action-submit": "Submit",
925
+ "seo_title": " hello SEO ",
926
+ }
927
+ response = self.client.post(
928
+ reverse(
929
+ "wagtailadmin_pages:add",
930
+ args=("tests", "simplepage", self.root_page.id),
931
+ ),
932
+ post_data,
933
+ )
934
+
935
+ # Should be successful, as both title and seo_title are non-empty after stripping
936
+ self.assertEqual(response.status_code, 302)
937
+
938
+ # Whitespace should be automatically stripped from title and seo_title
939
+ page = Page.objects.order_by("-id").first()
940
+ self.assertEqual(page.title, "Hello")
941
+ self.assertEqual(page.draft_title, "Hello")
942
+ self.assertEqual(page.seo_title, "hello SEO")
943
+
944
+ def test_long_slug(self):
945
+ post_data = {
946
+ "title": "Hello world",
947
+ "content": "Some content",
948
+ "slug": "hello-world-hello-world-hello-world-hello-world-hello-world-hello-world-"
949
+ "hello-world-hello-world-hello-world-hello-world-hello-world-hello-world-"
950
+ "hello-world-hello-world-hello-world-hello-world-hello-world-hello-world-"
951
+ "hello-world-hello-world-hello-world-hello-world-hello-world-hello-world",
952
+ "action-submit": "Submit",
953
+ }
954
+ response = self.client.post(
955
+ reverse(
956
+ "wagtailadmin_pages:add",
957
+ args=("tests", "simplepage", self.root_page.id),
958
+ ),
959
+ post_data,
960
+ )
961
+
962
+ # Check that a form error was raised
963
+ self.assertEqual(response.status_code, 200)
964
+ self.assertFormError(
965
+ response,
966
+ "form",
967
+ "slug",
968
+ "Ensure this value has at most 255 characters (it has 287).",
969
+ )
970
+
971
+ def test_before_create_page_hook(self):
972
+ def hook_func(request, parent_page, page_class):
973
+ self.assertIsInstance(request, HttpRequest)
974
+ self.assertEqual(parent_page.id, self.root_page.id)
975
+ self.assertEqual(page_class, SimplePage)
976
+
977
+ return HttpResponse("Overridden!")
978
+
979
+ with self.register_hook("before_create_page", hook_func):
980
+ response = self.client.get(
981
+ reverse(
982
+ "wagtailadmin_pages:add",
983
+ args=("tests", "simplepage", self.root_page.id),
984
+ )
985
+ )
986
+
987
+ self.assertEqual(response.status_code, 200)
988
+ self.assertEqual(response.content, b"Overridden!")
989
+
990
+ def test_before_create_page_hook_post(self):
991
+ def hook_func(request, parent_page, page_class):
992
+ self.assertIsInstance(request, HttpRequest)
993
+ self.assertEqual(parent_page.id, self.root_page.id)
994
+ self.assertEqual(page_class, SimplePage)
995
+
996
+ return HttpResponse("Overridden!")
997
+
998
+ with self.register_hook("before_create_page", hook_func):
999
+ post_data = {
1000
+ "title": "New page!",
1001
+ "content": "Some content",
1002
+ "slug": "hello-world",
1003
+ }
1004
+ response = self.client.post(
1005
+ reverse(
1006
+ "wagtailadmin_pages:add",
1007
+ args=("tests", "simplepage", self.root_page.id),
1008
+ ),
1009
+ post_data,
1010
+ )
1011
+
1012
+ self.assertEqual(response.status_code, 200)
1013
+ self.assertEqual(response.content, b"Overridden!")
1014
+
1015
+ # page should not be created
1016
+ self.assertFalse(Page.objects.filter(title="New page!").exists())
1017
+
1018
+ def test_after_create_page_hook(self):
1019
+ def hook_func(request, page):
1020
+ self.assertIsInstance(request, HttpRequest)
1021
+ self.assertIsInstance(page, SimplePage)
1022
+
1023
+ # Both are None as this is only a draft
1024
+ self.assertIsNone(page.first_published_at)
1025
+ self.assertIsNone(page.last_published_at)
1026
+
1027
+ return HttpResponse("Overridden!")
1028
+
1029
+ with self.register_hook("after_create_page", hook_func):
1030
+ post_data = {
1031
+ "title": "New page!",
1032
+ "content": "Some content",
1033
+ "slug": "hello-world",
1034
+ }
1035
+ response = self.client.post(
1036
+ reverse(
1037
+ "wagtailadmin_pages:add",
1038
+ args=("tests", "simplepage", self.root_page.id),
1039
+ ),
1040
+ post_data,
1041
+ )
1042
+
1043
+ self.assertEqual(response.status_code, 200)
1044
+ self.assertEqual(response.content, b"Overridden!")
1045
+
1046
+ # page should be created
1047
+ self.assertTrue(Page.objects.filter(title="New page!").exists())
1048
+
1049
+ def test_after_create_page_hook_with_page_publish(self):
1050
+ def hook_func(request, page):
1051
+ self.assertIsInstance(request, HttpRequest)
1052
+ self.assertIsInstance(page, SimplePage)
1053
+
1054
+ self.assertIsNotNone(page.first_published_at)
1055
+ self.assertIsNotNone(page.last_published_at)
1056
+
1057
+ return HttpResponse("Overridden!")
1058
+
1059
+ with self.register_hook("after_create_page", hook_func):
1060
+ post_data = {
1061
+ "title": "New page!",
1062
+ "content": "Some content",
1063
+ "slug": "hello-world",
1064
+ "action-publish": "Publish",
1065
+ }
1066
+ response = self.client.post(
1067
+ reverse(
1068
+ "wagtailadmin_pages:add",
1069
+ args=("tests", "simplepage", self.root_page.id),
1070
+ ),
1071
+ post_data,
1072
+ )
1073
+
1074
+ self.assertEqual(response.status_code, 200)
1075
+ self.assertEqual(response.content, b"Overridden!")
1076
+
1077
+ # page should be created
1078
+ self.assertTrue(Page.objects.filter(title="New page!").exists())
1079
+
1080
+ def test_after_publish_page(self):
1081
+ def hook_func(request, page):
1082
+ self.assertIsInstance(request, HttpRequest)
1083
+ self.assertEqual(page.title, "New page!")
1084
+
1085
+ self.assertIsNotNone(page.first_published_at)
1086
+ self.assertIsNotNone(page.last_published_at)
1087
+
1088
+ return HttpResponse("Overridden!")
1089
+
1090
+ with self.register_hook("after_publish_page", hook_func):
1091
+ post_data = {
1092
+ "title": "New page!",
1093
+ "content": "Some content",
1094
+ "slug": "hello-world",
1095
+ "action-publish": "Publish",
1096
+ }
1097
+ response = self.client.post(
1098
+ reverse(
1099
+ "wagtailadmin_pages:add",
1100
+ args=("tests", "simplepage", self.root_page.id),
1101
+ ),
1102
+ post_data,
1103
+ )
1104
+
1105
+ self.assertEqual(response.status_code, 200)
1106
+ self.assertEqual(response.content, b"Overridden!")
1107
+ self.root_page.refresh_from_db()
1108
+ self.assertEqual(self.root_page.get_children()[0].status_string, _("live"))
1109
+
1110
+ def test_before_publish_page(self):
1111
+ def hook_func(request, page):
1112
+ self.assertIsInstance(request, HttpRequest)
1113
+ self.assertEqual(page.title, "New page!")
1114
+
1115
+ self.assertIsNone(page.first_published_at)
1116
+ self.assertIsNone(page.last_published_at)
1117
+
1118
+ return HttpResponse("Overridden!")
1119
+
1120
+ with self.register_hook("before_publish_page", hook_func):
1121
+ post_data = {
1122
+ "title": "New page!",
1123
+ "content": "Some content",
1124
+ "slug": "hello-world",
1125
+ "action-publish": "Publish",
1126
+ }
1127
+ response = self.client.post(
1128
+ reverse(
1129
+ "wagtailadmin_pages:add",
1130
+ args=("tests", "simplepage", self.root_page.id),
1131
+ ),
1132
+ post_data,
1133
+ )
1134
+
1135
+ self.assertEqual(response.status_code, 200)
1136
+ self.assertEqual(response.content, b"Overridden!")
1137
+ self.root_page.refresh_from_db()
1138
+ self.assertEqual(
1139
+ self.root_page.get_children()[0].status_string, _("live + draft")
1140
+ )
1141
+
1142
+ def test_display_moderation_button_by_default(self):
1143
+ """
1144
+ Tests that by default the "Submit for Moderation" button is shown in the action menu.
1145
+ """
1146
+ response = self.client.get(
1147
+ reverse(
1148
+ "wagtailadmin_pages:add",
1149
+ args=("tests", "simplepage", self.root_page.id),
1150
+ )
1151
+ )
1152
+ self.assertContains(
1153
+ response,
1154
+ '<button type="submit" name="action-submit" value="Submit for moderation" class="button">'
1155
+ '<svg class="icon icon-resubmit icon" aria-hidden="true"><use href="#icon-resubmit"></use></svg>'
1156
+ "Submit for moderation</button>",
1157
+ )
1158
+
1159
+ @override_settings(WAGTAIL_MODERATION_ENABLED=False)
1160
+ def test_hide_moderation_button(self):
1161
+ """
1162
+ Tests that if WAGTAIL_MODERATION_ENABLED is set to False, the "Submit for Moderation" button is not shown.
1163
+ """
1164
+ response = self.client.get(
1165
+ reverse(
1166
+ "wagtailadmin_pages:add",
1167
+ args=("tests", "simplepage", self.root_page.id),
1168
+ )
1169
+ )
1170
+ self.assertNotContains(
1171
+ response,
1172
+ '<button type="submit" name="action-submit" value="Submit for moderation" class="button">Submit for moderation</button>',
1173
+ )
1174
+
1175
+ def test_create_sets_locale_to_parent_locale(self):
1176
+ # We need to make sure the page's locale it set to the parent in the create view so that any customisations
1177
+ # for that language will take effect.
1178
+ fr_locale = Locale.objects.create(language_code="fr")
1179
+ fr_homepage = self.root_page.add_child(
1180
+ instance=Page(
1181
+ title="Home",
1182
+ slug="home-fr",
1183
+ locale=fr_locale,
1184
+ )
1185
+ )
1186
+
1187
+ response = self.client.get(
1188
+ reverse(
1189
+ "wagtailadmin_pages:add", args=("tests", "simplepage", fr_homepage.id)
1190
+ )
1191
+ )
1192
+
1193
+ self.assertEqual(response.context["page"].locale, fr_locale)
1194
+
1195
+
1196
+ class TestPermissionedFieldPanels(TestCase, WagtailTestUtils):
1197
+ fixtures = ["test.json"]
1198
+
1199
+ def setUp(self):
1200
+ # Find root page
1201
+ self.root_page = Page.objects.get(id=2)
1202
+ GroupPagePermission.objects.create(
1203
+ group=Group.objects.get(name="Site-wide editors"),
1204
+ page=self.root_page,
1205
+ permission_type="add",
1206
+ )
1207
+
1208
+ def test_create_page_with_permissioned_field_panel(self):
1209
+ """
1210
+ Test that permission rules on field panels are honoured
1211
+ """
1212
+ # non-superusers should not see secret_data
1213
+ self.login(username="siteeditor", password="password")
1214
+ response = self.client.get(
1215
+ reverse(
1216
+ "wagtailadmin_pages:add",
1217
+ args=("tests", "secretpage", self.root_page.id),
1218
+ )
1219
+ )
1220
+ self.assertEqual(response.status_code, 200)
1221
+ self.assertContains(response, '"boring_data"')
1222
+ self.assertNotContains(response, '"secret_data"')
1223
+
1224
+ # superusers should see secret_data
1225
+ self.login(username="superuser", password="password")
1226
+ response = self.client.get(
1227
+ reverse(
1228
+ "wagtailadmin_pages:add",
1229
+ args=("tests", "secretpage", self.root_page.id),
1230
+ )
1231
+ )
1232
+ self.assertEqual(response.status_code, 200)
1233
+ self.assertContains(response, '"boring_data"')
1234
+ self.assertContains(response, '"secret_data"')
1235
+
1236
+
1237
+ class TestSubpageBusinessRules(TestCase, WagtailTestUtils):
1238
+ def setUp(self):
1239
+ # Find root page
1240
+ self.root_page = Page.objects.get(id=2)
1241
+
1242
+ # Add standard page (allows subpages of any type)
1243
+ self.standard_index = StandardIndex()
1244
+ self.standard_index.title = "Standard Index"
1245
+ self.standard_index.slug = "standard-index"
1246
+ self.root_page.add_child(instance=self.standard_index)
1247
+
1248
+ # Add business page (allows BusinessChild and BusinessSubIndex as subpages)
1249
+ self.business_index = BusinessIndex()
1250
+ self.business_index.title = "Business Index"
1251
+ self.business_index.slug = "business-index"
1252
+ self.root_page.add_child(instance=self.business_index)
1253
+
1254
+ # Add business child (allows no subpages)
1255
+ self.business_child = BusinessChild()
1256
+ self.business_child.title = "Business Child"
1257
+ self.business_child.slug = "business-child"
1258
+ self.business_index.add_child(instance=self.business_child)
1259
+
1260
+ # Add business subindex (allows only BusinessChild as subpages)
1261
+ self.business_subindex = BusinessSubIndex()
1262
+ self.business_subindex.title = "Business Subindex"
1263
+ self.business_subindex.slug = "business-subindex"
1264
+ self.business_index.add_child(instance=self.business_subindex)
1265
+
1266
+ # Login
1267
+ self.login()
1268
+
1269
+ def test_standard_subpage(self):
1270
+ add_subpage_url = reverse(
1271
+ "wagtailadmin_pages:add_subpage", args=(self.standard_index.id,)
1272
+ )
1273
+
1274
+ # explorer should contain a link to 'add child page'
1275
+ response = self.client.get(
1276
+ reverse("wagtailadmin_explore", args=(self.standard_index.id,))
1277
+ )
1278
+ self.assertEqual(response.status_code, 200)
1279
+ self.assertContains(response, add_subpage_url)
1280
+
1281
+ # add_subpage should give us choices of StandardChild, and BusinessIndex.
1282
+ # BusinessSubIndex and BusinessChild are not allowed
1283
+ response = self.client.get(add_subpage_url)
1284
+ self.assertEqual(response.status_code, 200)
1285
+ self.assertContains(response, StandardChild.get_verbose_name())
1286
+ self.assertContains(response, BusinessIndex.get_verbose_name())
1287
+ self.assertNotContains(response, BusinessSubIndex.get_verbose_name())
1288
+ self.assertNotContains(response, BusinessChild.get_verbose_name())
1289
+
1290
+ def test_business_subpage(self):
1291
+ add_subpage_url = reverse(
1292
+ "wagtailadmin_pages:add_subpage", args=(self.business_index.id,)
1293
+ )
1294
+
1295
+ # explorer should contain a link to 'add child page'
1296
+ response = self.client.get(
1297
+ reverse("wagtailadmin_explore", args=(self.business_index.id,))
1298
+ )
1299
+ self.assertEqual(response.status_code, 200)
1300
+ self.assertContains(response, add_subpage_url)
1301
+
1302
+ # add_subpage should give us a cut-down set of page types to choose
1303
+ response = self.client.get(add_subpage_url)
1304
+ self.assertEqual(response.status_code, 200)
1305
+ self.assertNotContains(response, StandardIndex.get_verbose_name())
1306
+ self.assertNotContains(response, StandardChild.get_verbose_name())
1307
+ self.assertContains(response, BusinessSubIndex.get_verbose_name())
1308
+ self.assertContains(response, BusinessChild.get_verbose_name())
1309
+
1310
+ def test_business_child_subpage(self):
1311
+ add_subpage_url = reverse(
1312
+ "wagtailadmin_pages:add_subpage", args=(self.business_child.id,)
1313
+ )
1314
+
1315
+ # explorer should not contain a link to 'add child page', as this page doesn't accept subpages
1316
+ response = self.client.get(
1317
+ reverse("wagtailadmin_explore", args=(self.business_child.id,))
1318
+ )
1319
+ self.assertEqual(response.status_code, 200)
1320
+ self.assertNotContains(response, add_subpage_url)
1321
+
1322
+ # this also means that fetching add_subpage is blocked at the permission-check level
1323
+ response = self.client.get(
1324
+ reverse("wagtailadmin_pages:add_subpage", args=(self.business_child.id,))
1325
+ )
1326
+ self.assertEqual(response.status_code, 302)
1327
+
1328
+ def test_cannot_add_invalid_subpage_type(self):
1329
+ # cannot add StandardChild as a child of BusinessIndex, as StandardChild is not present in subpage_types
1330
+ response = self.client.get(
1331
+ reverse(
1332
+ "wagtailadmin_pages:add",
1333
+ args=("tests", "standardchild", self.business_index.id),
1334
+ )
1335
+ )
1336
+ self.assertRedirects(response, "/admin/")
1337
+
1338
+ # likewise for BusinessChild which has an empty subpage_types list
1339
+ response = self.client.get(
1340
+ reverse(
1341
+ "wagtailadmin_pages:add",
1342
+ args=("tests", "standardchild", self.business_child.id),
1343
+ )
1344
+ )
1345
+ self.assertRedirects(response, "/admin/")
1346
+
1347
+ # cannot add BusinessChild to StandardIndex, as BusinessChild restricts is parent page types
1348
+ response = self.client.get(
1349
+ reverse(
1350
+ "wagtailadmin_pages:add",
1351
+ args=("tests", "businesschild", self.standard_index.id),
1352
+ )
1353
+ )
1354
+ self.assertRedirects(response, "/admin/")
1355
+
1356
+ # but we can add a BusinessChild to BusinessIndex
1357
+ response = self.client.get(
1358
+ reverse(
1359
+ "wagtailadmin_pages:add",
1360
+ args=("tests", "businesschild", self.business_index.id),
1361
+ )
1362
+ )
1363
+ self.assertEqual(response.status_code, 200)
1364
+
1365
+ def test_not_prompted_for_page_type_when_only_one_choice(self):
1366
+ response = self.client.get(
1367
+ reverse("wagtailadmin_pages:add_subpage", args=(self.business_subindex.id,))
1368
+ )
1369
+ # BusinessChild is the only valid subpage type of BusinessSubIndex, so redirect straight there
1370
+ self.assertRedirects(
1371
+ response,
1372
+ reverse(
1373
+ "wagtailadmin_pages:add",
1374
+ args=("tests", "businesschild", self.business_subindex.id),
1375
+ ),
1376
+ )
1377
+
1378
+
1379
+ class TestInlinePanelMedia(TestCase, WagtailTestUtils):
1380
+ """
1381
+ Test that form media required by InlinePanels is correctly pulled in to the edit page
1382
+ """
1383
+
1384
+ def test_inline_panel_media(self):
1385
+ homepage = Page.objects.get(id=2)
1386
+ self.login()
1387
+
1388
+ # simplepage does not need draftail...
1389
+ response = self.client.get(
1390
+ reverse("wagtailadmin_pages:add", args=("tests", "simplepage", homepage.id))
1391
+ )
1392
+ self.assertEqual(response.status_code, 200)
1393
+ self.assertNotContains(response, "wagtailadmin/js/draftail.js")
1394
+
1395
+ # but sectionedrichtextpage does
1396
+ response = self.client.get(
1397
+ reverse(
1398
+ "wagtailadmin_pages:add",
1399
+ args=("tests", "sectionedrichtextpage", homepage.id),
1400
+ )
1401
+ )
1402
+ self.assertEqual(response.status_code, 200)
1403
+ self.assertContains(response, "wagtailadmin/js/draftail.js")
1404
+
1405
+
1406
+ class TestInlineStreamField(TestCase, WagtailTestUtils):
1407
+ """
1408
+ Test that streamfields inside an inline child work
1409
+ """
1410
+
1411
+ def test_inline_streamfield(self):
1412
+ homepage = Page.objects.get(id=2)
1413
+ self.login()
1414
+
1415
+ response = self.client.get(
1416
+ reverse(
1417
+ "wagtailadmin_pages:add",
1418
+ args=("tests", "inlinestreampage", homepage.id),
1419
+ )
1420
+ )
1421
+ self.assertEqual(response.status_code, 200)
1422
+
1423
+ # response should include HTML declarations for streamfield child blocks
1424
+ self.assertContains(response, '<div id="sections-__prefix__-body" data-block="')
1425
+
1426
+
1427
+ class TestIssue2994(TestCase, WagtailTestUtils):
1428
+ """
1429
+ In contrast to most "standard" form fields, StreamField form widgets generally won't
1430
+ provide a postdata field with a name exactly matching the field name. To prevent Django
1431
+ from wrongly interpreting this as the field being omitted from the form,
1432
+ we need to provide a custom value_omitted_from_data method.
1433
+ """
1434
+
1435
+ def setUp(self):
1436
+ self.root_page = Page.objects.get(id=2)
1437
+ self.user = self.login()
1438
+
1439
+ def test_page_edit_post_publish_url(self):
1440
+ # Post
1441
+ post_data = {
1442
+ "title": "Issue 2994 test",
1443
+ "slug": "issue-2994-test",
1444
+ "body-count": "1",
1445
+ "body-0-deleted": "",
1446
+ "body-0-order": "0",
1447
+ "body-0-type": "text",
1448
+ "body-0-value": "hello world",
1449
+ "action-publish": "Publish",
1450
+ }
1451
+ self.client.post(
1452
+ reverse(
1453
+ "wagtailadmin_pages:add",
1454
+ args=("tests", "defaultstreampage", self.root_page.id),
1455
+ ),
1456
+ post_data,
1457
+ )
1458
+ new_page = DefaultStreamPage.objects.get(slug="issue-2994-test")
1459
+ self.assertEqual(1, len(new_page.body))
1460
+ self.assertEqual("hello world", new_page.body[0].value)
1461
+
1462
+
1463
+ class TestInlinePanelWithTags(TestCase, WagtailTestUtils):
1464
+ # https://github.com/wagtail/wagtail/issues/5414#issuecomment-567080707
1465
+
1466
+ def setUp(self):
1467
+ self.root_page = Page.objects.get(id=2)
1468
+ self.user = self.login()
1469
+
1470
+ def test_create(self):
1471
+ post_data = {
1472
+ "title": "Mr Benn",
1473
+ "slug": "mr-benn",
1474
+ "first_name": "William",
1475
+ "last_name": "Benn",
1476
+ "addresses-TOTAL_FORMS": 1,
1477
+ "addresses-INITIAL_FORMS": 0,
1478
+ "addresses-MIN_NUM_FORMS": 0,
1479
+ "addresses-MAX_NUM_FORMS": 1000,
1480
+ "addresses-0-address": "52 Festive Road, London",
1481
+ "addresses-0-tags": "shopkeeper, bowler-hat",
1482
+ "action-publish": "Publish",
1483
+ "comments-TOTAL_FORMS": 0,
1484
+ "comments-INITIAL_FORMS": 0,
1485
+ "comments-MIN_NUM_FORMS": 0,
1486
+ "comments-MAX_NUM_FORMS": 1000,
1487
+ }
1488
+ response = self.client.post(
1489
+ reverse(
1490
+ "wagtailadmin_pages:add",
1491
+ args=("tests", "personpage", self.root_page.id),
1492
+ ),
1493
+ post_data,
1494
+ )
1495
+ self.assertRedirects(
1496
+ response, reverse("wagtailadmin_explore", args=(self.root_page.id,))
1497
+ )
1498
+ new_page = PersonPage.objects.get(slug="mr-benn")
1499
+ self.assertEqual(new_page.addresses.first().tags.count(), 2)
1500
+
1501
+
1502
+ class TestInlinePanelNonFieldErrors(TestCase, WagtailTestUtils):
1503
+ """
1504
+ Test that non field errors will render for InlinePanels
1505
+ https://github.com/wagtail/wagtail/issues/3890
1506
+ """
1507
+
1508
+ fixtures = ["demosite.json"]
1509
+
1510
+ def setUp(self):
1511
+ self.root_page = Page.objects.get(id=2)
1512
+ self.user = self.login()
1513
+
1514
+ def test_create(self):
1515
+ post_data = {
1516
+ "title": "Issue 3890 test",
1517
+ "slug": "issue-3890-test",
1518
+ "related_links-TOTAL_FORMS": 1,
1519
+ "related_links-INITIAL_FORMS": 0,
1520
+ "related_links-MIN_NUM_FORMS": 0,
1521
+ "related_links-MAX_NUM_FORMS": 1000,
1522
+ "related_links-0-id": 0,
1523
+ "related_links-0-ORDER": 1,
1524
+ # Leaving all fields empty should raise a validation error
1525
+ "related_links-0-link_page": "",
1526
+ "related_links-0-link_document": "",
1527
+ "related_links-0-link_external": "",
1528
+ "carousel_items-INITIAL_FORMS": 0,
1529
+ "carousel_items-MAX_NUM_FORMS": 1000,
1530
+ "carousel_items-TOTAL_FORMS": 0,
1531
+ "action-publish": "Publish",
1532
+ "comments-TOTAL_FORMS": 0,
1533
+ "comments-INITIAL_FORMS": 0,
1534
+ "comments-MIN_NUM_FORMS": 0,
1535
+ "comments-MAX_NUM_FORMS": 1000,
1536
+ }
1537
+ response = self.client.post(
1538
+ reverse(
1539
+ "wagtailadmin_pages:add",
1540
+ args=("demosite", "homepage", self.root_page.id),
1541
+ ),
1542
+ post_data,
1543
+ )
1544
+ self.assertEqual(response.status_code, 200)
1545
+ self.assertContains(
1546
+ response, "The page could not be created due to validation errors"
1547
+ )
1548
+ self.assertContains(
1549
+ response,
1550
+ "You must provide a related page, related document or an external URL",
1551
+ count=1,
1552
+ )
1553
+
1554
+
1555
+ @override_settings(WAGTAIL_I18N_ENABLED=True)
1556
+ class TestLocaleSelector(TestCase, WagtailTestUtils):
1557
+ fixtures = ["test.json"]
1558
+
1559
+ def setUp(self):
1560
+ self.events_page = Page.objects.get(url_path="/home/events/")
1561
+ self.fr_locale = Locale.objects.create(language_code="fr")
1562
+ self.translated_events_page = self.events_page.copy_for_translation(
1563
+ self.fr_locale, copy_parents=True
1564
+ )
1565
+ self.user = self.login()
1566
+
1567
+ @unittest.expectedFailure # TODO: Page editor header rewrite
1568
+ def test_locale_selector(self):
1569
+ response = self.client.get(
1570
+ reverse(
1571
+ "wagtailadmin_pages:add",
1572
+ args=["tests", "eventpage", self.events_page.id],
1573
+ )
1574
+ )
1575
+
1576
+ self.assertContains(response, 'id="status-sidebar-english"')
1577
+
1578
+ add_translation_url = reverse(
1579
+ "wagtailadmin_pages:add",
1580
+ args=["tests", "eventpage", self.translated_events_page.id],
1581
+ )
1582
+ self.assertContains(response, f'href="{add_translation_url}"')
1583
+
1584
+ @override_settings(WAGTAIL_I18N_ENABLED=False)
1585
+ def test_locale_selector_not_present_when_i18n_disabled(self):
1586
+ response = self.client.get(
1587
+ reverse(
1588
+ "wagtailadmin_pages:add",
1589
+ args=["tests", "eventpage", self.events_page.id],
1590
+ )
1591
+ )
1592
+
1593
+ self.assertNotContains(response, "Page Locale:")
1594
+
1595
+ add_translation_url = reverse(
1596
+ "wagtailadmin_pages:add",
1597
+ args=["tests", "eventpage", self.translated_events_page.id],
1598
+ )
1599
+ self.assertNotContains(response, f'href="{add_translation_url}"')
1600
+
1601
+ def test_locale_selector_not_present_without_permission_to_add(self):
1602
+ # Remove user's permissions to add in the French tree
1603
+ group = Group.objects.get(name="Moderators")
1604
+ GroupPagePermission.objects.create(
1605
+ group=group,
1606
+ page=self.events_page,
1607
+ permission_type="add",
1608
+ )
1609
+ self.user.is_superuser = False
1610
+ self.user.user_permissions.add(
1611
+ Permission.objects.get(
1612
+ content_type__app_label="wagtailadmin", codename="access_admin"
1613
+ )
1614
+ )
1615
+ self.user.groups.add(group)
1616
+ self.user.save()
1617
+
1618
+ # Locale indicator should exist, but the "French" option should be hidden
1619
+ response = self.client.get(
1620
+ reverse(
1621
+ "wagtailadmin_pages:add",
1622
+ args=["tests", "eventpage", self.events_page.id],
1623
+ )
1624
+ )
1625
+
1626
+ self.assertContains(response, 'id="status-sidebar-english"')
1627
+
1628
+ add_translation_url = reverse(
1629
+ "wagtailadmin_pages:add",
1630
+ args=["tests", "eventpage", self.translated_events_page.id],
1631
+ )
1632
+ self.assertNotContains(response, f'href="{add_translation_url}"')
1633
+
1634
+
1635
+ @override_settings(WAGTAIL_I18N_ENABLED=True)
1636
+ class TestLocaleSelectorOnRootPage(TestCase, WagtailTestUtils):
1637
+ fixtures = ["test.json"]
1638
+
1639
+ def setUp(self):
1640
+ self.root_page = Page.objects.get(id=1)
1641
+ self.fr_locale = Locale.objects.create(language_code="fr")
1642
+ self.user = self.login()
1643
+
1644
+ @unittest.expectedFailure # TODO: Page editor header rewrite
1645
+ def test_locale_selector(self):
1646
+ response = self.client.get(
1647
+ reverse(
1648
+ "wagtailadmin_pages:add",
1649
+ args=["demosite", "homepage", self.root_page.id],
1650
+ )
1651
+ )
1652
+
1653
+ self.assertContains(response, 'id="status-sidebar-english"')
1654
+
1655
+ add_translation_url = (
1656
+ reverse(
1657
+ "wagtailadmin_pages:add",
1658
+ args=["demosite", "homepage", self.root_page.id],
1659
+ )
1660
+ + "?locale=fr"
1661
+ )
1662
+ self.assertContains(response, f'href="{add_translation_url}"')
1663
+
1664
+ @override_settings(WAGTAIL_I18N_ENABLED=False)
1665
+ def test_locale_selector_not_present_when_i18n_disabled(self):
1666
+ response = self.client.get(
1667
+ reverse(
1668
+ "wagtailadmin_pages:add",
1669
+ args=["demosite", "homepage", self.root_page.id],
1670
+ )
1671
+ )
1672
+
1673
+ self.assertNotContains(response, "Page Locale:")
1674
+
1675
+ add_translation_url = (
1676
+ reverse(
1677
+ "wagtailadmin_pages:add",
1678
+ args=["demosite", "homepage", self.root_page.id],
1679
+ )
1680
+ + "?locale=fr"
1681
+ )
1682
+ self.assertNotContains(response, f'href="{add_translation_url}"')
1683
+
1684
+
1685
+ class TestPageSubscriptionSettings(TestCase, WagtailTestUtils):
1686
+ def setUp(self):
1687
+ # Find root page
1688
+ self.root_page = Page.objects.get(id=2)
1689
+
1690
+ # Login
1691
+ self.user = self.login()
1692
+
1693
+ def test_commment_notifications_switched_on_by_default(self):
1694
+ response = self.client.get(
1695
+ reverse(
1696
+ "wagtailadmin_pages:add",
1697
+ args=["tests", "simplepage", self.root_page.id],
1698
+ )
1699
+ )
1700
+
1701
+ self.assertEqual(response.status_code, 200)
1702
+ self.assertContains(
1703
+ response,
1704
+ '<input type="checkbox" name="comment_notifications" id="id_comment_notifications" checked>',
1705
+ )
1706
+
1707
+ def test_post_with_comment_notifications_switched_on(self):
1708
+ post_data = {
1709
+ "title": "New page!",
1710
+ "content": "Some content",
1711
+ "slug": "hello-world",
1712
+ "comment_notifications": "on",
1713
+ }
1714
+ response = self.client.post(
1715
+ reverse(
1716
+ "wagtailadmin_pages:add",
1717
+ args=["tests", "simplepage", self.root_page.id],
1718
+ ),
1719
+ post_data,
1720
+ )
1721
+
1722
+ page = Page.objects.get(
1723
+ path__startswith=self.root_page.path, slug="hello-world"
1724
+ ).specific
1725
+
1726
+ self.assertRedirects(
1727
+ response, reverse("wagtailadmin_pages:edit", args=[page.id])
1728
+ )
1729
+
1730
+ # Check the subscription
1731
+ subscription = page.subscribers.get()
1732
+
1733
+ self.assertEqual(subscription.user, self.user)
1734
+ self.assertTrue(subscription.comment_notifications)
1735
+
1736
+ def test_post_with_comment_notifications_switched_off(self):
1737
+ post_data = {
1738
+ "title": "New page!",
1739
+ "content": "Some content",
1740
+ "slug": "hello-world",
1741
+ }
1742
+ response = self.client.post(
1743
+ reverse(
1744
+ "wagtailadmin_pages:add",
1745
+ args=["tests", "simplepage", self.root_page.id],
1746
+ ),
1747
+ post_data,
1748
+ )
1749
+
1750
+ page = Page.objects.get(
1751
+ path__startswith=self.root_page.path, slug="hello-world"
1752
+ ).specific
1753
+
1754
+ self.assertRedirects(
1755
+ response, reverse("wagtailadmin_pages:edit", args=[page.id])
1756
+ )
1757
+
1758
+ # Check the subscription
1759
+ subscription = page.subscribers.get()
1760
+
1761
+ self.assertEqual(subscription.user, self.user)
1762
+ self.assertFalse(subscription.comment_notifications)
testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_delete_page.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from unittest import mock
2
+
3
+ from django.contrib.auth.models import Permission
4
+ from django.db.models.signals import post_delete, pre_delete
5
+ from django.http import HttpRequest, HttpResponse
6
+ from django.test import TestCase, override_settings
7
+ from django.urls import reverse
8
+
9
+ from wagtail.models import Page
10
+ from wagtail.signals import page_unpublished
11
+ from wagtail.test.testapp.models import SimplePage, StandardChild, StandardIndex
12
+ from wagtail.test.utils import WagtailTestUtils
13
+
14
+
15
+ class TestPageDelete(TestCase, WagtailTestUtils):
16
+ def setUp(self):
17
+ # Find root page
18
+ self.root_page = Page.objects.get(id=2)
19
+
20
+ # Add child page
21
+ self.child_page = SimplePage(
22
+ title="Hello world!", slug="hello-world", content="hello"
23
+ )
24
+ self.root_page.add_child(instance=self.child_page)
25
+
26
+ # Add a page with child pages of its own
27
+ self.child_index = StandardIndex(title="Hello index", slug="hello-index")
28
+ self.root_page.add_child(instance=self.child_index)
29
+ self.grandchild_page = StandardChild(title="Hello Kitty", slug="hello-kitty")
30
+ self.child_index.add_child(instance=self.grandchild_page)
31
+
32
+ # Login
33
+ self.user = self.login()
34
+
35
+ def test_page_delete(self):
36
+ response = self.client.get(
37
+ reverse("wagtailadmin_pages:delete", args=(self.child_page.id,))
38
+ )
39
+ self.assertEqual(response.status_code, 200)
40
+ # deletion should not actually happen on GET
41
+ self.assertTrue(SimplePage.objects.filter(id=self.child_page.id).exists())
42
+
43
+ @override_settings(WAGTAILADMIN_UNSAFE_PAGE_DELETION_LIMIT=10)
44
+ def test_confirm_delete_scenario_1(self):
45
+ # If the number of pages to be deleted are less than
46
+ # WAGTAILADMIN_UNSAFE_PAGE_DELETION_LIMIT then don't need
47
+ # for confirmation
48
+ child_1 = SimplePage(title="child 1", slug="child-1", content="hello")
49
+ self.child_page.add_child(instance=child_1)
50
+ child_2 = SimplePage(title="child 2", slug="child-2", content="hello")
51
+ self.child_page.add_child(instance=child_2)
52
+ response = self.client.get(
53
+ reverse("wagtailadmin_pages:delete", args=(self.child_page.id,))
54
+ )
55
+ self.assertEqual(response.status_code, 200)
56
+ self.assertNotContains(response, '<input type="text" name="confirm_site_name"')
57
+ # deletion should not actually happen on GET
58
+ self.assertTrue(SimplePage.objects.filter(id=self.child_page.id).exists())
59
+
60
+ # And admin should be able to delete page without any confirmation
61
+ response = self.client.post(
62
+ reverse("wagtailadmin_pages:delete", args=(self.child_page.id,))
63
+ )
64
+ # Check that page is deleted
65
+ self.assertFalse(SimplePage.objects.filter(id=self.child_page.id).exists())
66
+
67
+ @override_settings(WAGTAILADMIN_UNSAFE_PAGE_DELETION_LIMIT=3)
68
+ @override_settings(WAGTAIL_SITE_NAME="mysite")
69
+ def test_confirm_delete_scenario_2(self):
70
+ # If the number of pages to be deleted are greater than or equal to
71
+ # WAGTAILADMIN_UNSAFE_PAGE_DELETION_LIMIT then show input box
72
+ # to input wagtail_site_name.
73
+ child_1 = SimplePage(title="child 1", slug="child-1", content="hello")
74
+ self.child_page.add_child(instance=child_1)
75
+ child_2 = SimplePage(title="child 2", slug="child-2", content="hello")
76
+ self.child_page.add_child(instance=child_2)
77
+ response = self.client.get(
78
+ reverse("wagtailadmin_pages:delete", args=(self.child_page.id,))
79
+ )
80
+ self.assertEqual(response.status_code, 200)
81
+ self.assertContains(response, "This action will delete total <b>3</b> pages.")
82
+ self.assertContains(response, "Please type <b>mysite</b> to confirm.")
83
+ self.assertContains(response, '<input type="text" name="confirm_site_name"')
84
+ # deletion should not actually happen on GET
85
+ self.assertTrue(SimplePage.objects.filter(id=self.child_page.id).exists())
86
+
87
+ @override_settings(WAGTAILADMIN_UNSAFE_PAGE_DELETION_LIMIT=3)
88
+ @override_settings(WAGTAIL_SITE_NAME="mysite")
89
+ def test_confirm_delete_scenario_3(self):
90
+ # If admin entered the incorrect site name and submit
91
+ # the form, then site should not be deleted and same
92
+ # form should be displayed again.
93
+ child_1 = SimplePage(title="child 1", slug="child-1", content="hello")
94
+ self.child_page.add_child(instance=child_1)
95
+ child_2 = SimplePage(title="child 2", slug="child-2", content="hello")
96
+ self.child_page.add_child(instance=child_2)
97
+ response = self.client.post(
98
+ reverse("wagtailadmin_pages:delete", args=(self.child_page.id,)),
99
+ data={"confirm_site_name": "random"},
100
+ )
101
+ self.assertEqual(response.status_code, 200)
102
+ # One error messages should be returned
103
+ messages = [m.message for m in response.context["messages"]]
104
+ self.assertEqual(len(messages), 1)
105
+ self.assertContains(response, "This action will delete total <b>3</b> pages.")
106
+ self.assertContains(response, "Please type <b>mysite</b> to confirm.")
107
+ self.assertContains(response, '<input type="text" name="confirm_site_name"')
108
+ # Site should not be deleted
109
+ self.assertTrue(SimplePage.objects.filter(id=self.child_page.id).exists())
110
+
111
+ @override_settings(WAGTAILADMIN_UNSAFE_PAGE_DELETION_LIMIT=3)
112
+ @override_settings(WAGTAIL_SITE_NAME="mysite")
113
+ def test_confirm_delete_scenario_4(self):
114
+ # If admin entered the correct site name and submit the form
115
+ # then the site should be deleted
116
+ child_1 = SimplePage(title="child 1", slug="child-1", content="hello")
117
+ self.child_page.add_child(instance=child_1)
118
+ child_2 = SimplePage(title="child 2", slug="child-2", content="hello")
119
+ self.child_page.add_child(instance=child_2)
120
+ response = self.client.post(
121
+ reverse("wagtailadmin_pages:delete", args=(self.child_page.id,)),
122
+ data={"confirm_site_name": "mysite"},
123
+ )
124
+ # Should be redirected to explorer page
125
+ self.assertRedirects(
126
+ response, reverse("wagtailadmin_explore", args=(self.root_page.id,))
127
+ )
128
+ # Check that the page is deleted
129
+ self.assertFalse(SimplePage.objects.filter(id=self.child_page.id).exists())
130
+ # Check that the subpage is also deleted
131
+ self.assertFalse(SimplePage.objects.filter(id=child_1.id).exists())
132
+ self.assertFalse(SimplePage.objects.filter(id=child_2.id).exists())
133
+
134
+ def test_page_delete_specific_admin_title(self):
135
+ response = self.client.get(
136
+ reverse("wagtailadmin_pages:delete", args=(self.child_page.id,))
137
+ )
138
+ self.assertEqual(response.status_code, 200)
139
+
140
+ # The admin_display_title specific to ChildPage is shown on the delete confirmation page.
141
+ self.assertContains(response, self.child_page.get_admin_display_title())
142
+
143
+ def test_page_delete_bad_permissions(self):
144
+ # Remove privileges from user
145
+ self.user.is_superuser = False
146
+ self.user.user_permissions.add(
147
+ Permission.objects.get(
148
+ content_type__app_label="wagtailadmin", codename="access_admin"
149
+ )
150
+ )
151
+ self.user.save()
152
+
153
+ # Get delete page
154
+ response = self.client.get(
155
+ reverse("wagtailadmin_pages:delete", args=(self.child_page.id,))
156
+ )
157
+
158
+ # Check that the user received a 302 redirect response
159
+ self.assertEqual(response.status_code, 302)
160
+
161
+ # Check that the deletion has not happened
162
+ self.assertTrue(SimplePage.objects.filter(id=self.child_page.id).exists())
163
+
164
+ def test_page_delete_post(self):
165
+ # Connect a mock signal handler to page_unpublished signal
166
+ mock_handler = mock.MagicMock()
167
+ page_unpublished.connect(mock_handler)
168
+
169
+ # Post
170
+ response = self.client.post(
171
+ reverse("wagtailadmin_pages:delete", args=(self.child_page.id,))
172
+ )
173
+
174
+ # Should be redirected to explorer page
175
+ self.assertRedirects(
176
+ response, reverse("wagtailadmin_explore", args=(self.root_page.id,))
177
+ )
178
+
179
+ # treebeard should report no consistency problems with the tree
180
+ self.assertFalse(
181
+ any(Page.find_problems()), "treebeard found consistency problems"
182
+ )
183
+
184
+ # Check that the page is gone
185
+ self.assertEqual(
186
+ Page.objects.filter(
187
+ path__startswith=self.root_page.path, slug="hello-world"
188
+ ).count(),
189
+ 0,
190
+ )
191
+
192
+ # Check that the page_unpublished signal was fired
193
+ self.assertEqual(mock_handler.call_count, 1)
194
+ mock_call = mock_handler.mock_calls[0][2]
195
+
196
+ self.assertEqual(mock_call["sender"], self.child_page.specific_class)
197
+ self.assertEqual(mock_call["instance"], self.child_page)
198
+ self.assertIsInstance(mock_call["instance"], self.child_page.specific_class)
199
+
200
+ def test_page_delete_notlive_post(self):
201
+ # Same as above, but this makes sure the page_unpublished signal is not fired
202
+ # when if the page is not live when it is deleted
203
+
204
+ # Unpublish the page
205
+ self.child_page.live = False
206
+ self.child_page.save()
207
+
208
+ # Connect a mock signal handler to page_unpublished signal
209
+ mock_handler = mock.MagicMock()
210
+ page_unpublished.connect(mock_handler)
211
+
212
+ # Post
213
+ response = self.client.post(
214
+ reverse("wagtailadmin_pages:delete", args=(self.child_page.id,))
215
+ )
216
+
217
+ # Should be redirected to explorer page
218
+ self.assertRedirects(
219
+ response, reverse("wagtailadmin_explore", args=(self.root_page.id,))
220
+ )
221
+
222
+ # treebeard should report no consistency problems with the tree
223
+ self.assertFalse(
224
+ any(Page.find_problems()), "treebeard found consistency problems"
225
+ )
226
+
227
+ # Check that the page is gone
228
+ self.assertEqual(
229
+ Page.objects.filter(
230
+ path__startswith=self.root_page.path, slug="hello-world"
231
+ ).count(),
232
+ 0,
233
+ )
234
+
235
+ # Check that the page_unpublished signal was not fired
236
+ self.assertEqual(mock_handler.call_count, 0)
237
+
238
+ def test_subpage_deletion(self):
239
+ # Connect mock signal handlers to page_unpublished, pre_delete and post_delete signals
240
+ unpublish_signals_received = []
241
+ pre_delete_signals_received = []
242
+ post_delete_signals_received = []
243
+
244
+ def page_unpublished_handler(sender, instance, **kwargs):
245
+ unpublish_signals_received.append((sender, instance.id))
246
+
247
+ def pre_delete_handler(sender, instance, **kwargs):
248
+ pre_delete_signals_received.append((sender, instance.id))
249
+
250
+ def post_delete_handler(sender, instance, **kwargs):
251
+ post_delete_signals_received.append((sender, instance.id))
252
+
253
+ page_unpublished.connect(page_unpublished_handler)
254
+ pre_delete.connect(pre_delete_handler)
255
+ post_delete.connect(post_delete_handler)
256
+
257
+ # Post
258
+ response = self.client.post(
259
+ reverse("wagtailadmin_pages:delete", args=(self.child_index.id,))
260
+ )
261
+
262
+ # Should be redirected to explorer page
263
+ self.assertRedirects(
264
+ response, reverse("wagtailadmin_explore", args=(self.root_page.id,))
265
+ )
266
+
267
+ # treebeard should report no consistency problems with the tree
268
+ self.assertFalse(
269
+ any(Page.find_problems()), "treebeard found consistency problems"
270
+ )
271
+
272
+ # Check that the page is gone
273
+ self.assertFalse(StandardIndex.objects.filter(id=self.child_index.id).exists())
274
+ self.assertFalse(Page.objects.filter(id=self.child_index.id).exists())
275
+
276
+ # Check that the subpage is also gone
277
+ self.assertFalse(
278
+ StandardChild.objects.filter(id=self.grandchild_page.id).exists()
279
+ )
280
+ self.assertFalse(Page.objects.filter(id=self.grandchild_page.id).exists())
281
+
282
+ # Check that the signals were fired for both pages
283
+ self.assertIn((StandardIndex, self.child_index.id), unpublish_signals_received)
284
+ self.assertIn(
285
+ (StandardChild, self.grandchild_page.id), unpublish_signals_received
286
+ )
287
+
288
+ self.assertIn((StandardIndex, self.child_index.id), pre_delete_signals_received)
289
+ self.assertIn(
290
+ (StandardChild, self.grandchild_page.id), pre_delete_signals_received
291
+ )
292
+
293
+ self.assertIn(
294
+ (StandardIndex, self.child_index.id), post_delete_signals_received
295
+ )
296
+ self.assertIn(
297
+ (StandardChild, self.grandchild_page.id), post_delete_signals_received
298
+ )
299
+
300
+ def test_before_delete_page_hook(self):
301
+ def hook_func(request, page):
302
+ self.assertIsInstance(request, HttpRequest)
303
+ self.assertEqual(page.id, self.child_page.id)
304
+
305
+ return HttpResponse("Overridden!")
306
+
307
+ with self.register_hook("before_delete_page", hook_func):
308
+ response = self.client.get(
309
+ reverse("wagtailadmin_pages:delete", args=(self.child_page.id,))
310
+ )
311
+
312
+ self.assertEqual(response.status_code, 200)
313
+ self.assertEqual(response.content, b"Overridden!")
314
+
315
+ def test_before_delete_page_hook_post(self):
316
+ def hook_func(request, page):
317
+ self.assertIsInstance(request, HttpRequest)
318
+ self.assertEqual(page.id, self.child_page.id)
319
+
320
+ return HttpResponse("Overridden!")
321
+
322
+ with self.register_hook("before_delete_page", hook_func):
323
+ response = self.client.post(
324
+ reverse("wagtailadmin_pages:delete", args=(self.child_page.id,))
325
+ )
326
+
327
+ self.assertEqual(response.status_code, 200)
328
+ self.assertEqual(response.content, b"Overridden!")
329
+
330
+ # page should not be deleted
331
+ self.assertTrue(Page.objects.filter(id=self.child_page.id).exists())
332
+
333
+ def test_after_delete_page_hook(self):
334
+ def hook_func(request, page):
335
+ self.assertIsInstance(request, HttpRequest)
336
+ self.assertEqual(page.id, self.child_page.id)
337
+
338
+ return HttpResponse("Overridden!")
339
+
340
+ with self.register_hook("after_delete_page", hook_func):
341
+ response = self.client.post(
342
+ reverse("wagtailadmin_pages:delete", args=(self.child_page.id,))
343
+ )
344
+
345
+ self.assertEqual(response.status_code, 200)
346
+ self.assertEqual(response.content, b"Overridden!")
347
+
348
+ # page should be deleted
349
+ self.assertFalse(Page.objects.filter(id=self.child_page.id).exists())
testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_move_page.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from unittest import mock
2
+
3
+ from django.contrib.auth import get_user_model
4
+ from django.contrib.auth.models import Permission
5
+ from django.contrib.messages import constants as message_constants
6
+ from django.http import HttpRequest, HttpResponse
7
+ from django.test import TestCase
8
+ from django.urls import reverse
9
+
10
+ from wagtail.models import Page
11
+ from wagtail.signals import post_page_move, pre_page_move
12
+ from wagtail.test.testapp.models import SimplePage
13
+ from wagtail.test.utils import WagtailTestUtils
14
+
15
+
16
+ class TestPageMove(TestCase, WagtailTestUtils):
17
+ fixtures = ["test.json"]
18
+
19
+ def setUp(self):
20
+ # Find root page
21
+ self.root_page = Page.objects.get(id=2)
22
+
23
+ # Create three sections
24
+ self.section_a = SimplePage(
25
+ title="Section A", slug="section-a", content="hello"
26
+ )
27
+ self.root_page.add_child(instance=self.section_a)
28
+
29
+ self.section_b = SimplePage(
30
+ title="Section B", slug="section-b", content="hello"
31
+ )
32
+ self.root_page.add_child(instance=self.section_b)
33
+
34
+ self.section_c = SimplePage(
35
+ title="Section C", slug="section-c", content="hello"
36
+ )
37
+ self.root_page.add_child(instance=self.section_c)
38
+
39
+ # Add test page A into section A
40
+ self.test_page_a = SimplePage(
41
+ title="Hello world!", slug="hello-world", content="hello"
42
+ )
43
+ self.section_a.add_child(instance=self.test_page_a)
44
+
45
+ # Add test page B into section C
46
+ self.test_page_b = SimplePage(
47
+ title="Hello world!", slug="hello-world", content="hello"
48
+ )
49
+ self.section_c.add_child(instance=self.test_page_b)
50
+
51
+ # Add unpublished page to the root with a child page
52
+ self.unpublished_page = SimplePage(
53
+ title="Unpublished", slug="unpublished", content="hello"
54
+ )
55
+ sub_page = SimplePage(title="Sub Page", slug="sub-page", content="child")
56
+ self.root_page.add_child(instance=self.unpublished_page)
57
+ self.unpublished_page.add_child(instance=sub_page)
58
+
59
+ # unpublish pages last (used to validate the edit only permission)
60
+ self.unpublished_page.unpublish()
61
+ sub_page.unpublish()
62
+
63
+ # Login
64
+ self.user = self.login()
65
+
66
+ def test_page_move(self):
67
+ response = self.client.get(
68
+ reverse("wagtailadmin_pages:move", args=(self.test_page_a.id,))
69
+ )
70
+ self.assertEqual(response.status_code, 200)
71
+
72
+ def test_page_move_bad_permissions(self):
73
+ # Remove privileges from user
74
+ self.user.is_superuser = False
75
+ self.user.user_permissions.add(
76
+ Permission.objects.get(
77
+ content_type__app_label="wagtailadmin", codename="access_admin"
78
+ )
79
+ )
80
+ self.user.save()
81
+
82
+ # Get move page
83
+ response = self.client.get(
84
+ reverse("wagtailadmin_pages:move", args=(self.test_page_a.id,))
85
+ )
86
+
87
+ # Check that the user received a 302 redirected response
88
+ self.assertEqual(response.status_code, 302)
89
+
90
+ def test_user_without_bulk_delete_permission_can_move(self):
91
+ # to verify that a user without bulk delete permission is able to move a page with a child page
92
+
93
+ self.client.logout()
94
+ user = get_user_model().objects.get(email="siteeditor@example.com")
95
+ self.login(user)
96
+
97
+ # ensure the bulk_delete is not applicable to this user
98
+ can_bulk_delete = self.test_page_b.permissions_for_user(user).can_delete()
99
+ self.assertFalse(can_bulk_delete)
100
+
101
+ response = self.client.get(
102
+ reverse("wagtailadmin_pages:move", args=(self.unpublished_page.id,))
103
+ )
104
+
105
+ self.assertEqual(response.status_code, 200)
106
+
107
+ def test_page_move_confirm(self):
108
+ response = self.client.get(
109
+ reverse(
110
+ "wagtailadmin_pages:move_confirm",
111
+ args=(self.test_page_a.id, self.section_b.id),
112
+ )
113
+ )
114
+ self.assertEqual(response.status_code, 200)
115
+
116
+ response = self.client.get(
117
+ reverse(
118
+ "wagtailadmin_pages:move_confirm",
119
+ args=(self.test_page_b.id, self.section_a.id),
120
+ )
121
+ )
122
+ # Duplicate slugs triggers a redirect with an error message.
123
+ self.assertEqual(response.status_code, 302)
124
+
125
+ response = self.client.get(reverse("wagtailadmin_home"))
126
+ messages = list(response.context["messages"])
127
+ self.assertEqual(len(messages), 1)
128
+ self.assertEqual(messages[0].level, message_constants.ERROR)
129
+ # Slug should be in error message.
130
+ self.assertIn("{}".format(self.test_page_b.slug), messages[0].message)
131
+
132
+ def test_move_triggers_signals(self):
133
+ # Connect a mock signal handler to pre_page_move and post_page_move signals
134
+ pre_moved_handler = mock.MagicMock()
135
+ post_moved_handler = mock.MagicMock()
136
+
137
+ pre_page_move.connect(pre_moved_handler)
138
+ post_page_move.connect(post_moved_handler)
139
+
140
+ # Post to view to move page
141
+ try:
142
+ self.client.post(
143
+ reverse(
144
+ "wagtailadmin_pages:move_confirm",
145
+ args=(self.test_page_a.id, self.section_b.id),
146
+ )
147
+ )
148
+ finally:
149
+ # Disconnect mock handler to prevent cross-test pollution
150
+ pre_page_move.disconnect(pre_moved_handler)
151
+ post_page_move.disconnect(post_moved_handler)
152
+
153
+ # Check that the pre_page_move signal was fired
154
+ self.assertEqual(pre_moved_handler.call_count, 1)
155
+ self.assertTrue(
156
+ pre_moved_handler.called_with(
157
+ sender=self.test_page_a.specific_class,
158
+ instance=self.test_page_a,
159
+ parent_page_before=self.section_a,
160
+ parent_page_after=self.section_b,
161
+ url_path_before="/home/section-a/hello-world/",
162
+ url_path_after="/home/section-b/hello-world/",
163
+ )
164
+ )
165
+
166
+ # Check that the post_page_move signal was fired
167
+ self.assertEqual(post_moved_handler.call_count, 1)
168
+ self.assertTrue(
169
+ post_moved_handler.called_with(
170
+ sender=self.test_page_a.specific_class,
171
+ instance=self.test_page_a,
172
+ parent_page_before=self.section_a,
173
+ parent_page_after=self.section_b,
174
+ url_path_before="/home/section-a/hello-world/",
175
+ url_path_after="/home/section-b/hello-world/",
176
+ )
177
+ )
178
+
179
+ def test_before_move_page_hook(self):
180
+ def hook_func(request, page, destination):
181
+ self.assertIsInstance(request, HttpRequest)
182
+ self.assertIsInstance(page.specific, SimplePage)
183
+ self.assertIsInstance(destination.specific, SimplePage)
184
+
185
+ return HttpResponse("Overridden!")
186
+
187
+ with self.register_hook("before_move_page", hook_func):
188
+ response = self.client.get(
189
+ reverse(
190
+ "wagtailadmin_pages:move_confirm",
191
+ args=(self.test_page_a.id, self.section_b.id),
192
+ )
193
+ )
194
+
195
+ self.assertEqual(response.status_code, 200)
196
+ self.assertEqual(response.content, b"Overridden!")
197
+
198
+ def test_before_move_page_hook_post(self):
199
+ def hook_func(request, page, destination):
200
+ self.assertIsInstance(request, HttpRequest)
201
+ self.assertIsInstance(page.specific, SimplePage)
202
+ self.assertIsInstance(destination.specific, SimplePage)
203
+
204
+ return HttpResponse("Overridden!")
205
+
206
+ with self.register_hook("before_move_page", hook_func):
207
+ response = self.client.post(
208
+ reverse(
209
+ "wagtailadmin_pages:move_confirm",
210
+ args=(self.test_page_a.id, self.section_b.id),
211
+ )
212
+ )
213
+
214
+ self.assertEqual(response.status_code, 200)
215
+ self.assertEqual(response.content, b"Overridden!")
216
+
217
+ # page should not be moved
218
+ self.assertEqual(
219
+ Page.objects.get(id=self.test_page_a.id).get_parent().id, self.section_a.id
220
+ )
221
+
222
+ def test_after_move_page_hook(self):
223
+ def hook_func(request, page):
224
+ self.assertIsInstance(request, HttpRequest)
225
+ self.assertIsInstance(page.specific, SimplePage)
226
+
227
+ return HttpResponse("Overridden!")
228
+
229
+ with self.register_hook("after_move_page", hook_func):
230
+ response = self.client.post(
231
+ reverse(
232
+ "wagtailadmin_pages:move_confirm",
233
+ args=(self.test_page_a.id, self.section_b.id),
234
+ )
235
+ )
236
+
237
+ self.assertEqual(response.status_code, 200)
238
+ self.assertEqual(response.content, b"Overridden!")
239
+
240
+ # page should be moved
241
+ self.assertEqual(
242
+ Page.objects.get(id=self.test_page_a.id).get_parent().id, self.section_b.id
243
+ )
testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_page_locking.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.contrib.auth.models import Group, Permission
2
+ from django.test import TestCase
3
+ from django.urls import reverse
4
+ from django.utils import timezone
5
+ from django.utils.html import escape
6
+
7
+ from wagtail.models import Page
8
+ from wagtail.test.testapp.models import SimplePage
9
+ from wagtail.test.utils import WagtailTestUtils
10
+
11
+
12
+ class TestLocking(TestCase, WagtailTestUtils):
13
+ def setUp(self):
14
+ # Find root page
15
+ self.root_page = Page.objects.get(id=2)
16
+
17
+ # Login
18
+ self.user = self.login()
19
+
20
+ # Create a page and submit it for moderation
21
+ self.child_page = SimplePage(
22
+ title="Hello world!",
23
+ slug="hello-world",
24
+ content="hello",
25
+ live=False,
26
+ )
27
+ self.root_page.add_child(instance=self.child_page)
28
+
29
+ def test_lock_post(self):
30
+ response = self.client.post(
31
+ reverse("wagtailadmin_pages:lock", args=(self.child_page.id,))
32
+ )
33
+
34
+ # Check response
35
+ self.assertRedirects(
36
+ response, reverse("wagtailadmin_explore", args=(self.root_page.id,))
37
+ )
38
+
39
+ # Check that the page is locked
40
+ page = Page.objects.get(id=self.child_page.id)
41
+ self.assertTrue(page.locked)
42
+ self.assertEqual(page.locked_by, self.user)
43
+ self.assertIsNotNone(page.locked_at)
44
+
45
+ def test_lock_get(self):
46
+ response = self.client.get(
47
+ reverse("wagtailadmin_pages:lock", args=(self.child_page.id,))
48
+ )
49
+
50
+ # Check response
51
+ self.assertEqual(response.status_code, 405)
52
+
53
+ # Check that the page is still unlocked
54
+ page = Page.objects.get(id=self.child_page.id)
55
+ self.assertFalse(page.locked)
56
+ self.assertIsNone(page.locked_by)
57
+ self.assertIsNone(page.locked_at)
58
+
59
+ def test_lock_post_already_locked(self):
60
+ # Lock the page
61
+ self.child_page.locked = True
62
+ self.child_page.locked_by = self.user
63
+ self.child_page.locked_at = timezone.now()
64
+ self.child_page.save()
65
+
66
+ response = self.client.post(
67
+ reverse("wagtailadmin_pages:lock", args=(self.child_page.id,))
68
+ )
69
+
70
+ # Check response
71
+ self.assertRedirects(
72
+ response, reverse("wagtailadmin_explore", args=(self.root_page.id,))
73
+ )
74
+
75
+ # Check that the page is still locked
76
+ page = Page.objects.get(id=self.child_page.id)
77
+ self.assertTrue(page.locked)
78
+ self.assertEqual(page.locked_by, self.user)
79
+ self.assertIsNotNone(page.locked_at)
80
+
81
+ def test_lock_post_with_good_redirect(self):
82
+ response = self.client.post(
83
+ reverse("wagtailadmin_pages:lock", args=(self.child_page.id,)),
84
+ {"next": reverse("wagtailadmin_pages:edit", args=(self.child_page.id,))},
85
+ )
86
+
87
+ # Check response
88
+ self.assertRedirects(
89
+ response, reverse("wagtailadmin_pages:edit", args=(self.child_page.id,))
90
+ )
91
+
92
+ # Check that the page is locked
93
+ page = Page.objects.get(id=self.child_page.id)
94
+ self.assertTrue(page.locked)
95
+ self.assertEqual(page.locked_by, self.user)
96
+ self.assertIsNotNone(page.locked_at)
97
+
98
+ def test_lock_post_with_bad_redirect(self):
99
+ response = self.client.post(
100
+ reverse("wagtailadmin_pages:lock", args=(self.child_page.id,)),
101
+ {"next": "http://www.google.co.uk"},
102
+ )
103
+
104
+ # Check response
105
+ self.assertRedirects(
106
+ response, reverse("wagtailadmin_explore", args=(self.root_page.id,))
107
+ )
108
+
109
+ # Check that the page is locked
110
+ page = Page.objects.get(id=self.child_page.id)
111
+ self.assertTrue(page.locked)
112
+ self.assertEqual(page.locked_by, self.user)
113
+ self.assertIsNotNone(page.locked_at)
114
+
115
+ def test_lock_post_bad_page(self):
116
+ response = self.client.post(reverse("wagtailadmin_pages:lock", args=(9999,)))
117
+
118
+ # Check response
119
+ self.assertEqual(response.status_code, 404)
120
+
121
+ # Check that the page is still unlocked
122
+ page = Page.objects.get(id=self.child_page.id)
123
+ self.assertFalse(page.locked)
124
+ self.assertIsNone(page.locked_by)
125
+ self.assertIsNone(page.locked_at)
126
+
127
+ def test_lock_post_bad_permissions(self):
128
+ # Remove privileges from user
129
+ self.user.is_superuser = False
130
+ self.user.user_permissions.add(
131
+ Permission.objects.get(
132
+ content_type__app_label="wagtailadmin", codename="access_admin"
133
+ )
134
+ )
135
+ self.user.save()
136
+
137
+ response = self.client.post(
138
+ reverse("wagtailadmin_pages:lock", args=(self.child_page.id,))
139
+ )
140
+
141
+ # Check response
142
+ self.assertEqual(response.status_code, 302)
143
+
144
+ # Check that the page is still unlocked
145
+ page = Page.objects.get(id=self.child_page.id)
146
+ self.assertFalse(page.locked)
147
+ self.assertIsNone(page.locked_by)
148
+ self.assertIsNone(page.locked_at)
149
+
150
+ def test_locked_pages_dashboard_panel(self):
151
+ self.child_page.locked = True
152
+ self.child_page.locked_by = self.user
153
+ self.child_page.locked_at = timezone.now()
154
+ self.child_page.save()
155
+ response = self.client.get(reverse("wagtailadmin_home"))
156
+ self.assertContains(response, "Your locked pages")
157
+ # check that LockUnlockAction is present and passes a valid csrf token
158
+ self.assertRegex(
159
+ response.content.decode("utf-8"),
160
+ r"LockUnlockAction\(\'\w+\'\, \'\/admin\/'\)",
161
+ )
162
+
163
+ def test_unlock_post(self):
164
+ # Lock the page
165
+ self.child_page.locked = True
166
+ self.child_page.locked_by = self.user
167
+ self.child_page.locked_at = timezone.now()
168
+ self.child_page.save()
169
+
170
+ response = self.client.post(
171
+ reverse("wagtailadmin_pages:unlock", args=(self.child_page.id,))
172
+ )
173
+
174
+ # Check response
175
+ self.assertRedirects(
176
+ response, reverse("wagtailadmin_explore", args=(self.root_page.id,))
177
+ )
178
+
179
+ # Check that the page is unlocked
180
+ page = Page.objects.get(id=self.child_page.id)
181
+ self.assertFalse(page.locked)
182
+ self.assertIsNone(page.locked_by)
183
+ self.assertIsNone(page.locked_at)
184
+
185
+ def test_unlock_get(self):
186
+ # Lock the page
187
+ self.child_page.locked = True
188
+ self.child_page.locked_by = self.user
189
+ self.child_page.locked_at = timezone.now()
190
+ self.child_page.save()
191
+
192
+ response = self.client.get(
193
+ reverse("wagtailadmin_pages:unlock", args=(self.child_page.id,))
194
+ )
195
+
196
+ # Check response
197
+ self.assertEqual(response.status_code, 405)
198
+
199
+ # Check that the page is still locked
200
+ page = Page.objects.get(id=self.child_page.id)
201
+ self.assertTrue(page.locked)
202
+ self.assertEqual(page.locked_by, self.user)
203
+ self.assertIsNotNone(page.locked_at)
204
+
205
+ def test_unlock_post_already_unlocked(self):
206
+ response = self.client.post(
207
+ reverse("wagtailadmin_pages:unlock", args=(self.child_page.id,))
208
+ )
209
+
210
+ # Check response
211
+ self.assertRedirects(
212
+ response, reverse("wagtailadmin_explore", args=(self.root_page.id,))
213
+ )
214
+
215
+ # Check that the page is still unlocked
216
+ page = Page.objects.get(id=self.child_page.id)
217
+ self.assertFalse(page.locked)
218
+ self.assertIsNone(page.locked_by)
219
+ self.assertIsNone(page.locked_at)
220
+
221
+ def test_unlock_post_with_good_redirect(self):
222
+ # Lock the page
223
+ self.child_page.locked = True
224
+ self.child_page.locked_by = self.user
225
+ self.child_page.locked_at = timezone.now()
226
+ self.child_page.save()
227
+
228
+ response = self.client.post(
229
+ reverse("wagtailadmin_pages:unlock", args=(self.child_page.id,)),
230
+ {"next": reverse("wagtailadmin_pages:edit", args=(self.child_page.id,))},
231
+ follow=True,
232
+ )
233
+
234
+ # Check response
235
+ self.assertRedirects(
236
+ response, reverse("wagtailadmin_pages:edit", args=(self.child_page.id,))
237
+ )
238
+
239
+ # Should show unlocked message
240
+ self.assertContains(
241
+ response, escape("Page 'Hello world! (simple page)' is now unlocked.")
242
+ )
243
+
244
+ # Message shouldn't be wrapped in a tuple
245
+ self.assertNotContains(
246
+ response,
247
+ escape(("Page 'Hello world! (simple page)' is now unlocked.",)),
248
+ )
249
+
250
+ # Check that the page is unlocked
251
+ page = Page.objects.get(id=self.child_page.id)
252
+ self.assertFalse(page.locked)
253
+ self.assertIsNone(page.locked_by)
254
+ self.assertIsNone(page.locked_at)
255
+
256
+ def test_unlock_post_with_bad_redirect(self):
257
+ # Lock the page
258
+ self.child_page.locked = True
259
+ self.child_page.locked_by = self.user
260
+ self.child_page.locked_at = timezone.now()
261
+ self.child_page.save()
262
+
263
+ response = self.client.post(
264
+ reverse("wagtailadmin_pages:unlock", args=(self.child_page.id,)),
265
+ {"next": "http://www.google.co.uk"},
266
+ )
267
+
268
+ # Check response
269
+ self.assertRedirects(
270
+ response, reverse("wagtailadmin_explore", args=(self.root_page.id,))
271
+ )
272
+
273
+ # Check that the page is unlocked
274
+ page = Page.objects.get(id=self.child_page.id)
275
+ self.assertFalse(page.locked)
276
+ self.assertIsNone(page.locked_by)
277
+ self.assertIsNone(page.locked_at)
278
+
279
+ def test_unlock_post_bad_page(self):
280
+ # Lock the page
281
+ self.child_page.locked = True
282
+ self.child_page.locked_by = self.user
283
+ self.child_page.locked_at = timezone.now()
284
+ self.child_page.save()
285
+
286
+ response = self.client.post(reverse("wagtailadmin_pages:unlock", args=(9999,)))
287
+
288
+ # Check response
289
+ self.assertEqual(response.status_code, 404)
290
+
291
+ # Check that the page is still locked
292
+ page = Page.objects.get(id=self.child_page.id)
293
+ self.assertTrue(page.locked)
294
+ self.assertEqual(page.locked_by, self.user)
295
+ self.assertIsNotNone(page.locked_at)
296
+
297
+ def test_unlock_post_bad_permissions(self):
298
+ # Remove privileges from user
299
+ self.user.is_superuser = False
300
+ self.user.groups.add(Group.objects.get(name="Editors"))
301
+ self.user.save()
302
+
303
+ # Lock the page
304
+ self.child_page.locked = True
305
+ self.child_page.locked_at = timezone.now()
306
+ self.child_page.save()
307
+
308
+ response = self.client.post(
309
+ reverse("wagtailadmin_pages:unlock", args=(self.child_page.id,))
310
+ )
311
+
312
+ # Check response
313
+ self.assertEqual(response.status_code, 302)
314
+
315
+ # Check that the page is still locked
316
+ page = Page.objects.get(id=self.child_page.id)
317
+ self.assertTrue(page.locked)
318
+ self.assertIsNotNone(page.locked_at)
319
+
320
+ def test_unlock_post_own_page_with_bad_permissions(self):
321
+ # Unlike the previous test, the user can unlock pages that they have locked
322
+
323
+ # Remove privileges from user
324
+ self.user.is_superuser = False
325
+ self.user.groups.add(Group.objects.get(name="Editors"))
326
+ self.user.save()
327
+
328
+ # Lock the page
329
+ self.child_page.locked = True
330
+ self.child_page.locked_by = self.user
331
+ self.child_page.locked_at = timezone.now()
332
+ self.child_page.save()
333
+
334
+ response = self.client.post(
335
+ reverse("wagtailadmin_pages:unlock", args=(self.child_page.id,)),
336
+ {"next": reverse("wagtailadmin_pages:edit", args=(self.child_page.id,))},
337
+ )
338
+
339
+ # Check response
340
+ self.assertRedirects(
341
+ response, reverse("wagtailadmin_pages:edit", args=(self.child_page.id,))
342
+ )
343
+
344
+ # Check that the page is still locked
345
+ page = Page.objects.get(id=self.child_page.id)
346
+ self.assertFalse(page.locked)
347
+ self.assertIsNone(page.locked_by)
348
+ self.assertIsNone(page.locked_at)
testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_preview.py ADDED
@@ -0,0 +1,641 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ from functools import wraps
3
+
4
+ from django.test import TestCase
5
+ from django.urls import reverse
6
+ from django.utils import timezone
7
+ from freezegun import freeze_time
8
+
9
+ from wagtail.admin.views.pages.preview import PreviewOnEdit
10
+ from wagtail.models import Page
11
+ from wagtail.test.testapp.models import (
12
+ EventCategory,
13
+ MultiPreviewModesPage,
14
+ SimplePage,
15
+ StreamPage,
16
+ )
17
+ from wagtail.test.utils import WagtailTestUtils
18
+
19
+
20
+ class TestIssue2599(TestCase, WagtailTestUtils):
21
+ """
22
+ When previewing a page on creation, we need to assign it a path value consistent with its
23
+ (future) position in the tree. The naive way of doing this is to give it an index number
24
+ one more than numchild - however, index numbers are not reassigned on page deletion, so
25
+ this can result in a path that collides with an existing page (which is invalid).
26
+ """
27
+
28
+ def test_issue_2599(self):
29
+ homepage = Page.objects.get(id=2)
30
+
31
+ child1 = Page(title="child1")
32
+ homepage.add_child(instance=child1)
33
+ child2 = Page(title="child2")
34
+ homepage.add_child(instance=child2)
35
+
36
+ child1.delete()
37
+
38
+ self.login()
39
+ post_data = {
40
+ "title": "New page!",
41
+ "content": "Some content",
42
+ "slug": "hello-world",
43
+ "action-submit": "Submit",
44
+ }
45
+ preview_url = reverse(
46
+ "wagtailadmin_pages:preview_on_add",
47
+ args=("tests", "simplepage", homepage.id),
48
+ )
49
+ response = self.client.post(preview_url, post_data)
50
+
51
+ # Check the JSON response
52
+ self.assertEqual(response.status_code, 200)
53
+ self.assertJSONEqual(
54
+ response.content.decode(),
55
+ {"is_valid": True, "is_available": True},
56
+ )
57
+
58
+ response = self.client.get(preview_url)
59
+
60
+ # Check the HTML response
61
+ self.assertEqual(response.status_code, 200)
62
+ self.assertTemplateUsed(response, "tests/simple_page.html")
63
+ self.assertContains(response, "New page!")
64
+
65
+ # Check that the treebeard attributes were set correctly on the page object
66
+ self.assertEqual(response.context["self"].depth, homepage.depth + 1)
67
+ self.assertTrue(response.context["self"].path.startswith(homepage.path))
68
+ self.assertEqual(response.context["self"].get_parent(), homepage)
69
+
70
+
71
+ def clear_edit_handler(page_cls):
72
+ def decorator(fn):
73
+ @wraps(fn)
74
+ def decorated(*args, **kwargs):
75
+ # Clear any old panel definitions generated
76
+ page_cls.get_edit_handler.cache_clear()
77
+ try:
78
+ fn(*args, **kwargs)
79
+ finally:
80
+ # Clear the bad panel definition generated just now
81
+ page_cls.get_edit_handler.cache_clear()
82
+
83
+ return decorated
84
+
85
+ return decorator
86
+
87
+
88
+ class TestPreview(TestCase, WagtailTestUtils):
89
+ fixtures = ["test.json"]
90
+
91
+ def setUp(self):
92
+ self.meetings_category = EventCategory.objects.create(name="Meetings")
93
+ self.parties_category = EventCategory.objects.create(name="Parties")
94
+ self.holidays_category = EventCategory.objects.create(name="Holidays")
95
+
96
+ self.home_page = Page.objects.get(url_path="/home/")
97
+ self.event_page = Page.objects.get(url_path="/home/events/christmas/")
98
+
99
+ self.user = self.login()
100
+
101
+ self.post_data = {
102
+ "title": "Beach party",
103
+ "slug": "beach-party",
104
+ "body": """{"entityMap": {},"blocks": [
105
+ {"inlineStyleRanges": [], "text": "party on wayne", "depth": 0, "type": "unstyled", "key": "00000", "entityRanges": []}
106
+ ]}""",
107
+ "date_from": "2017-08-01",
108
+ "audience": "public",
109
+ "location": "the beach",
110
+ "cost": "six squid",
111
+ "carousel_items-TOTAL_FORMS": 0,
112
+ "carousel_items-INITIAL_FORMS": 0,
113
+ "carousel_items-MIN_NUM_FORMS": 0,
114
+ "carousel_items-MAX_NUM_FORMS": 0,
115
+ "speakers-TOTAL_FORMS": 0,
116
+ "speakers-INITIAL_FORMS": 0,
117
+ "speakers-MIN_NUM_FORMS": 0,
118
+ "speakers-MAX_NUM_FORMS": 0,
119
+ "related_links-TOTAL_FORMS": 0,
120
+ "related_links-INITIAL_FORMS": 0,
121
+ "related_links-MIN_NUM_FORMS": 0,
122
+ "related_links-MAX_NUM_FORMS": 0,
123
+ "head_counts-TOTAL_FORMS": 0,
124
+ "head_counts-INITIAL_FORMS": 0,
125
+ "head_counts-MIN_NUM_FORMS": 0,
126
+ "head_counts-MAX_NUM_FORMS": 0,
127
+ "categories": [self.parties_category.id, self.holidays_category.id],
128
+ "comments-TOTAL_FORMS": 0,
129
+ "comments-INITIAL_FORMS": 0,
130
+ "comments-MIN_NUM_FORMS": 0,
131
+ "comments-MAX_NUM_FORMS": 1000,
132
+ }
133
+
134
+ def test_preview_on_create_with_no_session_data(self):
135
+ preview_url = reverse(
136
+ "wagtailadmin_pages:preview_on_add",
137
+ args=("tests", "eventpage", self.home_page.id),
138
+ )
139
+
140
+ preview_session_key = "wagtail-preview-tests-eventpage-{}".format(
141
+ self.home_page.id
142
+ )
143
+ self.assertNotIn(preview_session_key, self.client.session)
144
+
145
+ response = self.client.get(preview_url)
146
+
147
+ # The preview should be unavailable
148
+ self.assertEqual(response.status_code, 200)
149
+ self.assertTemplateUsed(response, "wagtailadmin/generic/preview_error.html")
150
+ self.assertContains(
151
+ response,
152
+ "<title>Preview not available - Wagtail</title>",
153
+ html=True,
154
+ )
155
+ self.assertContains(
156
+ response,
157
+ '<h1 class="preview-error__title">Preview not available</h1>',
158
+ html=True,
159
+ )
160
+
161
+ def test_preview_on_create_with_invalid_data(self):
162
+ preview_url = reverse(
163
+ "wagtailadmin_pages:preview_on_add",
164
+ args=("tests", "eventpage", self.home_page.id),
165
+ )
166
+
167
+ preview_session_key = "wagtail-preview-tests-eventpage-{}".format(
168
+ self.home_page.id
169
+ )
170
+ self.assertNotIn(preview_session_key, self.client.session)
171
+
172
+ response = self.client.post(preview_url, {**self.post_data, "title": ""})
173
+
174
+ # Check the JSON response
175
+ self.assertEqual(response.status_code, 200)
176
+ self.assertJSONEqual(
177
+ response.content.decode(),
178
+ {"is_valid": False, "is_available": False},
179
+ )
180
+
181
+ # The invalid data should not be saved in the session
182
+ self.assertNotIn(preview_session_key, self.client.session)
183
+
184
+ response = self.client.get(preview_url)
185
+
186
+ # The preview should still be unavailable
187
+ self.assertEqual(response.status_code, 200)
188
+ self.assertTemplateUsed(response, "wagtailadmin/generic/preview_error.html")
189
+ self.assertContains(
190
+ response,
191
+ "<title>Preview not available - Wagtail</title>",
192
+ html=True,
193
+ )
194
+ self.assertContains(
195
+ response,
196
+ '<h1 class="preview-error__title">Preview not available</h1>',
197
+ html=True,
198
+ )
199
+
200
+ def test_preview_on_create_with_m2m_field(self):
201
+ preview_url = reverse(
202
+ "wagtailadmin_pages:preview_on_add",
203
+ args=("tests", "eventpage", self.home_page.id),
204
+ )
205
+ response = self.client.post(preview_url, self.post_data)
206
+
207
+ # Check the JSON response
208
+ self.assertEqual(response.status_code, 200)
209
+ self.assertJSONEqual(
210
+ response.content.decode(),
211
+ {"is_valid": True, "is_available": True},
212
+ )
213
+
214
+ # Check the user can refresh the preview
215
+ preview_session_key = "wagtail-preview-tests-eventpage-{}".format(
216
+ self.home_page.id
217
+ )
218
+ self.assertIn(preview_session_key, self.client.session)
219
+
220
+ response = self.client.get(preview_url)
221
+
222
+ # Check the HTML response
223
+ self.assertEqual(response.status_code, 200)
224
+ self.assertTemplateUsed(response, "tests/event_page.html")
225
+ self.assertContains(response, "Beach party")
226
+ self.assertContains(response, "<li>Parties</li>")
227
+ self.assertContains(response, "<li>Holidays</li>")
228
+
229
+ def test_preview_on_edit_with_m2m_field(self):
230
+ preview_url = reverse(
231
+ "wagtailadmin_pages:preview_on_edit", args=(self.event_page.id,)
232
+ )
233
+ response = self.client.post(preview_url, self.post_data)
234
+
235
+ # Check the JSON response
236
+ self.assertEqual(response.status_code, 200)
237
+ self.assertJSONEqual(
238
+ response.content.decode(),
239
+ {"is_valid": True, "is_available": True},
240
+ )
241
+
242
+ # Check the user can refresh the preview
243
+ preview_session_key = "wagtail-preview-{}".format(self.event_page.id)
244
+ self.assertIn(preview_session_key, self.client.session)
245
+
246
+ response = self.client.get(preview_url)
247
+
248
+ # Check the HTML response
249
+ self.assertEqual(response.status_code, 200)
250
+ self.assertTemplateUsed(response, "tests/event_page.html")
251
+ self.assertContains(response, "Beach party")
252
+ self.assertContains(response, "<li>Parties</li>")
253
+ self.assertContains(response, "<li>Holidays</li>")
254
+
255
+ def test_preview_on_edit_with_valid_then_invalid_data(self):
256
+ preview_url = reverse(
257
+ "wagtailadmin_pages:preview_on_edit", args=(self.event_page.id,)
258
+ )
259
+ response = self.client.post(preview_url, self.post_data)
260
+
261
+ # Check the JSON response
262
+ self.assertEqual(response.status_code, 200)
263
+ self.assertJSONEqual(
264
+ response.content.decode(),
265
+ {"is_valid": True, "is_available": True},
266
+ )
267
+
268
+ # Send an invalid update request
269
+ response = self.client.post(preview_url, {**self.post_data, "title": ""})
270
+ self.assertEqual(response.status_code, 200)
271
+ self.assertJSONEqual(
272
+ response.content.decode(),
273
+ {"is_valid": False, "is_available": True},
274
+ )
275
+
276
+ # Check the user can still see the preview with the last valid data
277
+ preview_session_key = "wagtail-preview-{}".format(self.event_page.id)
278
+ self.assertIn(preview_session_key, self.client.session)
279
+
280
+ response = self.client.get(preview_url)
281
+
282
+ # Check the HTML response
283
+ self.assertEqual(response.status_code, 200)
284
+ self.assertTemplateUsed(response, "tests/event_page.html")
285
+ self.assertContains(response, "Beach party")
286
+ self.assertContains(response, "<li>Parties</li>")
287
+ self.assertContains(response, "<li>Holidays</li>")
288
+
289
+ def test_preview_on_edit_expiry(self):
290
+ initial_datetime = timezone.now()
291
+ expiry_datetime = initial_datetime + datetime.timedelta(
292
+ seconds=PreviewOnEdit.preview_expiration_timeout + 1
293
+ )
294
+
295
+ with freeze_time(initial_datetime) as frozen_datetime:
296
+ preview_url = reverse(
297
+ "wagtailadmin_pages:preview_on_edit", args=(self.event_page.id,)
298
+ )
299
+ response = self.client.post(preview_url, self.post_data)
300
+
301
+ # Check the JSON response
302
+ self.assertEqual(response.status_code, 200)
303
+
304
+ response = self.client.get(preview_url)
305
+
306
+ # Check the HTML response
307
+ self.assertEqual(response.status_code, 200)
308
+
309
+ frozen_datetime.move_to(expiry_datetime)
310
+
311
+ preview_url = reverse(
312
+ "wagtailadmin_pages:preview_on_edit", args=(self.home_page.id,)
313
+ )
314
+ response = self.client.post(preview_url, self.post_data)
315
+ self.assertEqual(response.status_code, 200)
316
+ response = self.client.get(preview_url)
317
+ self.assertEqual(response.status_code, 200)
318
+
319
+ def test_preview_on_create_clear_preview_data(self):
320
+ preview_session_key = "wagtail-preview-tests-eventpage-{}".format(
321
+ self.home_page.id
322
+ )
323
+
324
+ # Set a fake preview session data for the page
325
+ self.client.session[preview_session_key] = "test data"
326
+
327
+ preview_url = reverse(
328
+ "wagtailadmin_pages:preview_on_add",
329
+ args=("tests", "eventpage", self.home_page.id),
330
+ )
331
+ response = self.client.delete(preview_url)
332
+ self.assertEqual(response.status_code, 200)
333
+ self.assertJSONEqual(
334
+ response.content.decode(),
335
+ {"success": True},
336
+ )
337
+
338
+ # The data should no longer exist in the session
339
+ self.assertNotIn(preview_session_key, self.client.session)
340
+
341
+ response = self.client.get(preview_url)
342
+
343
+ # The preview should be unavailable
344
+ self.assertEqual(response.status_code, 200)
345
+ self.assertTemplateUsed(response, "wagtailadmin/generic/preview_error.html")
346
+ self.assertContains(
347
+ response,
348
+ "<title>Preview not available - Wagtail</title>",
349
+ html=True,
350
+ )
351
+ self.assertContains(
352
+ response,
353
+ '<h1 class="preview-error__title">Preview not available</h1>',
354
+ html=True,
355
+ )
356
+
357
+ def test_preview_on_edit_clear_preview_data(self):
358
+ preview_session_key = "wagtail-preview-{}".format(self.event_page.id)
359
+
360
+ # Set a fake preview session data for the page
361
+ self.client.session[preview_session_key] = "test data"
362
+
363
+ preview_url = reverse(
364
+ "wagtailadmin_pages:preview_on_edit", args=(self.event_page.id,)
365
+ )
366
+ response = self.client.delete(preview_url)
367
+ self.assertEqual(response.status_code, 200)
368
+ self.assertJSONEqual(
369
+ response.content.decode(),
370
+ {"success": True},
371
+ )
372
+
373
+ # The data should no longer exist in the session
374
+ self.assertNotIn(preview_session_key, self.client.session)
375
+
376
+ response = self.client.get(preview_url)
377
+
378
+ # The preview should be unavailable
379
+ self.assertEqual(response.status_code, 200)
380
+ self.assertTemplateUsed(response, "wagtailadmin/generic/preview_error.html")
381
+ self.assertContains(
382
+ response,
383
+ "<title>Preview not available - Wagtail</title>",
384
+ html=True,
385
+ )
386
+ self.assertContains(
387
+ response,
388
+ '<h1 class="preview-error__title">Preview not available</h1>',
389
+ html=True,
390
+ )
391
+
392
+ def test_preview_modes(self):
393
+ preview_url = reverse(
394
+ "wagtailadmin_pages:preview_on_add",
395
+ args=("tests", "multipreviewmodespage", self.home_page.id),
396
+ )
397
+
398
+ response = self.client.post(preview_url, data={"title": "Test", "slug": "test"})
399
+ self.assertEqual(response.status_code, 200)
400
+ self.assertJSONEqual(
401
+ response.content.decode(),
402
+ {"is_valid": True, "is_available": True},
403
+ )
404
+
405
+ cases = [
406
+ ("", "tests/simple_page_alt.html"),
407
+ ("?mode=original", "tests/simple_page.html"),
408
+ ("?mode=alt%231", "tests/simple_page_alt.html"),
409
+ ]
410
+
411
+ for params, template in cases:
412
+ with self.subTest(params=params, template=template):
413
+ response = self.client.get(preview_url + params)
414
+ self.assertEqual(response.status_code, 200)
415
+ self.assertTemplateUsed(response, template)
416
+
417
+
418
+ class TestEnablePreview(TestCase, WagtailTestUtils):
419
+ def setUp(self):
420
+ self.root_page = Page.objects.get(id=2)
421
+ self.user = self.login()
422
+
423
+ # SimplePage only has one preview mode
424
+ self.single = SimplePage(title="Single preview mode", content="foo")
425
+ # MultiPreviewModesPage has two preview modes
426
+ self.multiple = MultiPreviewModesPage(title="Multiple preview modes")
427
+
428
+ self.root_page.add_child(instance=self.single)
429
+ self.root_page.add_child(instance=self.multiple)
430
+
431
+ def get_url_on_add(self, name, page):
432
+ model_name = type(page)._meta.model_name
433
+ return reverse(
434
+ f"wagtailadmin_pages:{name}",
435
+ args=("tests", model_name, self.root_page.id),
436
+ )
437
+
438
+ def get_url_on_edit(self, name, page):
439
+ return reverse(f"wagtailadmin_pages:{name}", args=(page.id,))
440
+
441
+ def test_show_preview_panel_on_create_with_single_mode(self):
442
+ create_url = self.get_url_on_add("add", self.single)
443
+ preview_url = self.get_url_on_add("preview_on_add", self.single)
444
+ iframe_url = preview_url + "?in_preview_panel=true&mode="
445
+ response = self.client.get(create_url)
446
+
447
+ self.assertEqual(response.status_code, 200)
448
+
449
+ # Should show the preview panel
450
+ self.assertContains(response, 'data-side-panel-toggle="preview"')
451
+ self.assertContains(response, 'data-side-panel="preview"')
452
+ self.assertContains(response, 'data-action="%s"' % preview_url)
453
+
454
+ # Should show the iframe
455
+ self.assertContains(
456
+ response,
457
+ f'<iframe title="Preview" class="preview-panel__iframe" data-preview-iframe src="{iframe_url}" aria-describedby="preview-panel-error-banner">',
458
+ )
459
+
460
+ # Should not show the preview mode selection
461
+ self.assertNotContains(
462
+ response,
463
+ '<select id="id_preview_mode" name="preview_mode" class="preview-panel__mode-select" data-preview-mode-select>',
464
+ )
465
+
466
+ def test_show_preview_panel_on_create_with_multiple_modes(self):
467
+ create_url = self.get_url_on_add("add", self.multiple)
468
+ preview_url = self.get_url_on_add("preview_on_add", self.multiple)
469
+ iframe_url = preview_url + "?in_preview_panel=true&mode=alt%231"
470
+ response = self.client.get(create_url)
471
+
472
+ self.assertEqual(response.status_code, 200)
473
+
474
+ # Should show the preview panel
475
+ self.assertContains(response, 'data-side-panel-toggle="preview"')
476
+ self.assertContains(response, 'data-side-panel="preview"')
477
+ self.assertContains(response, 'data-action="%s"' % preview_url)
478
+
479
+ # Should show the iframe with the default mode set and correctly quoted
480
+ self.assertContains(
481
+ response,
482
+ f'<iframe title="Preview" class="preview-panel__iframe" data-preview-iframe src="{iframe_url}" aria-describedby="preview-panel-error-banner">',
483
+ )
484
+
485
+ # should show the preview mode selection
486
+ self.assertContains(
487
+ response,
488
+ '<select id="id_preview_mode" name="preview_mode" class="preview-panel__mode-select" data-preview-mode-select>',
489
+ )
490
+ self.assertContains(response, '<option value="original">Original</option>')
491
+
492
+ # Should respect the default_preview_mode
493
+ self.assertContains(
494
+ response, '<option value="alt#1" selected>Alternate</option>'
495
+ )
496
+
497
+ def test_show_preview_panel_on_edit_with_single_mode(self):
498
+ edit_url = self.get_url_on_edit("edit", self.single)
499
+ preview_url = self.get_url_on_edit("preview_on_edit", self.single)
500
+ iframe_url = preview_url + "?in_preview_panel=true&mode="
501
+ response = self.client.get(edit_url)
502
+
503
+ self.assertEqual(response.status_code, 200)
504
+
505
+ # Should show the preview panel
506
+ self.assertContains(response, 'data-side-panel-toggle="preview"')
507
+ self.assertContains(response, 'data-side-panel="preview"')
508
+ self.assertContains(response, 'data-action="%s"' % preview_url)
509
+
510
+ # Should show the iframe
511
+ self.assertContains(
512
+ response,
513
+ f'<iframe title="Preview" class="preview-panel__iframe" data-preview-iframe src="{iframe_url}" aria-describedby="preview-panel-error-banner">',
514
+ )
515
+
516
+ # Should not show the preview mode selection
517
+ self.assertNotContains(
518
+ response,
519
+ '<select id="id_preview_mode" name="preview_mode" class="preview-panel__mode-select" data-preview-mode-select>',
520
+ )
521
+
522
+ def test_show_preview_panel_on_edit_with_multiple_modes(self):
523
+ edit_url = self.get_url_on_edit("edit", self.multiple)
524
+ preview_url = self.get_url_on_edit("preview_on_edit", self.multiple)
525
+ iframe_url = preview_url + "?in_preview_panel=true&mode=alt%231"
526
+ response = self.client.get(edit_url)
527
+
528
+ self.assertEqual(response.status_code, 200)
529
+
530
+ # Should show the preview panel
531
+ self.assertContains(response, 'data-side-panel-toggle="preview"')
532
+ self.assertContains(response, 'data-side-panel="preview"')
533
+ self.assertContains(response, 'data-action="%s"' % preview_url)
534
+
535
+ # Should show the iframe with the default mode set and correctly quoted
536
+ self.assertContains(
537
+ response,
538
+ f'<iframe title="Preview" class="preview-panel__iframe" data-preview-iframe src="{iframe_url}" aria-describedby="preview-panel-error-banner">',
539
+ )
540
+
541
+ # should show the preview mode selection
542
+ self.assertContains(
543
+ response,
544
+ '<select id="id_preview_mode" name="preview_mode" class="preview-panel__mode-select" data-preview-mode-select>',
545
+ )
546
+ self.assertContains(response, '<option value="original">Original</option>')
547
+
548
+ # Should respect the default_preview_mode
549
+ self.assertContains(
550
+ response, '<option value="alt#1" selected>Alternate</option>'
551
+ )
552
+
553
+ def test_show_preview_on_revisions_list(self):
554
+ latest_revision = self.single.save_revision(log_action=True)
555
+ history_url = self.get_url_on_edit("history", self.single)
556
+ preview_url = reverse(
557
+ "wagtailadmin_pages:revisions_view",
558
+ args=(self.single.id, latest_revision.id),
559
+ )
560
+
561
+ response = self.client.get(history_url)
562
+ self.assertContains(response, "Preview")
563
+ self.assertContains(response, preview_url)
564
+
565
+
566
+ class TestDisablePreviewButton(TestCase, WagtailTestUtils):
567
+ """
568
+ Test that preview button can be disabled by setting preview_modes to an empty list
569
+ """
570
+
571
+ def setUp(self):
572
+ # Find root page
573
+ self.root_page = Page.objects.get(id=2)
574
+
575
+ # Login
576
+ self.user = self.login()
577
+
578
+ def test_disable_preview_on_create(self):
579
+ # StreamPage has preview_modes = []
580
+ response = self.client.get(
581
+ reverse(
582
+ "wagtailadmin_pages:add",
583
+ args=("tests", "streampage", self.root_page.id),
584
+ )
585
+ )
586
+ self.assertEqual(response.status_code, 200)
587
+
588
+ preview_url = reverse(
589
+ "wagtailadmin_pages:preview_on_add",
590
+ args=("tests", "streampage", self.root_page.id),
591
+ )
592
+ self.assertNotContains(response, 'data-side-panel-toggle="preview"')
593
+ self.assertNotContains(response, 'data-side-panel="preview"')
594
+ self.assertNotContains(response, 'data-action="%s"' % preview_url)
595
+
596
+ def test_disable_preview_on_edit(self):
597
+ stream_page = StreamPage(title="stream page", body=[("text", "hello")])
598
+ self.root_page.add_child(instance=stream_page)
599
+
600
+ # StreamPage has preview_modes = []
601
+ response = self.client.get(
602
+ reverse("wagtailadmin_pages:edit", args=(stream_page.id,))
603
+ )
604
+ self.assertEqual(response.status_code, 200)
605
+
606
+ preview_url = reverse(
607
+ "wagtailadmin_pages:preview_on_edit", args=(stream_page.id,)
608
+ )
609
+ self.assertNotContains(response, 'data-side-panel-toggle="preview"')
610
+ self.assertNotContains(response, 'data-side-panel="preview"')
611
+ self.assertNotContains(response, 'data-action="%s"' % preview_url)
612
+
613
+ def test_disable_preview_on_revisions_list(self):
614
+ stream_page = StreamPage(title="stream page", body=[("text", "hello")])
615
+ self.root_page.add_child(instance=stream_page)
616
+ latest_revision = stream_page.save_revision(log_action=True)
617
+
618
+ # StreamPage has preview_modes = []
619
+ response = self.client.get(
620
+ reverse("wagtailadmin_pages:history", args=(stream_page.id,))
621
+ )
622
+ preview_url = reverse(
623
+ "wagtailadmin_pages:revisions_view",
624
+ args=(stream_page.id, latest_revision.id),
625
+ )
626
+ self.assertNotContains(response, "Preview")
627
+ self.assertNotContains(response, preview_url)
628
+
629
+ def disable_preview_in_moderation_list(self):
630
+ stream_page = StreamPage(title="stream page", body=[("text", "hello")])
631
+ self.root_page.add_child(instance=stream_page)
632
+ latest_revision = stream_page.save_revision(
633
+ user=self.user, submitted_for_moderation=True
634
+ )
635
+
636
+ response = self.client.get(reverse("wagtailadmin_home"))
637
+ preview_url = reverse(
638
+ "wagtailadmin_pages:preview_for_moderation", args=(latest_revision.id,)
639
+ )
640
+ self.assertNotContains(response, '<li class="preview">')
641
+ self.assertNotContains(response, 'data-action="%s"' % preview_url)
testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_reorder_page.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.test import TestCase
2
+ from django.urls import reverse
3
+
4
+ from wagtail.models import Page
5
+ from wagtail.test.testapp.models import BusinessChild, BusinessIndex, SimplePage
6
+ from wagtail.test.utils import WagtailTestUtils
7
+
8
+
9
+ class TestPageReorder(TestCase, WagtailTestUtils):
10
+ fixtures = ["test.json"]
11
+
12
+ def __init__(self, methodName: str = ...) -> None:
13
+ super().__init__(methodName)
14
+
15
+ def setUp(self):
16
+ # Find root page
17
+ self.root_page = Page.objects.get(id=2)
18
+
19
+ # root
20
+ # |- simple_index (SimplePage)
21
+ # | |- simple_child_1 (SimplePage)
22
+ # | |- simple_child_2 (SimplePage)
23
+ # | |- simple_child_3 (SimplePage)
24
+
25
+ self.index_page = SimplePage(title="Simple", slug="simple", content="hello")
26
+ self.root_page.add_child(instance=self.index_page)
27
+
28
+ self.child_1 = SimplePage(
29
+ title="Child 1 of SimplePage", slug="child-1", content="hello"
30
+ )
31
+ self.index_page.add_child(instance=self.child_1)
32
+ self.child_2 = SimplePage(
33
+ title="Child 2 of SimplePage", slug="child-2", content="hello"
34
+ )
35
+ self.index_page.add_child(instance=self.child_2)
36
+ self.child_3 = SimplePage(
37
+ title="Child 3 of SimplePage", slug="child-3", content="hello"
38
+ )
39
+ self.index_page.add_child(instance=self.child_3)
40
+
41
+ # Login
42
+ self.user = self.login()
43
+
44
+ def test_page_set_page_position_get_request_with_simple_page(self):
45
+ """
46
+ Test that GET requests to set_page_position view don't alter the page order.
47
+ """
48
+ response = self.client.get(
49
+ reverse("wagtailadmin_pages:set_page_position", args=(self.child_1.id,))
50
+ )
51
+ self.assertEqual(response.status_code, 200)
52
+
53
+ # Ensure page order does not change:
54
+ child_slugs = self.index_page.get_children().values_list("slug", flat=True)
55
+ self.assertListEqual(list(child_slugs), ["child-1", "child-2", "child-3"])
56
+
57
+ def test_page_set_page_position_without_position_argument_moves_it_to_the_end(self):
58
+ response = self.client.post(
59
+ reverse("wagtailadmin_pages:set_page_position", args=(self.child_1.id,))
60
+ )
61
+ self.assertEqual(response.status_code, 200)
62
+
63
+ # check if child_1 is the last child page:
64
+ child_slugs = self.index_page.get_children().values_list("slug", flat=True)
65
+ self.assertListEqual(list(child_slugs), ["child-2", "child-3", "child-1"])
66
+
67
+ def test_page_move_page_position_up(self):
68
+ """Moves child 3 to the first position."""
69
+ response = self.client.post(
70
+ reverse("wagtailadmin_pages:set_page_position", args=(self.child_3.id,))
71
+ + "?position=0"
72
+ )
73
+ self.assertEqual(response.status_code, 200)
74
+ # check if child_3 is the first child page:
75
+ child_slugs = self.index_page.get_children().values_list("slug", flat=True)
76
+ self.assertListEqual(list(child_slugs), ["child-3", "child-1", "child-2"])
77
+
78
+ def test_page_move_page_position_down(self):
79
+ """
80
+ Moves child 3 to the first position."""
81
+ response = self.client.post(
82
+ reverse("wagtailadmin_pages:set_page_position", args=(self.child_1.id,))
83
+ + "?position=1"
84
+ )
85
+ self.assertEqual(response.status_code, 200)
86
+ # check if child_1 is the second child page:
87
+ child_slugs = self.index_page.get_children().values_list("slug", flat=True)
88
+ self.assertListEqual(list(child_slugs), ["child-2", "child-1", "child-3"])
89
+
90
+ def test_page_move_page_position_to_the_same_position(self):
91
+ """
92
+ Moves child 3 to the first position."""
93
+ response = self.client.post(
94
+ reverse("wagtailadmin_pages:set_page_position", args=(self.child_1.id,))
95
+ + "?position=0"
96
+ )
97
+ self.assertEqual(response.status_code, 200)
98
+ # Ensure page order does not change:
99
+ child_slugs = self.index_page.get_children().values_list("slug", flat=True)
100
+ self.assertListEqual(list(child_slugs), ["child-1", "child-2", "child-3"])
101
+
102
+ def test_page_set_page_position_with_invalid_target_position(self):
103
+ response = self.client.post(
104
+ reverse("wagtailadmin_pages:set_page_position", args=(self.child_3.id,))
105
+ + "?position=99"
106
+ )
107
+ self.assertEqual(response.status_code, 200)
108
+
109
+ # Ensure page order does not change:
110
+ child_slugs = self.index_page.get_children().values_list("slug", flat=True)
111
+ self.assertListEqual(list(child_slugs), ["child-1", "child-2", "child-3"])
112
+
113
+
114
+ class TestPageReorderWithParentPageRestrictions(TestPageReorder):
115
+ """
116
+ This testCase is the same as the TestPageReorder class above, but with a different
117
+ page type: BusinessChild has a parent_page_types restriction.
118
+ This ensures that this restriction doesn't affect the ability to reorder pages.
119
+ """
120
+
121
+ def setUp(self):
122
+ # Find root page
123
+ self.root_page = Page.objects.get(id=2)
124
+
125
+ # root
126
+ # |- index_page (BusinessIndex)
127
+ # | |- child_1 (BusinessChild)
128
+ # | |- child_2 (BusinessChild)
129
+ # | |- child_3 (BusinessChild)
130
+
131
+ self.index_page = BusinessIndex(title="Simple", slug="simple")
132
+ self.root_page.add_child(instance=self.index_page)
133
+
134
+ self.child_1 = BusinessChild(title="Child 1 of BusinessIndex", slug="child-1")
135
+ self.index_page.add_child(instance=self.child_1)
136
+ self.child_2 = BusinessChild(title="Child 2 of BusinessIndex", slug="child-2")
137
+ self.index_page.add_child(instance=self.child_2)
138
+ self.child_3 = BusinessChild(title="Child 3 of BusinessIndex", slug="child-3")
139
+ self.index_page.add_child(instance=self.child_3)
140
+
141
+ # Login
142
+ self.user = self.login()
testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_revisions.py ADDED
@@ -0,0 +1,631 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.conf import settings
2
+ from django.contrib.auth import get_user_model
3
+ from django.contrib.auth.models import Group, Permission
4
+ from django.test import TestCase
5
+ from django.urls import reverse
6
+ from freezegun import freeze_time
7
+
8
+ from wagtail.admin.staticfiles import versioned_static
9
+ from wagtail.models import Page
10
+ from wagtail.test.testapp.models import (
11
+ DefaultStreamPage,
12
+ EventPage,
13
+ FormClassAdditionalFieldPage,
14
+ SecretPage,
15
+ )
16
+ from wagtail.test.utils import WagtailTestUtils
17
+ from wagtail.test.utils.timestamps import local_datetime
18
+
19
+
20
+ class TestRevisions(TestCase, WagtailTestUtils):
21
+ fixtures = ["test.json"]
22
+
23
+ def setUp(self):
24
+ self.christmas_event = EventPage.objects.get(url_path="/home/events/christmas/")
25
+ self.christmas_event.title = "Last Christmas"
26
+ self.christmas_event.date_from = "2013-12-25"
27
+ self.christmas_event.body = (
28
+ "<p>Last Christmas I gave you my heart, "
29
+ "but the very next day you gave it away</p>"
30
+ )
31
+ self.last_christmas_revision = self.christmas_event.save_revision()
32
+ self.last_christmas_revision.created_at = local_datetime(2013, 12, 25)
33
+ self.last_christmas_revision.save()
34
+
35
+ self.christmas_event.title = "This Christmas"
36
+ self.christmas_event.date_from = "2014-12-25"
37
+ self.christmas_event.body = (
38
+ "<p>This year, to save me from tears, "
39
+ "I'll give it to someone special</p>"
40
+ )
41
+ self.this_christmas_revision = self.christmas_event.save_revision()
42
+ self.this_christmas_revision.created_at = local_datetime(2014, 12, 25)
43
+ self.this_christmas_revision.save()
44
+
45
+ self.login()
46
+
47
+ def test_get_revisions_index(self):
48
+ response = self.client.get(
49
+ reverse(
50
+ "wagtailadmin_pages:revisions_index", args=(self.christmas_event.id,)
51
+ )
52
+ )
53
+ history_url = reverse(
54
+ "wagtailadmin_pages:history", args=(self.christmas_event.id,)
55
+ )
56
+ self.assertRedirects(response, history_url)
57
+
58
+ def request_preview_revision(self):
59
+ last_christmas_preview_url = reverse(
60
+ "wagtailadmin_pages:revisions_view",
61
+ args=(self.christmas_event.id, self.last_christmas_revision.id),
62
+ )
63
+ return self.client.get(last_christmas_preview_url)
64
+
65
+ def test_preview_revision(self):
66
+ response = self.request_preview_revision()
67
+
68
+ self.assertEqual(response.status_code, 200)
69
+ self.assertContains(response, "Last Christmas I gave you my heart")
70
+
71
+ def test_preview_revision_with_no_page_permissions_redirects_to_admin(self):
72
+ admin_only_user = self.create_user(
73
+ username="admin_only", email="admin_only@email.com", password="password"
74
+ )
75
+ admin_only_user.user_permissions.add(
76
+ Permission.objects.get_by_natural_key(
77
+ codename="access_admin", app_label="wagtailadmin", model="admin"
78
+ )
79
+ )
80
+
81
+ self.login(user=admin_only_user)
82
+ response = self.request_preview_revision()
83
+
84
+ self.assertEqual(response.status_code, 302)
85
+ self.assertEqual(response["Location"], reverse("wagtailadmin_home"))
86
+
87
+ def test_preview_revision_forbidden_without_permission(self):
88
+ # Alter the editors group so it has no permissions for Christmas page.
89
+ st_patricks = Page.objects.get(slug="saint-patrick")
90
+ editors_group = Group.objects.get(name="Site-wide editors")
91
+ editors_group.page_permissions.update(page_id=st_patricks.id)
92
+
93
+ editor = get_user_model().objects.get(email="siteeditor@example.com")
94
+
95
+ self.login(editor)
96
+ response = self.request_preview_revision()
97
+
98
+ self.assertEqual(response.status_code, 302)
99
+
100
+ def test_revert_revision(self):
101
+ last_christmas_preview_url = reverse(
102
+ "wagtailadmin_pages:revisions_revert",
103
+ args=(self.christmas_event.id, self.last_christmas_revision.id),
104
+ )
105
+ response = self.client.get(last_christmas_preview_url)
106
+ self.assertEqual(response.status_code, 200)
107
+
108
+ self.assertContains(response, "Editing Event page")
109
+ self.assertContains(response, "You are viewing a previous version of this page")
110
+
111
+ # Form should show the content of the revision, not the current draft
112
+ self.assertContains(response, "Last Christmas I gave you my heart")
113
+
114
+ # Form should include a hidden 'revision' field
115
+ revision_field = (
116
+ """<input type="hidden" name="revision" value="%d" />"""
117
+ % self.last_christmas_revision.id
118
+ )
119
+ self.assertContains(response, revision_field)
120
+
121
+ # Buttons should be relabelled
122
+ self.assertContains(response, "Replace current draft")
123
+ self.assertContains(response, "Publish this version")
124
+
125
+ @freeze_time("2014-12-20 12:00:00")
126
+ def test_scheduled_revision(self):
127
+ if settings.USE_TZ:
128
+ # 12:00 UTC
129
+ self.christmas_event.go_live_at = "2014-12-26T12:00:00.000Z"
130
+ else:
131
+ # 12:00 in no specific timezone
132
+ self.christmas_event.go_live_at = "2014-12-26T12:00:00"
133
+ this_christmas_revision = self.christmas_event.save_revision(log_action=True)
134
+ this_christmas_revision.publish(log_action=True)
135
+ this_christmas_unschedule_url = reverse(
136
+ "wagtailadmin_pages:revisions_unschedule",
137
+ args=(self.christmas_event.id, this_christmas_revision.id),
138
+ )
139
+ response = self.client.get(
140
+ reverse("wagtailadmin_pages:history", args=(self.christmas_event.id,))
141
+ )
142
+ self.assertEqual(response.status_code, 200)
143
+ self.assertContains(response, "Page scheduled for publishing at 26 Dec 2014")
144
+ self.assertContains(response, this_christmas_unschedule_url)
145
+
146
+
147
+ class TestStreamRevisions(TestCase, WagtailTestUtils):
148
+ def setUp(self):
149
+ self.root_page = Page.objects.get(id=2)
150
+
151
+ self.test_page = DefaultStreamPage(
152
+ title="A DefaultStreamPage",
153
+ slug="a-defaultstreampage",
154
+ )
155
+ self.root_page.add_child(instance=self.test_page)
156
+
157
+ self.test_page.title = "An Updated DefaultStreamPage"
158
+ self.first_revision = self.test_page.save_revision()
159
+ self.first_revision.created_at = local_datetime(2022, 5, 10)
160
+ self.first_revision.save()
161
+
162
+ self.login()
163
+
164
+ def test_revert_revision(self):
165
+ test_page_revert_url = reverse(
166
+ "wagtailadmin_pages:revisions_revert",
167
+ args=(self.test_page.id, self.first_revision.id),
168
+ )
169
+ response = self.client.get(test_page_revert_url)
170
+ self.assertEqual(response.status_code, 200)
171
+
172
+ html = response.content.decode()
173
+ blocks_js = versioned_static("wagtailadmin/js/telepath/blocks.js")
174
+ streamfield_css = versioned_static("wagtailadmin/css/panels/streamfield.css")
175
+
176
+ # The media files for StreamField should be included in the HTML
177
+ self.assertTagInHTML(f'<script src="{blocks_js}"></script>', html)
178
+ self.assertTagInHTML(
179
+ f'<link href="{streamfield_css}" media="all" rel="stylesheet">',
180
+ html,
181
+ allow_extra_attrs=True, # Django 4.1 removes the type="text/css" attribute
182
+ )
183
+
184
+
185
+ class TestCompareRevisions(TestCase, WagtailTestUtils):
186
+ # Actual tests for the comparison classes can be found in test_compare.py
187
+
188
+ fixtures = ["test.json"]
189
+
190
+ def setUp(self):
191
+ self.christmas_event = EventPage.objects.get(url_path="/home/events/christmas/")
192
+ self.christmas_event.title = "Last Christmas"
193
+ self.christmas_event.date_from = "2013-12-25"
194
+ self.christmas_event.body = (
195
+ "<p>Last Christmas I gave you my heart, "
196
+ "but the very next day you gave it away</p>"
197
+ )
198
+ self.last_christmas_revision = self.christmas_event.save_revision()
199
+ self.last_christmas_revision.created_at = local_datetime(2013, 12, 25)
200
+ self.last_christmas_revision.save()
201
+
202
+ self.christmas_event.title = "This Christmas"
203
+ self.christmas_event.date_from = "2014-12-25"
204
+ self.christmas_event.body = (
205
+ "<p>This year, to save me from tears, "
206
+ "I'll give it to someone special</p>"
207
+ )
208
+ self.this_christmas_revision = self.christmas_event.save_revision()
209
+ self.this_christmas_revision.created_at = local_datetime(2014, 12, 25)
210
+ self.this_christmas_revision.save()
211
+
212
+ self.login()
213
+
214
+ def test_compare_revisions(self):
215
+ compare_url = reverse(
216
+ "wagtailadmin_pages:revisions_compare",
217
+ args=(
218
+ self.christmas_event.id,
219
+ self.last_christmas_revision.id,
220
+ self.this_christmas_revision.id,
221
+ ),
222
+ )
223
+ response = self.client.get(compare_url)
224
+ self.assertEqual(response.status_code, 200)
225
+
226
+ self.assertContains(
227
+ response,
228
+ '<span class="deletion">Last Christmas I gave you my heart, but the very next day you gave it away</span><span class="addition">This year, to save me from tears, I&#39;ll give it to someone special</span>',
229
+ html=True,
230
+ )
231
+
232
+ def test_compare_revisions_earliest(self):
233
+ compare_url = reverse(
234
+ "wagtailadmin_pages:revisions_compare",
235
+ args=(self.christmas_event.id, "earliest", self.this_christmas_revision.id),
236
+ )
237
+ response = self.client.get(compare_url)
238
+ self.assertEqual(response.status_code, 200)
239
+
240
+ self.assertContains(
241
+ response,
242
+ '<span class="deletion">Last Christmas I gave you my heart, but the very next day you gave it away</span><span class="addition">This year, to save me from tears, I&#39;ll give it to someone special</span>',
243
+ html=True,
244
+ )
245
+
246
+ def test_compare_revisions_latest(self):
247
+ compare_url = reverse(
248
+ "wagtailadmin_pages:revisions_compare",
249
+ args=(self.christmas_event.id, self.last_christmas_revision.id, "latest"),
250
+ )
251
+ response = self.client.get(compare_url)
252
+ self.assertEqual(response.status_code, 200)
253
+
254
+ self.assertContains(
255
+ response,
256
+ '<span class="deletion">Last Christmas I gave you my heart, but the very next day you gave it away</span><span class="addition">This year, to save me from tears, I&#39;ll give it to someone special</span>',
257
+ html=True,
258
+ )
259
+
260
+ def test_compare_revisions_live(self):
261
+ # Mess with the live version, bypassing revisions
262
+ self.christmas_event.body = (
263
+ "<p>This year, to save me from tears, " "I'll just feed it to the dog</p>"
264
+ )
265
+ self.christmas_event.save(update_fields=["body"])
266
+
267
+ compare_url = reverse(
268
+ "wagtailadmin_pages:revisions_compare",
269
+ args=(self.christmas_event.id, self.last_christmas_revision.id, "live"),
270
+ )
271
+ response = self.client.get(compare_url)
272
+ self.assertEqual(response.status_code, 200)
273
+
274
+ self.assertContains(
275
+ response,
276
+ '<span class="deletion">Last Christmas I gave you my heart, but the very next day you gave it away</span><span class="addition">This year, to save me from tears, I&#39;ll just feed it to the dog</span>',
277
+ html=True,
278
+ )
279
+
280
+
281
+ class TestCompareRevisionsWithPerUserEditHandlers(TestCase, WagtailTestUtils):
282
+ fixtures = ["test.json"]
283
+
284
+ def setUp(self):
285
+ self.home = Page.objects.get(url_path="/home/")
286
+ self.secret_page = SecretPage(
287
+ title="Secret page",
288
+ boring_data="InnocentCorp is the leading supplier of door hinges",
289
+ secret_data="for flying saucers",
290
+ )
291
+ self.home.add_child(instance=self.secret_page)
292
+ self.old_revision = self.secret_page.save_revision()
293
+ self.secret_page.boring_data = (
294
+ "InnocentCorp is the leading supplier of rubber sprockets"
295
+ )
296
+ self.secret_page.secret_data = "for fake moon landings"
297
+ self.new_revision = self.secret_page.save_revision()
298
+ self.compare_url = reverse(
299
+ "wagtailadmin_pages:revisions_compare",
300
+ args=(self.secret_page.id, self.old_revision.id, self.new_revision.id),
301
+ )
302
+
303
+ def test_comparison_as_superuser(self):
304
+ self.login()
305
+ response = self.client.get(self.compare_url)
306
+ self.assertEqual(response.status_code, 200)
307
+
308
+ self.assertContains(
309
+ response,
310
+ 'InnocentCorp is the leading supplier of <span class="deletion">door hinges</span><span class="addition">rubber sprockets</span>',
311
+ html=True,
312
+ )
313
+ self.assertContains(
314
+ response,
315
+ 'for <span class="deletion">flying saucers</span><span class="addition">fake moon landings</span>',
316
+ html=True,
317
+ )
318
+
319
+ def test_comparison_as_ordinary_user(self):
320
+ user = self.create_user(username="editor", password="password")
321
+ user.groups.add(Group.objects.get(name="Site-wide editors"))
322
+ self.login(username="editor", password="password")
323
+
324
+ response = self.client.get(self.compare_url)
325
+ self.assertEqual(response.status_code, 200)
326
+
327
+ self.assertContains(
328
+ response,
329
+ 'InnocentCorp is the leading supplier of <span class="deletion">door hinges</span><span class="addition">rubber sprockets</span>',
330
+ html=True,
331
+ )
332
+ self.assertNotContains(
333
+ response,
334
+ "moon landings",
335
+ )
336
+
337
+
338
+ class TestCompareRevisionsWithNonModelField(TestCase, WagtailTestUtils):
339
+ """
340
+ Tests if form fields defined in the base_form_class will not be included.
341
+ in revisions view as they are not actually on the model.
342
+ Flagged in issue #3737
343
+ Note: Actual tests for comparison classes can be found in test_compare.py
344
+ """
345
+
346
+ fixtures = ["test.json"]
347
+ # FormClassAdditionalFieldPage
348
+
349
+ def setUp(self):
350
+ # Find root page
351
+ self.root_page = Page.objects.get(id=2)
352
+
353
+ # Add child page of class with base_form_class override
354
+ # non model field is 'code'
355
+ self.test_page = FormClassAdditionalFieldPage(
356
+ title="A Statement",
357
+ slug="a-statement",
358
+ location="Early Morning Cafe, Mainland, NZ",
359
+ body="<p>hello</p>",
360
+ )
361
+ self.root_page.add_child(instance=self.test_page)
362
+
363
+ # add new revision
364
+ self.test_page.title = "Statement"
365
+ self.test_page.location = "Victory Monument, Bangkok"
366
+ self.test_page.body = "<p>I would like very much to go into the forrest.</p>"
367
+ self.test_page_revision = self.test_page.save_revision()
368
+ self.test_page_revision.created_at = local_datetime(2017, 10, 15)
369
+ self.test_page_revision.save()
370
+
371
+ # add another new revision
372
+ self.test_page.title = "True Statement"
373
+ self.test_page.location = "Victory Monument, Bangkok"
374
+ self.test_page.body = "<p>I would like very much to go into the forest.</p>"
375
+ self.test_page_revision_new = self.test_page.save_revision()
376
+ self.test_page_revision_new.created_at = local_datetime(2017, 10, 16)
377
+ self.test_page_revision_new.save()
378
+
379
+ self.login()
380
+
381
+ def test_base_form_class_used(self):
382
+ """First ensure that the non-model field is appearing in edit."""
383
+ edit_url = reverse(
384
+ "wagtailadmin_pages:add",
385
+ args=("tests", "formclassadditionalfieldpage", self.test_page.id),
386
+ )
387
+ response = self.client.get(edit_url)
388
+ self.assertContains(
389
+ response,
390
+ '<input type="text" name="code" aria-describedby="panel-child-content-child-code-helptext" required id="id_code" maxlength="5" />',
391
+ html=True,
392
+ )
393
+
394
+ def test_compare_revisions(self):
395
+ """Confirm that the non-model field is not shown in revision."""
396
+ compare_url = reverse(
397
+ "wagtailadmin_pages:revisions_compare",
398
+ args=(
399
+ self.test_page.id,
400
+ self.test_page_revision.id,
401
+ self.test_page_revision_new.id,
402
+ ),
403
+ )
404
+ response = self.client.get(compare_url)
405
+ self.assertContains(
406
+ response,
407
+ '<span class="deletion">forrest.</span><span class="addition">forest.</span>',
408
+ )
409
+ # should not contain the field defined in the formclass used
410
+ self.assertNotContains(response, "<h2>Code:</h2>")
411
+
412
+
413
+ class TestRevisionsUnschedule(TestCase, WagtailTestUtils):
414
+ fixtures = ["test.json"]
415
+
416
+ def setUp(self):
417
+ self.christmas_event = EventPage.objects.get(url_path="/home/events/christmas/")
418
+ self.christmas_event.title = "Last Christmas"
419
+ self.christmas_event.date_from = "2013-12-25"
420
+ self.christmas_event.body = (
421
+ "<p>Last Christmas I gave you my heart, "
422
+ "but the very next day you gave it away</p>"
423
+ )
424
+ self.last_christmas_revision = self.christmas_event.save_revision()
425
+ self.last_christmas_revision.created_at = local_datetime(2013, 12, 25)
426
+ self.last_christmas_revision.save()
427
+ self.last_christmas_revision.publish()
428
+
429
+ self.christmas_event.title = "This Christmas"
430
+ self.christmas_event.date_from = "2014-12-25"
431
+ self.christmas_event.body = (
432
+ "<p>This year, to save me from tears, "
433
+ "I'll give it to someone special</p>"
434
+ )
435
+ self.this_christmas_revision = self.christmas_event.save_revision()
436
+ self.this_christmas_revision.created_at = local_datetime(2014, 12, 24)
437
+ self.this_christmas_revision.save()
438
+
439
+ self.this_christmas_revision.approved_go_live_at = local_datetime(2014, 12, 25)
440
+ self.this_christmas_revision.save()
441
+
442
+ self.user = self.login()
443
+
444
+ def test_unschedule_view(self):
445
+ """
446
+ This tests that the unschedule view responds with a confirm page
447
+ """
448
+ response = self.client.get(
449
+ reverse(
450
+ "wagtailadmin_pages:revisions_unschedule",
451
+ args=(self.christmas_event.id, self.this_christmas_revision.id),
452
+ )
453
+ )
454
+ self.assertEqual(response.status_code, 200)
455
+ self.assertTemplateUsed(
456
+ response, "wagtailadmin/shared/revisions/confirm_unschedule.html"
457
+ )
458
+
459
+ def test_unschedule_view_invalid_page_id(self):
460
+ """
461
+ This tests that the unschedule view returns an error if the page id is invalid
462
+ """
463
+ # Get unschedule page
464
+ response = self.client.get(
465
+ reverse("wagtailadmin_pages:revisions_unschedule", args=(12345, 67894))
466
+ )
467
+
468
+ # Check that the user received a 404 response
469
+ self.assertEqual(response.status_code, 404)
470
+
471
+ def test_unschedule_view_invalid_revision_id(self):
472
+ """
473
+ This tests that the unschedule view returns an error if the page id is invalid
474
+ """
475
+ # Get unschedule page
476
+ response = self.client.get(
477
+ reverse(
478
+ "wagtailadmin_pages:revisions_unschedule",
479
+ args=(self.christmas_event.id, 67894),
480
+ )
481
+ )
482
+
483
+ # Check that the user received a 404 response
484
+ self.assertEqual(response.status_code, 404)
485
+
486
+ def test_unschedule_view_bad_permissions(self):
487
+ """
488
+ This tests that the unschedule view doesn't allow users without publish permissions
489
+ """
490
+ # Remove privileges from user
491
+ self.user.is_superuser = False
492
+ self.user.user_permissions.add(
493
+ Permission.objects.get(
494
+ content_type__app_label="wagtailadmin", codename="access_admin"
495
+ )
496
+ )
497
+ self.user.save()
498
+
499
+ # Get unschedule page
500
+ response = self.client.get(
501
+ reverse(
502
+ "wagtailadmin_pages:revisions_unschedule",
503
+ args=(self.christmas_event.id, self.this_christmas_revision.id),
504
+ )
505
+ )
506
+
507
+ # Check that the user received a 302 redirected response
508
+ self.assertEqual(response.status_code, 302)
509
+
510
+ def test_unschedule_view_post(self):
511
+ """
512
+ This posts to the unschedule view and checks that the revision was unscheduled
513
+ """
514
+
515
+ # Post to the unschedule page
516
+ response = self.client.post(
517
+ reverse(
518
+ "wagtailadmin_pages:revisions_unschedule",
519
+ args=(self.christmas_event.id, self.this_christmas_revision.id),
520
+ )
521
+ )
522
+
523
+ # Should be redirected to page history
524
+ self.assertRedirects(
525
+ response,
526
+ reverse("wagtailadmin_pages:history", args=(self.christmas_event.id,)),
527
+ )
528
+
529
+ # Check that the page has no approved_schedule
530
+ self.assertFalse(
531
+ EventPage.objects.get(id=self.christmas_event.id).approved_schedule
532
+ )
533
+
534
+ # Check that the approved_go_live_at has been cleared from the revision
535
+ self.assertIsNone(
536
+ self.christmas_event.revisions.get(
537
+ id=self.this_christmas_revision.id
538
+ ).approved_go_live_at
539
+ )
540
+
541
+ def test_unschedule_view_post_with_next_url(self):
542
+ """
543
+ This tests that the redirect response follows the "next" parameter
544
+ """
545
+
546
+ unschedule_url = reverse(
547
+ "wagtailadmin_pages:revisions_unschedule",
548
+ args=(self.christmas_event.id, self.this_christmas_revision.id),
549
+ )
550
+ edit_url = reverse("wagtailadmin_pages:edit", args=(self.christmas_event.id,))
551
+
552
+ # Post to the unschedule page
553
+ response = self.client.post(f"{unschedule_url}?next={edit_url}")
554
+
555
+ # Should be redirected to edit page
556
+ self.assertRedirects(response, edit_url)
557
+
558
+ # Check that the page has no approved_schedule
559
+ self.assertFalse(
560
+ EventPage.objects.get(id=self.christmas_event.id).approved_schedule
561
+ )
562
+
563
+ # Check that the approved_go_live_at has been cleared from the revision
564
+ self.assertIsNone(
565
+ self.christmas_event.revisions.get(
566
+ id=self.this_christmas_revision.id
567
+ ).approved_go_live_at
568
+ )
569
+
570
+
571
+ class TestRevisionsUnscheduleForUnpublishedPages(TestCase, WagtailTestUtils):
572
+ fixtures = ["test.json"]
573
+
574
+ def setUp(self):
575
+ self.unpublished_event = EventPage.objects.get(
576
+ url_path="/home/events/tentative-unpublished-event/"
577
+ )
578
+ self.unpublished_event.title = "Unpublished Page"
579
+ self.unpublished_event.date_from = "2014-12-25"
580
+ self.unpublished_event.body = "<p>Some Content</p>"
581
+ self.unpublished_revision = self.unpublished_event.save_revision()
582
+ self.unpublished_revision.created_at = local_datetime(2014, 12, 25)
583
+ self.unpublished_revision.save()
584
+
585
+ self.user = self.login()
586
+
587
+ def test_unschedule_view(self):
588
+ """
589
+ This tests that the unschedule view responds with a confirm page
590
+ """
591
+ response = self.client.get(
592
+ reverse(
593
+ "wagtailadmin_pages:revisions_unschedule",
594
+ args=(self.unpublished_event.id, self.unpublished_revision.id),
595
+ )
596
+ )
597
+ self.assertEqual(response.status_code, 200)
598
+ self.assertTemplateUsed(
599
+ response, "wagtailadmin/shared/revisions/confirm_unschedule.html"
600
+ )
601
+
602
+ def test_unschedule_view_post(self):
603
+ """
604
+ This posts to the unschedule view and checks that the revision was unscheduled
605
+ """
606
+
607
+ # Post to the unschedule page
608
+ response = self.client.post(
609
+ reverse(
610
+ "wagtailadmin_pages:revisions_unschedule",
611
+ args=(self.unpublished_event.id, self.unpublished_revision.id),
612
+ )
613
+ )
614
+
615
+ # Should be redirected to page history
616
+ self.assertRedirects(
617
+ response,
618
+ reverse("wagtailadmin_pages:history", args=(self.unpublished_event.id,)),
619
+ )
620
+
621
+ # Check that the page has no approved_schedule
622
+ self.assertFalse(
623
+ EventPage.objects.get(id=self.unpublished_event.id).approved_schedule
624
+ )
625
+
626
+ # Check that the approved_go_live_at has been cleared from the revision
627
+ self.assertIsNone(
628
+ self.unpublished_event.revisions.get(
629
+ id=self.unpublished_revision.id
630
+ ).approved_go_live_at
631
+ )
testbed/wagtail__wagtail/wagtail/admin/tests/pages/test_view_draft.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.contrib.auth import get_user_model
2
+ from django.contrib.auth.models import Group, Permission
3
+ from django.test import TestCase
4
+ from django.urls import reverse
5
+
6
+ from wagtail.models import Page
7
+ from wagtail.test.testapp.models import SimplePage, StreamPage
8
+ from wagtail.test.utils import WagtailTestUtils
9
+
10
+
11
+ class TestDraftAccess(TestCase, WagtailTestUtils):
12
+ """Tests for the draft view access restrictions."""
13
+
14
+ def setUp(self):
15
+ # Find root page
16
+ self.root_page = Page.objects.get(id=2)
17
+
18
+ # Add child page
19
+ self.child_page = SimplePage(
20
+ title="Hello world!",
21
+ slug="hello-world",
22
+ content="hello",
23
+ )
24
+ self.root_page.add_child(instance=self.child_page)
25
+
26
+ # Add stream page (which has empty preview_modes, and so doesn't allow viewing draft)
27
+ self.stream_page = StreamPage(title="stream page", body=[("text", "hello")])
28
+ self.root_page.add_child(instance=self.stream_page)
29
+
30
+ # create user with admin access (but not draft_view access)
31
+ user = self.create_user(username="bob", password="password")
32
+ user.user_permissions.add(
33
+ Permission.objects.get(
34
+ content_type__app_label="wagtailadmin", codename="access_admin"
35
+ )
36
+ )
37
+
38
+ def test_draft_access_admin(self):
39
+ """Test that admin can view draft."""
40
+ # Login as admin
41
+ self.user = self.login()
42
+
43
+ # Try getting page draft
44
+ response = self.client.get(
45
+ reverse("wagtailadmin_pages:view_draft", args=(self.child_page.id,))
46
+ )
47
+
48
+ # User can view
49
+ self.assertEqual(response.status_code, 200)
50
+
51
+ def test_page_without_preview_modes_is_unauthorised(self):
52
+ # Login as admin
53
+ self.user = self.login()
54
+
55
+ # Try getting page draft
56
+ response = self.client.get(
57
+ reverse("wagtailadmin_pages:view_draft", args=(self.stream_page.id,))
58
+ )
59
+
60
+ # Unauthorised response (because this page type has previewing disabled)
61
+ self.assertRedirects(response, "/admin/")
62
+
63
+ def test_draft_access_unauthorised(self):
64
+ """Test that user without edit/publish permission can't view draft."""
65
+ self.login(username="bob", password="password")
66
+
67
+ # Try getting page draft
68
+ response = self.client.get(
69
+ reverse("wagtailadmin_pages:view_draft", args=(self.child_page.id,))
70
+ )
71
+
72
+ # User gets redirected to the home page
73
+ self.assertEqual(response.status_code, 302)
74
+
75
+ def test_draft_access_authorised(self):
76
+ """Test that user with edit permission can view draft."""
77
+ # give user the permission to edit page
78
+ user = get_user_model().objects.get(email="bob@example.com")
79
+ user.groups.add(Group.objects.get(name="Moderators"))
80
+ user.save()
81
+
82
+ self.login(username="bob", password="password")
83
+
84
+ # Get add subpage page
85
+ response = self.client.get(
86
+ reverse("wagtailadmin_pages:view_draft", args=(self.child_page.id,))
87
+ )
88
+
89
+ # User can view
90
+ self.assertEqual(response.status_code, 200)
91
+
92
+ def test_middleware_response_is_returned(self):
93
+ """
94
+ If middleware returns a response while serving a page preview, that response should be
95
+ returned back to the user
96
+ """
97
+ self.login()
98
+ response = self.client.get(
99
+ reverse("wagtailadmin_pages:view_draft", args=(self.child_page.id,)),
100
+ HTTP_USER_AGENT="EvilHacker",
101
+ )
102
+ self.assertEqual(response.status_code, 403)
testbed/wagtail__wagtail/wagtail/admin/tests/test_account_management.py ADDED
@@ -0,0 +1,952 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import pytz
4
+ from django.conf import settings
5
+ from django.contrib.auth import get_user_model
6
+ from django.contrib.auth import views as auth_views
7
+ from django.contrib.auth.models import Group, Permission
8
+ from django.contrib.auth.tokens import PasswordResetTokenGenerator
9
+ from django.core import mail
10
+ from django.core.files.uploadedfile import SimpleUploadedFile
11
+ from django.test import RequestFactory, TestCase, override_settings
12
+ from django.urls import reverse
13
+
14
+ from wagtail.admin.localization import (
15
+ WAGTAILADMIN_PROVIDED_LANGUAGES,
16
+ get_available_admin_languages,
17
+ get_available_admin_time_zones,
18
+ )
19
+ from wagtail.admin.views.account import account, profile_tab
20
+ from wagtail.images.tests.utils import get_test_image_file
21
+ from wagtail.test.utils import WagtailTestUtils
22
+ from wagtail.users.models import UserProfile
23
+
24
+
25
+ class TestAuthentication(TestCase, WagtailTestUtils):
26
+ """
27
+ This tests that users can login and logout of the admin interface
28
+ """
29
+
30
+ def test_login_view(self):
31
+ """
32
+ This tests that the login view responds with a login page
33
+ """
34
+ # Get login page
35
+ response = self.client.get(reverse("wagtailadmin_login"))
36
+
37
+ # Check that the user received a login page
38
+ self.assertEqual(response.status_code, 200)
39
+ self.assertTemplateUsed(response, "wagtailadmin/login.html")
40
+
41
+ def test_login_view_post(self):
42
+ """
43
+ This posts user credentials to the login view and checks that
44
+ the user was logged in successfully
45
+ """
46
+ # Create user to log in with
47
+ self.create_superuser(
48
+ username="test", email="test@email.com", password="password"
49
+ )
50
+
51
+ # Post credentials to the login page
52
+ response = self.client.post(
53
+ reverse("wagtailadmin_login"),
54
+ {
55
+ "username": "test@email.com"
56
+ if settings.AUTH_USER_MODEL == "emailuser.EmailUser"
57
+ else "test",
58
+ "password": "password",
59
+ # NOTE: This is set using a hidden field in reality
60
+ "next": reverse("wagtailadmin_home"),
61
+ },
62
+ )
63
+
64
+ # Check that the user was redirected to the dashboard
65
+ self.assertRedirects(response, reverse("wagtailadmin_home"))
66
+
67
+ # Check that the user was logged in
68
+ self.assertIn("_auth_user_id", self.client.session)
69
+ self.assertEqual(
70
+ str(self.client.session["_auth_user_id"]),
71
+ str(get_user_model().objects.get(email="test@email.com").pk),
72
+ )
73
+
74
+ def test_already_logged_in_redirect(self):
75
+ """
76
+ This tests that a user who is already logged in is automatically
77
+ redirected to the admin dashboard if they try to access the login
78
+ page
79
+ """
80
+ # Login
81
+ self.login()
82
+
83
+ # Get login page
84
+ response = self.client.get(reverse("wagtailadmin_login"))
85
+
86
+ # Check that the user was redirected to the dashboard
87
+ self.assertRedirects(response, reverse("wagtailadmin_home"))
88
+
89
+ def test_logged_in_as_non_privileged_user_doesnt_redirect(self):
90
+ """
91
+ This tests that if the user is logged in but hasn't got permission
92
+ to access the admin, they are not redirected to the admin
93
+
94
+ This tests issue #431
95
+ """
96
+ # Login as unprivileged user
97
+ self.create_user(username="unprivileged", password="123")
98
+ self.login(username="unprivileged", password="123")
99
+
100
+ # Get login page
101
+ response = self.client.get(reverse("wagtailadmin_login"))
102
+
103
+ # Check that the user received a login page and was not redirected
104
+ self.assertEqual(response.status_code, 200)
105
+ self.assertTemplateUsed(response, "wagtailadmin/login.html")
106
+
107
+ def test_logout(self):
108
+ """
109
+ This tests that the user can logout
110
+ """
111
+ # Login
112
+ self.login()
113
+
114
+ # Get logout page
115
+ response = self.client.get(reverse("wagtailadmin_logout"))
116
+
117
+ # Check that the user was redirected to the login page
118
+ self.assertRedirects(response, reverse("wagtailadmin_login"))
119
+
120
+ # Check that the user was logged out
121
+ self.assertNotIn("_auth_user_id", self.client.session)
122
+
123
+ def test_not_logged_in_redirect(self):
124
+ """
125
+ This tests that a not logged in user is redirected to the
126
+ login page
127
+ """
128
+ # Get dashboard
129
+ response = self.client.get(reverse("wagtailadmin_home"))
130
+
131
+ # Check that the user was redirected to the login page and that next was set correctly
132
+ self.assertRedirects(
133
+ response,
134
+ reverse("wagtailadmin_login") + "?next=" + reverse("wagtailadmin_home"),
135
+ )
136
+
137
+ def test_not_logged_in_gives_403_to_ajax_requests(self):
138
+ """
139
+ This tests that a not logged in user is given a 403 error on AJAX requests
140
+ """
141
+ # Get dashboard
142
+ response = self.client.get(
143
+ reverse("wagtailadmin_home"), HTTP_X_REQUESTED_WITH="XMLHttpRequest"
144
+ )
145
+
146
+ # AJAX requests should be given a 403 error instead of being redirected
147
+ self.assertEqual(response.status_code, 403)
148
+
149
+ def test_not_logged_in_redirect_default_settings(self):
150
+ """
151
+ This does the same as the above test but checks that it
152
+ redirects to the correct place when the user has not set
153
+ the LOGIN_URL setting correctly
154
+ """
155
+ # Get dashboard with default LOGIN_URL setting
156
+ with self.settings(LOGIN_URL="django.contrib.auth.views.login"):
157
+ response = self.client.get(reverse("wagtailadmin_home"))
158
+
159
+ # Check that the user was redirected to the login page and that next was set correctly
160
+ # Note: The user will be redirected to 'django.contrib.auth.views.login' but
161
+ # this must be the same URL as 'wagtailadmin_login'
162
+ self.assertEqual(response.status_code, 302)
163
+ self.assertRedirects(
164
+ response,
165
+ reverse("wagtailadmin_login") + "?next=" + reverse("wagtailadmin_home"),
166
+ )
167
+
168
+ def test_logged_in_no_permission_redirect(self):
169
+ """
170
+ This tests that a logged in user without admin access permissions is
171
+ redirected to the login page, with an error message
172
+ """
173
+ # Login as unprivileged user
174
+ self.create_user(username="unprivileged", password="123")
175
+ self.login(username="unprivileged", password="123")
176
+
177
+ # Get dashboard
178
+ response = self.client.get(reverse("wagtailadmin_home"), follow=True)
179
+
180
+ # Check that the user was redirected to the login page and that next was set correctly
181
+ self.assertRedirects(
182
+ response,
183
+ reverse("wagtailadmin_login") + "?next=" + reverse("wagtailadmin_home"),
184
+ )
185
+ self.assertContains(response, "You do not have permission to access the admin")
186
+
187
+ def test_logged_in_no_permission_gives_403_to_ajax_requests(self):
188
+ """
189
+ This tests that a logged in user without admin access permissions is
190
+ given a 403 error on ajax requests
191
+ """
192
+ # Login as unprivileged user
193
+ self.create_user(username="unprivileged", password="123")
194
+ self.login(username="unprivileged", password="123")
195
+
196
+ # Get dashboard
197
+ response = self.client.get(
198
+ reverse("wagtailadmin_home"), HTTP_X_REQUESTED_WITH="XMLHttpRequest"
199
+ )
200
+
201
+ # AJAX requests should be given a 403 error instead of being redirected
202
+ self.assertEqual(response.status_code, 403)
203
+
204
+
205
+ class TestAccountSectionUtilsMixin:
206
+ def assertPanelActive(self, response, name):
207
+ panels = {
208
+ panel.name
209
+ for panelset in response.context["panels_by_tab"].values()
210
+ for panel in panelset
211
+ }
212
+ self.assertIn(name, panels, "Panel %s not active in response" % name)
213
+
214
+ def assertPanelNotActive(self, response, name):
215
+ panels = {
216
+ panel.name
217
+ for panelset in response.context["panels_by_tab"].values()
218
+ for panel in panelset
219
+ }
220
+ self.assertNotIn(name, panels, "Panel %s active in response" % name)
221
+
222
+ def post_form(self, extra_post_data):
223
+ post_data = {
224
+ "name_email-first_name": "Test",
225
+ "name_email-last_name": "User",
226
+ "name_email-email": self.user.email,
227
+ "notifications-submitted_notifications": "false",
228
+ "notifications-approved_notifications": "false",
229
+ "notifications-rejected_notifications": "true",
230
+ "notifications-updated_comments_notifications": "true",
231
+ "locale-preferred_language": "es",
232
+ "locale-current_time_zone": "Europe/London",
233
+ }
234
+ post_data.update(extra_post_data)
235
+ return self.client.post(reverse("wagtailadmin_account"), post_data)
236
+
237
+
238
+ class TestAccountSection(TestCase, WagtailTestUtils, TestAccountSectionUtilsMixin):
239
+ """
240
+ This tests that the accounts section is working
241
+ """
242
+
243
+ def setUp(self):
244
+ self.user = self.login()
245
+
246
+ def test_account_view(self):
247
+ """
248
+ This tests that the accounts view responds with an index page
249
+ """
250
+ # Get account page
251
+ response = self.client.get(reverse("wagtailadmin_account"))
252
+
253
+ # Check that the user received an account page
254
+ self.assertEqual(response.status_code, 200)
255
+ self.assertTemplateUsed(response, "wagtailadmin/account/account.html")
256
+
257
+ self.assertPanelActive(response, "name_email")
258
+ self.assertPanelActive(response, "notifications")
259
+ self.assertPanelActive(response, "locale")
260
+ self.assertPanelActive(response, "password")
261
+
262
+ # These fields may hide themselves
263
+ self.assertContains(response, "Email")
264
+ self.assertContains(response, "Preferred language")
265
+
266
+ if settings.USE_TZ:
267
+ self.assertContains(response, "Current time zone")
268
+ else:
269
+ self.assertNotContains(response, "Current time zone")
270
+
271
+ # Form media should be included on the page
272
+ self.assertContains(response, "vendor/colorpicker.js")
273
+
274
+ def test_change_name_post(self):
275
+ response = self.post_form(
276
+ {
277
+ "name_email-first_name": "Fox",
278
+ "name_email-last_name": "Mulder",
279
+ }
280
+ )
281
+
282
+ # Check that the user was redirected to the account page
283
+ self.assertRedirects(response, reverse("wagtailadmin_account"))
284
+
285
+ # Check that the name was changed
286
+ self.user.refresh_from_db()
287
+ self.assertEqual(self.user.first_name, "Fox")
288
+ self.assertEqual(self.user.last_name, "Mulder")
289
+
290
+ def test_change_email_post(self):
291
+ response = self.post_form(
292
+ {
293
+ "name_email-email": "test@email.com",
294
+ }
295
+ )
296
+
297
+ # Check that the user was redirected to the account page
298
+ self.assertRedirects(response, reverse("wagtailadmin_account"))
299
+
300
+ # Check that the email was changed
301
+ self.user.refresh_from_db()
302
+ self.assertEqual(self.user.email, "test@email.com")
303
+
304
+ def test_change_email_not_valid(self):
305
+ response = self.post_form(
306
+ {
307
+ "name_email-email": "test@email",
308
+ }
309
+ )
310
+
311
+ # Check that the user wasn't redirected
312
+ self.assertEqual(response.status_code, 200)
313
+
314
+ # Check that a validation error was raised
315
+ self.assertIn(
316
+ "email",
317
+ response.context["panels_by_tab"][profile_tab][0].get_form().errors.keys(),
318
+ )
319
+
320
+ # Check that the email was not changed
321
+ self.user.refresh_from_db()
322
+ self.assertNotEqual(self.user.email, "test@email")
323
+
324
+ @override_settings(WAGTAIL_EMAIL_MANAGEMENT_ENABLED=False)
325
+ def test_with_email_management_disabled(self):
326
+ # Get account page
327
+ response = self.client.get(reverse("wagtailadmin_account"))
328
+
329
+ self.assertEqual(response.status_code, 200)
330
+ self.assertTemplateUsed(response, "wagtailadmin/account/account.html")
331
+ self.assertNotContains(response, "id_name_email-email")
332
+
333
+ @override_settings(WAGTAIL_PASSWORD_MANAGEMENT_ENABLED=False)
334
+ def test_account_view_with_password_management_disabled(self):
335
+ # Get account page
336
+ response = self.client.get(reverse("wagtailadmin_account"))
337
+
338
+ self.assertEqual(response.status_code, 200)
339
+ self.assertTemplateUsed(response, "wagtailadmin/account/account.html")
340
+ # Page should NOT contain a 'Change password' option
341
+ self.assertNotContains(response, "Change password")
342
+
343
+ @override_settings(WAGTAIL_PASSWORD_MANAGEMENT_ENABLED=False)
344
+ def test_change_password_view_disabled(self):
345
+ response = self.client.get(reverse("wagtailadmin_account"))
346
+ self.assertPanelNotActive(response, "password")
347
+
348
+ def test_change_password(self):
349
+ response = self.post_form(
350
+ {
351
+ "password-old_password": "password",
352
+ "password-new_password1": "newpassword",
353
+ "password-new_password2": "newpassword",
354
+ }
355
+ )
356
+
357
+ # Check that the user was redirected to the account page
358
+ self.assertRedirects(response, reverse("wagtailadmin_account"))
359
+
360
+ # Check that the password was changed
361
+ self.user.refresh_from_db()
362
+ self.assertTrue(self.user.check_password("newpassword"))
363
+
364
+ def test_change_password_post_password_mismatch(self):
365
+ response = self.post_form(
366
+ {
367
+ "password-old_password": "password",
368
+ "password-new_password1": "newpassword",
369
+ "password-new_password2": "badpassword",
370
+ }
371
+ )
372
+
373
+ # Check that the user wasn't redirected
374
+ self.assertEqual(response.status_code, 200)
375
+
376
+ # Find password panel through context
377
+ password_panel = None
378
+ for panelset in response.context["panels_by_tab"].values():
379
+ for panel in panelset:
380
+ if panel.name == "password":
381
+ password_panel = panel
382
+ break
383
+
384
+ # Check that a validation error was raised
385
+ password_form = password_panel.get_form()
386
+ self.assertIn("new_password2", password_form.errors.keys())
387
+ self.assertIn(
388
+ "The two password fields didn’t match.",
389
+ password_form.errors["new_password2"],
390
+ )
391
+
392
+ # Check that the password was not changed
393
+ self.user.refresh_from_db()
394
+ self.assertTrue(self.user.check_password("password"))
395
+
396
+ def test_change_notifications(self):
397
+ response = self.post_form(
398
+ {
399
+ "submitted_notifications": "false",
400
+ "approved_notifications": "false",
401
+ "rejected_notifications": "true",
402
+ "updated_comments_notifications": "true",
403
+ }
404
+ )
405
+
406
+ # Check that the user was redirected to the account page
407
+ self.assertRedirects(response, reverse("wagtailadmin_account"))
408
+
409
+ profile = UserProfile.get_for_user(
410
+ get_user_model().objects.get(pk=self.user.pk)
411
+ )
412
+
413
+ # Check that the notification preferences are as submitted
414
+ self.assertFalse(profile.submitted_notifications)
415
+ self.assertFalse(profile.approved_notifications)
416
+ self.assertTrue(profile.rejected_notifications)
417
+ self.assertTrue(profile.updated_comments_notifications)
418
+
419
+ def test_change_language_preferences(self):
420
+ response = self.post_form(
421
+ {
422
+ "locale-preferred_language": "es",
423
+ }
424
+ )
425
+
426
+ # Check that the user was redirected to the account page
427
+ self.assertRedirects(response, reverse("wagtailadmin_account"))
428
+
429
+ profile = UserProfile.get_for_user(self.user)
430
+ profile.refresh_from_db()
431
+
432
+ # Check that the language preferences are stored
433
+ self.assertEqual(profile.preferred_language, "es")
434
+
435
+ # check that the updated language preference is now indicated in HTML header
436
+ response = self.client.get(reverse("wagtailadmin_home"))
437
+ self.assertContains(response, '<html lang="es" dir="ltr">')
438
+
439
+ def test_unset_language_preferences(self):
440
+ profile = UserProfile.get_for_user(self.user)
441
+ profile.preferred_language = "en"
442
+ profile.save()
443
+
444
+ response = self.post_form(
445
+ {
446
+ "locale-preferred_language": "",
447
+ }
448
+ )
449
+
450
+ # Check that the user was redirected to the account page
451
+ self.assertRedirects(response, reverse("wagtailadmin_account"))
452
+
453
+ # Check that the language preferences are stored
454
+ profile.refresh_from_db()
455
+ self.assertEqual(profile.preferred_language, "")
456
+
457
+ # Check that the current language is assumed as English
458
+ self.assertEqual(profile.get_preferred_language(), "en")
459
+
460
+ @override_settings(
461
+ WAGTAILADMIN_PERMITTED_LANGUAGES=[("en", "English"), ("es", "Spanish")]
462
+ )
463
+ def test_available_admin_languages_with_permitted_languages(self):
464
+ self.assertListEqual(
465
+ get_available_admin_languages(), [("en", "English"), ("es", "Spanish")]
466
+ )
467
+
468
+ def test_available_admin_languages_by_default(self):
469
+ self.assertListEqual(
470
+ get_available_admin_languages(), WAGTAILADMIN_PROVIDED_LANGUAGES
471
+ )
472
+
473
+ @override_settings(WAGTAILADMIN_PERMITTED_LANGUAGES=[("en", "English")])
474
+ def test_not_show_options_if_only_one_language_is_permitted(self):
475
+ response = self.client.get(reverse("wagtailadmin_account"))
476
+ self.assertNotContains(response, "Preferred language")
477
+
478
+ @unittest.skipUnless(settings.USE_TZ, "Timezone support is disabled")
479
+ def test_change_current_time_zone(self):
480
+ response = self.post_form(
481
+ {
482
+ "locale-current_time_zone": "Pacific/Fiji",
483
+ }
484
+ )
485
+
486
+ # Check that the user was redirected to the account page
487
+ self.assertRedirects(response, reverse("wagtailadmin_account"))
488
+
489
+ profile = UserProfile.get_for_user(self.user)
490
+ profile.refresh_from_db()
491
+
492
+ # Check that the current time zone is stored
493
+ self.assertEqual(profile.current_time_zone, "Pacific/Fiji")
494
+
495
+ @unittest.skipUnless(settings.USE_TZ, "Timezone support is disabled")
496
+ def test_unset_current_time_zone(self):
497
+ response = self.post_form(
498
+ {
499
+ "locale-current_time_zone": "",
500
+ }
501
+ )
502
+
503
+ # Check that the user was redirected to the account page
504
+ self.assertRedirects(response, reverse("wagtailadmin_account"))
505
+
506
+ profile = UserProfile.get_for_user(self.user)
507
+ profile.refresh_from_db()
508
+
509
+ # Check that the current time zone are stored
510
+ self.assertEqual(profile.current_time_zone, "")
511
+
512
+ @unittest.skipUnless(settings.USE_TZ, "Timezone support is disabled")
513
+ @override_settings(
514
+ WAGTAIL_USER_TIME_ZONES=["Africa/Addis_Ababa", "America/Argentina/Buenos_Aires"]
515
+ )
516
+ def test_available_admin_time_zones_with_permitted_time_zones(self):
517
+ self.assertListEqual(
518
+ get_available_admin_time_zones(),
519
+ ["Africa/Addis_Ababa", "America/Argentina/Buenos_Aires"],
520
+ )
521
+
522
+ @unittest.skipUnless(settings.USE_TZ, "Timezone support is disabled")
523
+ def test_available_admin_time_zones_by_default(self):
524
+ self.assertListEqual(get_available_admin_time_zones(), pytz.common_timezones)
525
+
526
+ @unittest.skipUnless(settings.USE_TZ, "Timezone support is disabled")
527
+ @override_settings(WAGTAIL_USER_TIME_ZONES=["Europe/London"])
528
+ def test_not_show_options_if_only_one_time_zone_is_permitted(self):
529
+ response = self.client.get(reverse("wagtailadmin_account"))
530
+ self.assertNotContains(response, "Current time zone")
531
+
532
+ @unittest.skipIf(settings.USE_TZ, "Timezone support is enabled")
533
+ def test_not_show_options_if_timezone_support_disabled(self):
534
+ response = self.client.get(reverse("wagtailadmin_account"))
535
+ self.assertNotContains(response, "Current time zone")
536
+
537
+ @unittest.skipUnless(settings.USE_TZ, "Timezone support is disabled")
538
+ @override_settings(
539
+ WAGTAIL_USER_TIME_ZONES=["Europe/London"],
540
+ WAGTAILADMIN_PERMITTED_LANGUAGES=[("en", "English")],
541
+ )
542
+ def test_doesnt_render_locale_panel_when_only_one_timezone_and_one_locale_permitted(
543
+ self,
544
+ ):
545
+ response = self.client.get(reverse("wagtailadmin_account"))
546
+ self.assertPanelNotActive(response, "locale")
547
+
548
+ def test_sensitive_post_parameters(self):
549
+ request = RequestFactory().post("wagtailadmin_account", data={})
550
+ request.user = self.user
551
+ account(request)
552
+ self.assertTrue(hasattr(request, "sensitive_post_parameters"))
553
+ self.assertEqual(request.sensitive_post_parameters, "__ALL__")
554
+
555
+
556
+ class TestAccountUploadAvatar(TestCase, WagtailTestUtils, TestAccountSectionUtilsMixin):
557
+ def setUp(self):
558
+ self.user = self.login()
559
+ self.avatar = get_test_image_file()
560
+ self.other_avatar = get_test_image_file()
561
+
562
+ def test_account_view(self):
563
+ """
564
+ This tests that the account view renders a "Upload a profile picture" field
565
+ """
566
+ response = self.client.get(reverse("wagtailadmin_account"))
567
+
568
+ self.assertEqual(response.status_code, 200)
569
+ self.assertContains(response, "Upload a profile picture")
570
+
571
+ def test_set_custom_avatar_stores_and_get_custom_avatar(self):
572
+ response = self.post_form(
573
+ {
574
+ "avatar-avatar": SimpleUploadedFile(
575
+ "other.png", self.other_avatar.file.getvalue()
576
+ )
577
+ }
578
+ )
579
+ # Check that the user was redirected to the account page
580
+ self.assertRedirects(response, reverse("wagtailadmin_account"))
581
+
582
+ profile = UserProfile.get_for_user(self.user)
583
+ profile.refresh_from_db()
584
+ self.assertIn("other.png", profile.avatar.url)
585
+
586
+ def test_user_upload_another_image_removes_previous_one(self):
587
+ profile = UserProfile.get_for_user(self.user)
588
+ profile.avatar = self.avatar
589
+ profile.save()
590
+
591
+ old_avatar_path = profile.avatar.path
592
+
593
+ # Upload a new avatar
594
+ response = self.post_form(
595
+ {
596
+ "avatar-avatar": SimpleUploadedFile(
597
+ "other.png", self.other_avatar.file.getvalue()
598
+ )
599
+ }
600
+ )
601
+ # Check that the user was redirected to the account page
602
+ self.assertRedirects(response, reverse("wagtailadmin_account"))
603
+
604
+ # Check the avatar was changed
605
+ profile.refresh_from_db()
606
+ self.assertIn("other.png", profile.avatar.url)
607
+
608
+ # Check old avatar doesn't exist anymore in filesystem
609
+ with self.assertRaises(FileNotFoundError):
610
+ open(old_avatar_path)
611
+
612
+ def test_no_value_preserves_current_avatar(self):
613
+ """
614
+ Tests that submitting a blank value for avatar doesn't remove it.
615
+ """
616
+ profile = UserProfile.get_for_user(self.user)
617
+ profile.avatar = self.avatar
618
+ profile.save()
619
+
620
+ # Upload a new avatar
621
+ response = self.post_form({})
622
+ # Check that the user was redirected to the account page
623
+ self.assertRedirects(response, reverse("wagtailadmin_account"))
624
+
625
+ # Check the avatar was changed
626
+ profile.refresh_from_db()
627
+ self.assertIn("test.png", profile.avatar.url)
628
+
629
+ def test_clear_removes_current_avatar(self):
630
+ """
631
+ Tests that submitting a blank value for avatar doesn't remove it.
632
+ """
633
+ profile = UserProfile.get_for_user(self.user)
634
+ profile.avatar = self.avatar
635
+ profile.save()
636
+
637
+ # Upload a new avatar
638
+ response = self.post_form({"avatar-clear": "on"})
639
+ # Check that the user was redirected to the account page
640
+ self.assertRedirects(response, reverse("wagtailadmin_account"))
641
+
642
+ # Check the avatar was changed
643
+ profile.refresh_from_db()
644
+ self.assertIn("test.png", profile.avatar.url)
645
+
646
+
647
+ class TestAccountManagementForNonModerator(TestCase, WagtailTestUtils):
648
+ """
649
+ Tests of reduced-functionality for editors
650
+ """
651
+
652
+ def setUp(self):
653
+ # Create a non-moderator user
654
+ self.submitter = self.create_user(
655
+ "submitter", "submitter@example.com", "password"
656
+ )
657
+ self.submitter.groups.add(Group.objects.get(name="Editors"))
658
+
659
+ self.login(username="submitter", password="password")
660
+
661
+ def test_notification_preferences_panel_reduced_for_non_moderators(self):
662
+ """
663
+ This tests that a user without publish permissions is not shown the
664
+ notification preference for 'submitted' items
665
+ """
666
+ response = self.client.get(reverse("wagtailadmin_account"))
667
+
668
+ # Find notifications panel through context
669
+ notifications_panel = None
670
+ for panelset in response.context["panels_by_tab"].values():
671
+ for panel in panelset:
672
+ if panel.name == "notifications":
673
+ notifications_panel = panel
674
+ break
675
+
676
+ notifications_form = notifications_panel.get_form()
677
+ self.assertIn("approved_notifications", notifications_form.fields.keys())
678
+ self.assertIn("rejected_notifications", notifications_form.fields.keys())
679
+ self.assertNotIn("submitted_notifications", notifications_form.fields.keys())
680
+ self.assertIn(
681
+ "updated_comments_notifications", notifications_form.fields.keys()
682
+ )
683
+
684
+
685
+ class TestAccountManagementForAdminOnlyUser(
686
+ TestCase, WagtailTestUtils, TestAccountSectionUtilsMixin
687
+ ):
688
+ """
689
+ Tests for users with no edit/publish permissions at all
690
+ """
691
+
692
+ def setUp(self):
693
+ # Create a non-moderator user
694
+ admin_only_group = Group.objects.create(name="Admin Only")
695
+ admin_only_group.permissions.add(
696
+ Permission.objects.get(codename="access_admin")
697
+ )
698
+
699
+ self.admin_only_user = self.create_user(
700
+ "admin_only_user", "admin_only_user@example.com", "password"
701
+ )
702
+ self.admin_only_user.groups.add(admin_only_group)
703
+
704
+ self.login(username="admin_only_user", password="password")
705
+
706
+ def test_notification_preferences_not_rendered_for_admin_only_users(self):
707
+ """
708
+ Test that the user is not shown the notification preferences panel
709
+ """
710
+ response = self.client.get(reverse("wagtailadmin_account"))
711
+ self.assertPanelNotActive(response, "notifications")
712
+
713
+
714
+ class TestPasswordReset(TestCase, WagtailTestUtils):
715
+ """
716
+ This tests that the password reset is working
717
+ """
718
+
719
+ def setUp(self):
720
+ # Create a user
721
+ self.create_superuser(
722
+ username="test", email="test@email.com", password="password"
723
+ )
724
+
725
+ def test_password_reset_view(self):
726
+ """
727
+ This tests that the password reset view returns a password reset page
728
+ """
729
+ # Get password reset page
730
+ response = self.client.get(reverse("wagtailadmin_password_reset"))
731
+
732
+ # Check that the user received a password reset page
733
+ self.assertEqual(response.status_code, 200)
734
+ self.assertTemplateUsed(
735
+ response, "wagtailadmin/account/password_reset/form.html"
736
+ )
737
+
738
+ def test_password_reset_view_post(self):
739
+ """
740
+ This posts an email address to the password reset view and
741
+ checks that a password reset email was sent
742
+ """
743
+ # Post email address to password reset view
744
+ post_data = {
745
+ "email": "test@email.com",
746
+ }
747
+ response = self.client.post(reverse("wagtailadmin_password_reset"), post_data)
748
+
749
+ # Check that the user was redirected to the done page
750
+ self.assertRedirects(response, reverse("wagtailadmin_password_reset_done"))
751
+
752
+ # Check that a password reset email was sent to the user
753
+ self.assertEqual(len(mail.outbox), 1)
754
+ self.assertEqual(mail.outbox[0].to, ["test@email.com"])
755
+ self.assertEqual(mail.outbox[0].subject, "Password reset")
756
+
757
+ def test_password_reset_view_post_unknown_email(self):
758
+ """
759
+ This posts an unknown email address to the password reset view and
760
+ checks that the password reset form raises a validation error
761
+ """
762
+ post_data = {
763
+ "email": "unknown@email.com",
764
+ }
765
+ response = self.client.post(reverse("wagtailadmin_password_reset"), post_data)
766
+
767
+ # Check that the user was redirected to the done page
768
+ self.assertRedirects(response, reverse("wagtailadmin_password_reset_done"))
769
+
770
+ # Check that an email was not sent
771
+ self.assertEqual(len(mail.outbox), 0)
772
+
773
+ def test_password_reset_view_post_invalid_email(self):
774
+ """
775
+ This posts an invalid email address to the password reset view and
776
+ checks that the password reset form raises a validation error
777
+ """
778
+ post_data = {
779
+ "email": "Hello world!",
780
+ }
781
+ response = self.client.post(reverse("wagtailadmin_password_reset"), post_data)
782
+
783
+ # Check that the user wasn't redirected
784
+ self.assertEqual(response.status_code, 200)
785
+
786
+ # Check that a validation error was raised
787
+ self.assertIn("email", response.context["form"].errors.keys())
788
+ self.assertIn(
789
+ "Enter a valid email address.", response.context["form"].errors["email"]
790
+ )
791
+
792
+ # Check that an email was not sent
793
+ self.assertEqual(len(mail.outbox), 0)
794
+
795
+ def setup_password_reset_confirm_tests(self):
796
+ from django.utils.encoding import force_bytes, force_str
797
+ from django.utils.http import urlsafe_base64_encode
798
+
799
+ # Get user
800
+ self.user = get_user_model().objects.get(email="test@email.com")
801
+
802
+ # Generate a password reset token
803
+ self.password_reset_token = PasswordResetTokenGenerator().make_token(self.user)
804
+
805
+ # Generate a password reset uid
806
+ self.password_reset_uid = force_str(
807
+ urlsafe_base64_encode(force_bytes(self.user.pk))
808
+ )
809
+
810
+ # Create url_args
811
+ token = auth_views.PasswordResetConfirmView.reset_url_token
812
+
813
+ self.url_kwargs = {"uidb64": self.password_reset_uid, "token": token}
814
+
815
+ # Add token to session object
816
+ s = self.client.session
817
+ s.update(
818
+ {
819
+ auth_views.INTERNAL_RESET_SESSION_TOKEN: self.password_reset_token,
820
+ }
821
+ )
822
+ s.save()
823
+
824
+ def test_password_reset_confirm_view_invalid_link(self):
825
+ """
826
+ This tests that the password reset view shows an error message if the link is invalid
827
+ """
828
+ self.setup_password_reset_confirm_tests()
829
+
830
+ # Create invalid url_args
831
+ self.url_kwargs = {"uidb64": self.password_reset_uid, "token": "invalid-token"}
832
+
833
+ # Get password reset confirm page
834
+ response = self.client.get(
835
+ reverse("wagtailadmin_password_reset_confirm", kwargs=self.url_kwargs)
836
+ )
837
+
838
+ # Check that the user received a password confirm done page
839
+ self.assertEqual(response.status_code, 200)
840
+ self.assertTemplateUsed(
841
+ response, "wagtailadmin/account/password_reset/confirm.html"
842
+ )
843
+ self.assertFalse(response.context["validlink"])
844
+ self.assertContains(
845
+ response,
846
+ "The password reset link was invalid, possibly because it has already been used.",
847
+ )
848
+ self.assertContains(response, "Request a new password reset")
849
+
850
+ def test_password_reset_confirm_view(self):
851
+ """
852
+ This tests that the password reset confirm view returns a password reset confirm page
853
+ """
854
+ self.setup_password_reset_confirm_tests()
855
+
856
+ # Get password reset confirm page
857
+ response = self.client.get(
858
+ reverse("wagtailadmin_password_reset_confirm", kwargs=self.url_kwargs)
859
+ )
860
+
861
+ # Check that the user received a password confirm done page
862
+ self.assertEqual(response.status_code, 200)
863
+ self.assertTemplateUsed(
864
+ response, "wagtailadmin/account/password_reset/confirm.html"
865
+ )
866
+
867
+ def test_password_reset_confirm_view_post(self):
868
+ """
869
+ This posts a new password to the password reset confirm view and checks
870
+ that the users password was changed
871
+ """
872
+ self.setup_password_reset_confirm_tests()
873
+
874
+ # Post new password to change password page
875
+ post_data = {
876
+ "new_password1": "newpassword",
877
+ "new_password2": "newpassword",
878
+ }
879
+ response = self.client.post(
880
+ reverse("wagtailadmin_password_reset_confirm", kwargs=self.url_kwargs),
881
+ post_data,
882
+ )
883
+
884
+ # Check that the user was redirected to the complete page
885
+ self.assertRedirects(response, reverse("wagtailadmin_password_reset_complete"))
886
+
887
+ # Check that the password was changed
888
+ self.assertTrue(
889
+ get_user_model()
890
+ .objects.get(email="test@email.com")
891
+ .check_password("newpassword")
892
+ )
893
+
894
+ def test_password_reset_confirm_view_post_password_mismatch(self):
895
+ """
896
+ This posts a two passwords that don't match to the password reset
897
+ confirm view and checks that a validation error was raised
898
+ """
899
+ self.setup_password_reset_confirm_tests()
900
+
901
+ # Post new password to change password page
902
+ post_data = {
903
+ "new_password1": "newpassword",
904
+ "new_password2": "badpassword",
905
+ }
906
+ response = self.client.post(
907
+ reverse("wagtailadmin_password_reset_confirm", kwargs=self.url_kwargs),
908
+ post_data,
909
+ )
910
+
911
+ # Check that the user wasn't redirected
912
+ self.assertEqual(response.status_code, 200)
913
+
914
+ # Check that a validation error was raised
915
+ self.assertIn("new_password2", response.context["form"].errors.keys())
916
+ self.assertIn(
917
+ "The two password fields didn’t match.",
918
+ response.context["form"].errors["new_password2"],
919
+ )
920
+
921
+ # Check that the password was not changed
922
+ self.assertTrue(
923
+ get_user_model()
924
+ .objects.get(email="test@email.com")
925
+ .check_password("password")
926
+ )
927
+
928
+ def test_password_reset_done_view(self):
929
+ """
930
+ This tests that the password reset done view returns a password reset done page
931
+ """
932
+ # Get password reset done page
933
+ response = self.client.get(reverse("wagtailadmin_password_reset_done"))
934
+
935
+ # Check that the user received a password reset done page
936
+ self.assertEqual(response.status_code, 200)
937
+ self.assertTemplateUsed(
938
+ response, "wagtailadmin/account/password_reset/done.html"
939
+ )
940
+
941
+ def test_password_reset_complete_view(self):
942
+ """
943
+ This tests that the password reset complete view returns a password reset complete page
944
+ """
945
+ # Get password reset complete page
946
+ response = self.client.get(reverse("wagtailadmin_password_reset_complete"))
947
+
948
+ # Check that the user received a password reset complete page
949
+ self.assertEqual(response.status_code, 200)
950
+ self.assertTemplateUsed(
951
+ response, "wagtailadmin/account/password_reset/complete.html"
952
+ )
testbed/wagtail__wagtail/wagtail/admin/tests/test_admin_search.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for the search box in the admin side menu, and the custom search hooks.
3
+ """
4
+ from django.contrib.auth.models import Permission
5
+ from django.template import Context, Template
6
+ from django.test import RequestFactory, TestCase
7
+ from django.urls import reverse
8
+
9
+ from wagtail.admin.auth import user_has_any_page_permission
10
+ from wagtail.test.utils import WagtailTestUtils
11
+
12
+
13
+ class BaseSearchAreaTestCase(WagtailTestUtils, TestCase):
14
+ rf = RequestFactory()
15
+
16
+ def search_other(self, current_url="/admin/", data=None):
17
+ request = self.rf.get(current_url, data=data)
18
+ request.user = self.user
19
+ template = Template("{% load wagtailadmin_tags %}{% search_other %}")
20
+ return template.render(Context({"request": request}))
21
+
22
+
23
+ class TestSearchAreas(BaseSearchAreaTestCase):
24
+ def setUp(self):
25
+ super().setUp()
26
+ self.user = self.login()
27
+
28
+ def test_other_searches(self):
29
+ search_url = reverse("wagtailadmin_pages:search")
30
+ query = "Hello"
31
+ base_css = "search--custom-class"
32
+ icon = '<svg class="icon icon-custom filter-options__icon" aria-hidden="true"><use href="#icon-custom"></use></svg>'
33
+ test_string = (
34
+ '<a href="/customsearch/?q=%s" class="%s" is-custom="true">%sMy Search</a>'
35
+ )
36
+ # Testing the option link exists
37
+ response = self.client.get(search_url, {"q": query})
38
+ self.assertEqual(response.status_code, 200)
39
+ self.assertTemplateUsed(response, "wagtailadmin/pages/search.html")
40
+ self.assertTemplateUsed(response, "wagtailadmin/shared/search_area.html")
41
+ self.assertTemplateUsed(response, "wagtailadmin/shared/search_other.html")
42
+ self.assertContains(response, test_string % (query, base_css, icon), html=True)
43
+
44
+ # Testing is_shown
45
+ response = self.client.get(search_url, {"q": query, "hide-option": "true"})
46
+ self.assertNotContains(
47
+ response, test_string % (query, base_css, icon), status_code=200, html=True
48
+ )
49
+
50
+ # Testing is_active
51
+ response = self.client.get(search_url, {"q": query, "active-option": "true"})
52
+ self.assertContains(
53
+ response,
54
+ test_string % (query, base_css + " nolink", icon),
55
+ status_code=200,
56
+ html=True,
57
+ )
58
+
59
+ def test_search_other(self):
60
+ rendered = self.search_other()
61
+ self.assertIn(reverse("wagtailadmin_pages:search"), rendered)
62
+ self.assertIn("/customsearch/", rendered)
63
+
64
+ self.assertIn("Pages", rendered)
65
+ self.assertIn("My Search", rendered)
66
+
67
+
68
+ class TestSearchAreaNoPagePermissions(BaseSearchAreaTestCase):
69
+ """
70
+ Test the admin search when the user does not have permission to manage
71
+ pages. The search bar should show the first available search area instead.
72
+ """
73
+
74
+ def setUp(self):
75
+ self.user = self.login()
76
+ self.assertFalse(user_has_any_page_permission(self.user))
77
+
78
+ def create_test_user(self):
79
+ user = super().create_test_user()
80
+ user.is_superuser = False
81
+ user.user_permissions.add(
82
+ Permission.objects.get(
83
+ content_type__app_label="wagtailadmin", codename="access_admin"
84
+ )
85
+ )
86
+ user.save()
87
+ return user
88
+
89
+ def test_dashboard(self):
90
+ """
91
+ Check that the menu search area on the dashboard is not searching
92
+ pages, as they are not allowed.
93
+ """
94
+ response = self.client.get("/admin/")
95
+ # The menu search bar should go to /customsearch/, not /admin/pages/search/
96
+ self.assertNotContains(response, reverse("wagtailadmin_pages:search"))
97
+ self.assertContains(
98
+ response,
99
+ '{"_type": "wagtail.sidebar.SearchModule", "_args": ["/customsearch/"]}',
100
+ )
101
+
102
+ def test_search_other(self):
103
+ """The pages search link should be hidden, custom search should be visible."""
104
+ rendered = self.search_other()
105
+ self.assertNotIn(reverse("wagtailadmin_pages:search"), rendered)
106
+ self.assertIn("/customsearch/", rendered)
107
+
108
+ self.assertNotIn("Pages", rendered)
109
+ self.assertIn("My Search", rendered)
testbed/wagtail__wagtail/wagtail/admin/tests/test_audit_log.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import timedelta
2
+
3
+ from django.contrib.auth.models import Group, Permission
4
+ from django.test import TestCase
5
+ from django.urls import reverse
6
+ from django.utils import timezone
7
+ from freezegun import freeze_time
8
+
9
+ from wagtail.models import GroupPagePermission, Page, PageLogEntry, PageViewRestriction
10
+ from wagtail.test.testapp.models import SimplePage
11
+ from wagtail.test.utils import WagtailTestUtils
12
+
13
+
14
+ class TestAuditLogAdmin(TestCase, WagtailTestUtils):
15
+ def setUp(self):
16
+ self.root_page = Page.objects.get(id=2)
17
+
18
+ self.hello_page = SimplePage(
19
+ title="Hello world!",
20
+ slug="hello-world",
21
+ content="hello",
22
+ live=False,
23
+ )
24
+ self.root_page.add_child(instance=self.hello_page)
25
+
26
+ self.about_page = SimplePage(title="About", slug="about", content="hello")
27
+ self.root_page.add_child(instance=self.about_page)
28
+
29
+ self.administrator = self.create_superuser(
30
+ username="administrator",
31
+ email="administrator@email.com",
32
+ password="password",
33
+ )
34
+ self.editor = self.create_user(
35
+ username="the_editor", email="the_editor@example.com", password="password"
36
+ )
37
+ sub_editors = Group.objects.create(name="Sub editors")
38
+ sub_editors.permissions.add(
39
+ Permission.objects.get(
40
+ content_type__app_label="wagtailadmin", codename="access_admin"
41
+ )
42
+ )
43
+ self.editor.groups.add(sub_editors)
44
+
45
+ for permission_type in ["add", "edit", "publish"]:
46
+ GroupPagePermission.objects.create(
47
+ group=sub_editors, page=self.hello_page, permission_type=permission_type
48
+ )
49
+
50
+ def _update_page(self, page):
51
+ # save revision
52
+ page.save_revision(user=self.editor, log_action=True)
53
+ # schedule for publishing
54
+ page.go_live_at = timezone.now() + timedelta(seconds=1)
55
+ revision = page.save_revision(user=self.editor, log_action=True)
56
+ revision.publish(user=self.editor)
57
+
58
+ # publish
59
+ with freeze_time(timezone.now() + timedelta(seconds=2)):
60
+ revision.publish(user=self.editor)
61
+
62
+ # lock/unlock
63
+ page.save(user=self.editor, log_action="wagtail.lock")
64
+ page.save(user=self.editor, log_action="wagtail.unlock")
65
+
66
+ # change privacy
67
+ restriction = PageViewRestriction(
68
+ page=page, restriction_type=PageViewRestriction.LOGIN
69
+ )
70
+ restriction.save(user=self.editor)
71
+ restriction.restriction_type = PageViewRestriction.PASSWORD
72
+ restriction.save(user=self.administrator)
73
+ restriction.delete()
74
+
75
+ def test_page_history(self):
76
+ self._update_page(self.hello_page)
77
+
78
+ history_url = reverse(
79
+ "wagtailadmin_pages:history", kwargs={"page_id": self.hello_page.id}
80
+ )
81
+
82
+ self.login(user=self.editor)
83
+
84
+ response = self.client.get(history_url)
85
+ self.assertEqual(response.status_code, 200)
86
+
87
+ self.assertContains(response, "Created", 1)
88
+ self.assertContains(response, "Draft saved", 2)
89
+ self.assertContains(response, "Locked", 1)
90
+ self.assertContains(response, "Unlocked", 1)
91
+ self.assertContains(response, "Page scheduled for publishing", 1)
92
+ self.assertContains(response, "Published", 1)
93
+
94
+ self.assertContains(
95
+ response,
96
+ "Added the &#x27;Private, accessible to logged-in users&#x27; view restriction",
97
+ )
98
+ self.assertContains(
99
+ response,
100
+ "Updated the view restriction to &#x27;Private, accessible with the following password&#x27;",
101
+ )
102
+ self.assertContains(
103
+ response,
104
+ "Removed the &#x27;Private, accessible with the following password&#x27; view restriction",
105
+ )
106
+
107
+ self.assertContains(
108
+ response, "system", 2
109
+ ) # create without a user + remove restriction
110
+ self.assertContains(
111
+ response, "the_editor", 9
112
+ ) # 7 entries by editor + 1 in sidebar menu + 1 in filter
113
+ self.assertContains(
114
+ response, "administrator", 2
115
+ ) # the final restriction change + filter
116
+
117
+ def test_page_history_filters(self):
118
+ self.login(user=self.editor)
119
+ self._update_page(self.hello_page)
120
+
121
+ history_url = reverse(
122
+ "wagtailadmin_pages:history", kwargs={"page_id": self.hello_page.id}
123
+ )
124
+ response = self.client.get(history_url + "?action=wagtail.edit")
125
+ self.assertEqual(response.status_code, 200)
126
+ self.assertContains(response, "Draft saved", count=2)
127
+ self.assertNotContains(response, "Locked")
128
+ self.assertNotContains(response, "Unlocked")
129
+ self.assertNotContains(response, "Page scheduled for publishing")
130
+ self.assertNotContains(response, "Published")
131
+
132
+ def test_site_history(self):
133
+ self._update_page(self.hello_page)
134
+ self.about_page.save_revision(user=self.administrator, log_action=True)
135
+ self.about_page.delete(user=self.administrator)
136
+
137
+ site_history_url = reverse("wagtailadmin_reports:site_history")
138
+
139
+ # the editor has access to the root page, so should see everything
140
+ self.login(user=self.editor)
141
+
142
+ response = self.client.get(site_history_url)
143
+ self.assertEqual(response.status_code, 200)
144
+
145
+ self.assertNotContains(response, "About")
146
+ self.assertContains(response, "Draft saved", 2)
147
+ self.assertNotContains(response, "Deleted")
148
+
149
+ # once a page is deleted, its log entries are only visible to super admins or users with
150
+ # permissions on the root page
151
+ self.hello_page.delete(user=self.administrator)
152
+ response = self.client.get(site_history_url)
153
+ self.assertContains(response, "No log entries found")
154
+
155
+ # add the editor user to the Editors group which has permissions on the root page
156
+ self.editor.groups.add(Group.objects.get(name="Editors"))
157
+ response = self.client.get(site_history_url)
158
+
159
+ self.assertContains(response, "About", 3) # create, save draft, delete
160
+ self.assertContains(response, "Created", 2)
161
+ self.assertContains(response, "Deleted", 2)
162
+
163
+ # check with super admin
164
+ self.login(user=self.administrator)
165
+ response = self.client.get(site_history_url)
166
+
167
+ self.assertContains(response, "About", 3) # create, save draft, delete
168
+ self.assertContains(response, "Deleted", 2)
169
+
170
+ def test_history_with_deleted_user(self):
171
+ self._update_page(self.hello_page)
172
+
173
+ expected_deleted_string = f"user {self.editor.pk} (deleted)"
174
+ self.editor.delete()
175
+
176
+ self.login(user=self.administrator)
177
+
178
+ # check page history
179
+ response = self.client.get(
180
+ reverse(
181
+ "wagtailadmin_pages:history", kwargs={"page_id": self.hello_page.id}
182
+ )
183
+ )
184
+ self.assertContains(response, expected_deleted_string)
185
+
186
+ # check site history
187
+ response = self.client.get(reverse("wagtailadmin_reports:site_history"))
188
+ self.assertContains(response, expected_deleted_string)
189
+
190
+ def test_edit_form_has_history_link(self):
191
+ self.hello_page.save_revision()
192
+ self.login(user=self.editor)
193
+ response = self.client.get(
194
+ reverse("wagtailadmin_pages:edit", args=[self.hello_page.id])
195
+ )
196
+ self.assertEqual(response.status_code, 200)
197
+ history_url = reverse("wagtailadmin_pages:history", args=[self.hello_page.id])
198
+ self.assertContains(response, history_url)
199
+
200
+ def test_create_and_publish_logs_revision_save(self):
201
+ self.login(user=self.administrator)
202
+ post_data = {
203
+ "title": "New page!",
204
+ "content": "Some content",
205
+ "slug": "hello-world-redux",
206
+ "action-publish": "action-publish",
207
+ }
208
+ response = self.client.post(
209
+ reverse(
210
+ "wagtailadmin_pages:add",
211
+ args=("tests", "simplepage", self.root_page.id),
212
+ ),
213
+ post_data,
214
+ follow=True,
215
+ )
216
+ self.assertEqual(response.status_code, 200)
217
+
218
+ page_id = Page.objects.get(
219
+ path__startswith=self.root_page.path, slug="hello-world-redux"
220
+ ).id
221
+
222
+ self.assertListEqual(
223
+ list(
224
+ PageLogEntry.objects.filter(page=page_id)
225
+ .values_list("action", flat=True)
226
+ .order_by("action")
227
+ ),
228
+ ["wagtail.create", "wagtail.edit", "wagtail.publish"],
229
+ )
230
+
231
+ def test_revert_and_publish_logs_reversion_and_publish(self):
232
+ revision = self.hello_page.save_revision(user=self.editor)
233
+ self.hello_page.save_revision(user=self.editor)
234
+
235
+ self.login(user=self.administrator)
236
+ response = self.client.post(
237
+ reverse("wagtailadmin_pages:edit", args=(self.hello_page.id,)),
238
+ {
239
+ "title": "Hello World!",
240
+ "content": "another hello",
241
+ "slug": "hello-world",
242
+ "revision": revision.id,
243
+ "action-publish": "action-publish",
244
+ },
245
+ follow=True,
246
+ )
247
+ self.assertEqual(response.status_code, 200)
248
+
249
+ entries = (
250
+ PageLogEntry.objects.filter(page=self.hello_page)
251
+ .values_list("action", flat=True)
252
+ .order_by("action")
253
+ )
254
+ self.assertListEqual(
255
+ list(entries),
256
+ ["wagtail.create", "wagtail.publish", "wagtail.rename", "wagtail.revert"],
257
+ )
testbed/wagtail__wagtail/wagtail/admin/tests/test_buttons_hooks.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.test import TestCase
2
+ from django.urls import reverse
3
+ from django.utils.http import urlencode
4
+
5
+ from wagtail import hooks
6
+ from wagtail.admin import widgets as wagtailadmin_widgets
7
+ from wagtail.admin.wagtail_hooks import page_header_buttons, page_listing_more_buttons
8
+ from wagtail.models import Page
9
+ from wagtail.test.testapp.models import SimplePage
10
+ from wagtail.test.utils import WagtailTestUtils
11
+
12
+
13
+ class BasePagePerms:
14
+ def can_move(self):
15
+ return False
16
+
17
+ def can_copy(self):
18
+ return False
19
+
20
+ def can_edit(self):
21
+ return False
22
+
23
+ def can_delete(self):
24
+ return False
25
+
26
+ def can_unpublish(self):
27
+ return False
28
+
29
+ def can_view_revisions(self):
30
+ return False
31
+
32
+ def can_reorder_children(self):
33
+ return False
34
+
35
+ def can_add_subpage(self):
36
+ return False
37
+
38
+
39
+ class DeleteOnlyPagePerms(BasePagePerms):
40
+ def can_delete(self):
41
+ return True
42
+
43
+
44
+ class DeleteAndUnpublishPagePerms(BasePagePerms):
45
+ def can_delete(self):
46
+ return True
47
+
48
+ def can_unpublish(self):
49
+ return True
50
+
51
+
52
+ class ReorderOnlyPagePerms(BasePagePerms):
53
+ def can_reorder_children(self):
54
+ return True
55
+
56
+
57
+ class TestButtonsHooks(TestCase, WagtailTestUtils):
58
+ def setUp(self):
59
+ self.login()
60
+
61
+ self.root_page = Page.objects.get(id=2)
62
+ self.child_page = self.root_page.add_child(
63
+ instance=SimplePage(
64
+ title="Public page",
65
+ content="hello",
66
+ live=True,
67
+ )
68
+ )
69
+
70
+
71
+ class TestPageListingButtonsHooks(TestButtonsHooks):
72
+ def test_register_page_listing_buttons(self):
73
+ def page_listing_buttons(page, page_perms, next_url=None):
74
+ yield wagtailadmin_widgets.PageListingButton(
75
+ "Another useless page listing button", "/custom-url", priority=10
76
+ )
77
+
78
+ with hooks.register_temporarily(
79
+ "register_page_listing_buttons", page_listing_buttons
80
+ ):
81
+ response = self.client.get(
82
+ reverse("wagtailadmin_explore", args=(self.root_page.id,))
83
+ )
84
+
85
+ self.assertEqual(response.status_code, 200)
86
+ self.assertTemplateUsed(
87
+ response, "wagtailadmin/pages/listing/_button_with_dropdown.html"
88
+ )
89
+ self.assertTemplateUsed(response, "wagtailadmin/pages/listing/_buttons.html")
90
+
91
+ self.assertContains(response, "Another useless page listing button")
92
+
93
+
94
+ class TestPageListingMoreButtonsHooks(TestButtonsHooks):
95
+ def test_register_page_listing_more_buttons(self):
96
+ def page_listing_more_buttons(page, page_perms, next_url=None):
97
+ yield wagtailadmin_widgets.Button(
98
+ 'Another useless button in default "More" dropdown',
99
+ "/custom-url",
100
+ priority=10,
101
+ )
102
+
103
+ with hooks.register_temporarily(
104
+ "register_page_listing_more_buttons", page_listing_more_buttons
105
+ ):
106
+ response = self.client.get(
107
+ reverse("wagtailadmin_explore", args=(self.root_page.id,))
108
+ )
109
+
110
+ self.assertEqual(response.status_code, 200)
111
+ self.assertTemplateUsed(
112
+ response, "wagtailadmin/pages/listing/_button_with_dropdown.html"
113
+ )
114
+ self.assertTemplateUsed(response, "wagtailadmin/pages/listing/_buttons.html")
115
+
116
+ self.assertContains(
117
+ response, "Another useless button in default &quot;More&quot; dropdown"
118
+ )
119
+
120
+ def test_custom_button_with_dropdown(self):
121
+ def page_custom_listing_buttons(page, page_perms, next_url=None):
122
+ yield wagtailadmin_widgets.ButtonWithDropdownFromHook(
123
+ "One more more button",
124
+ hook_name="register_page_listing_one_more_more_buttons",
125
+ page=page,
126
+ page_perms=page_perms,
127
+ next_url=next_url,
128
+ attrs={"target": "_blank", "rel": "noreferrer"},
129
+ priority=50,
130
+ )
131
+
132
+ def page_custom_listing_more_buttons(page, page_perms, next_url=None):
133
+ yield wagtailadmin_widgets.Button(
134
+ 'Another useless dropdown button in "One more more button" dropdown',
135
+ "/custom-url",
136
+ priority=10,
137
+ )
138
+
139
+ with hooks.register_temporarily(
140
+ "register_page_listing_buttons", page_custom_listing_buttons
141
+ ), hooks.register_temporarily(
142
+ "register_page_listing_one_more_more_buttons",
143
+ page_custom_listing_more_buttons,
144
+ ):
145
+ response = self.client.get(
146
+ reverse("wagtailadmin_explore", args=(self.root_page.id,))
147
+ )
148
+
149
+ self.assertEqual(response.status_code, 200)
150
+ self.assertTemplateUsed(
151
+ response, "wagtailadmin/pages/listing/_button_with_dropdown.html"
152
+ )
153
+ self.assertTemplateUsed(response, "wagtailadmin/pages/listing/_buttons.html")
154
+
155
+ self.assertContains(response, "One more more button")
156
+ self.assertContains(
157
+ response,
158
+ "Another useless dropdown button in &quot;One more more button&quot; dropdown",
159
+ )
160
+
161
+ def test_delete_button_with_next_url(self):
162
+ """
163
+ Ensure that the built in delete button supports a next_url provided.
164
+ """
165
+
166
+ # page_listing_more_button generator yields only `Delete button` with this permission set
167
+ page_perms = DeleteOnlyPagePerms()
168
+ page = self.root_page
169
+ base_url = reverse("wagtailadmin_pages:delete", args=[page.id])
170
+
171
+ next_url = "a/random/url/"
172
+ full_url = base_url + "?" + urlencode({"next": next_url})
173
+
174
+ delete_button = next(
175
+ page_listing_more_buttons(page, page_perms, next_url=next_url)
176
+ )
177
+
178
+ self.assertEqual(delete_button.url, full_url)
179
+
180
+ def test_delete_button_with_invalid_next_url(self):
181
+ """
182
+ Ensure that the built in delete button on page listing will not use
183
+ the next_url provided if that URL is directing the user to edit the page.
184
+ As the page is now deleted and cannot be edited.
185
+ """
186
+
187
+ # permissions should yield two buttons, delete and unpublish
188
+ page_perms = DeleteAndUnpublishPagePerms()
189
+ page = self.root_page
190
+
191
+ base_url = reverse("wagtailadmin_pages:delete", args=[page.id])
192
+ next_url = reverse("wagtailadmin_explore", args=[page.id])
193
+
194
+ buttons = page_listing_more_buttons(page, page_perms, next_url=next_url)
195
+
196
+ delete_button = next(buttons)
197
+
198
+ # check that the next_url is NOT included as it will not be available after deletion
199
+ self.assertEqual(delete_button.url, base_url)
200
+
201
+ # check that any buttons after do correctly still include the next_url
202
+ unpublish_base_url = reverse("wagtailadmin_pages:unpublish", args=[page.id])
203
+ unpublish_button = next(buttons)
204
+ full_url = unpublish_base_url + "?" + urlencode({"next": next_url})
205
+ self.assertEqual(unpublish_button.url, full_url)
206
+
207
+ def test_reorder_button_visibility(self):
208
+ page = self.root_page
209
+ page_perms = BasePagePerms()
210
+
211
+ # no button returned
212
+ buttons = page_listing_more_buttons(page, page_perms)
213
+ self.assertEqual(len(list(buttons)), 0)
214
+
215
+ page_perms = ReorderOnlyPagePerms()
216
+ # page_listing_more_button generator yields only `Sort menu order button`
217
+ reorder_button = next(page_listing_more_buttons(page, page_perms))
218
+
219
+ self.assertEqual(reorder_button.url, "?ordering=ord")
220
+
221
+
222
+ class TestPageHeaderButtonsHooks(TestButtonsHooks):
223
+ def test_register_page_header_buttons(self):
224
+ def custom_page_header_buttons(page, page_perms, next_url=None):
225
+ yield wagtailadmin_widgets.Button(
226
+ "Another useless header button", "/custom-url", priority=10
227
+ )
228
+
229
+ with hooks.register_temporarily(
230
+ "register_page_header_buttons", custom_page_header_buttons
231
+ ):
232
+ response = self.client.get(
233
+ reverse("wagtailadmin_pages:edit", args=(self.root_page.id,))
234
+ )
235
+
236
+ self.assertEqual(response.status_code, 200)
237
+ self.assertTemplateUsed(
238
+ response, "wagtailadmin/pages/listing/_modern_dropdown.html"
239
+ )
240
+
241
+ self.assertContains(response, "Another useless header button")
242
+
243
+ def test_delete_button_with_next_url(self):
244
+ """
245
+ Ensure that the built in delete button supports a next_url provided.
246
+ """
247
+
248
+ # page_listing_more_button generator yields only `Delete button` with this permission set
249
+ page_perms = DeleteOnlyPagePerms()
250
+ page = self.root_page
251
+ base_url = reverse("wagtailadmin_pages:delete", args=[page.id])
252
+
253
+ next_url = "a/random/url/"
254
+ full_url = base_url + "?" + urlencode({"next": next_url})
255
+
256
+ delete_button = next(page_header_buttons(page, page_perms, next_url=next_url))
257
+
258
+ self.assertEqual(delete_button.url, full_url)
259
+
260
+ def test_delete_button_with_invalid_next_url(self):
261
+ """
262
+ Ensure that the built in delete button on page edit/home (header button) will not use
263
+ the next_url provided if that URL is directing the user to edit the page.
264
+ As the page is now deleted and cannot be edited.
265
+ """
266
+
267
+ # permissions should yield two buttons, delete and unpublish
268
+ page_perms = DeleteAndUnpublishPagePerms()
269
+ page = self.root_page
270
+
271
+ base_url = reverse("wagtailadmin_pages:delete", args=[page.id])
272
+ next_url = reverse("wagtailadmin_explore", args=[page.id])
273
+
274
+ buttons = page_header_buttons(page, page_perms, next_url=next_url)
275
+
276
+ delete_button = next(buttons)
277
+
278
+ # check that the next_url is NOT included as it will not be available after deletion (page listing)
279
+ self.assertEqual(delete_button.url, base_url)
280
+
281
+ base_url = reverse("wagtailadmin_pages:delete", args=[page.id])
282
+ next_url = reverse("wagtailadmin_pages:edit", args=[page.id])
283
+
284
+ buttons = page_header_buttons(page, page_perms, next_url=next_url)
285
+
286
+ delete_button = next(buttons)
287
+
288
+ # check that the next_url is NOT included as it will not be available after deletion (edit page)
289
+ self.assertEqual(delete_button.url, base_url)
290
+
291
+ # check that any buttons after do correctly still include the next_url
292
+ unpublish_base_url = reverse("wagtailadmin_pages:unpublish", args=[page.id])
293
+ unpublish_button = next(buttons)
294
+ full_url = unpublish_base_url + "?" + urlencode({"next": next_url})
295
+ self.assertEqual(unpublish_button.url, full_url)
testbed/wagtail__wagtail/wagtail/admin/tests/test_collections_views.py ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.contrib.auth.models import Group, Permission
2
+ from django.contrib.contenttypes.models import ContentType
3
+ from django.test import TestCase
4
+ from django.urls import reverse
5
+
6
+ from wagtail.admin.admin_url_finder import AdminURLFinder
7
+ from wagtail.documents.models import Document
8
+ from wagtail.models import Collection, GroupCollectionPermission
9
+ from wagtail.test.utils import WagtailTestUtils
10
+
11
+
12
+ class CollectionInstanceTestUtils:
13
+ def setUp(self):
14
+ """
15
+ Common setup for testing collection views with per-instance permissions
16
+ """
17
+ collection_content_type = ContentType.objects.get_for_model(Collection)
18
+ self.add_permission = Permission.objects.get(
19
+ content_type=collection_content_type, codename="add_collection"
20
+ )
21
+ self.change_permission = Permission.objects.get(
22
+ content_type=collection_content_type, codename="change_collection"
23
+ )
24
+ self.delete_permission = Permission.objects.get(
25
+ content_type=collection_content_type, codename="delete_collection"
26
+ )
27
+ admin_permission = Permission.objects.get(codename="access_admin")
28
+
29
+ self.root_collection = Collection.get_first_root_node()
30
+ self.finance_collection = self.root_collection.add_child(name="Finance")
31
+ self.marketing_collection = self.root_collection.add_child(name="Marketing")
32
+ self.marketing_sub_collection = self.marketing_collection.add_child(
33
+ name="Digital Marketing"
34
+ )
35
+ self.marketing_sub_collection_2 = self.marketing_collection.add_child(
36
+ name="Direct Mail Marketing"
37
+ )
38
+
39
+ self.marketing_group = Group.objects.create(name="Marketing Group")
40
+ self.marketing_group.permissions.add(admin_permission)
41
+ self.marketing_user = self.create_user("marketing", password="password")
42
+ self.marketing_user.groups.add(self.marketing_group)
43
+
44
+
45
+ class TestCollectionsIndexViewAsSuperuser(TestCase, WagtailTestUtils):
46
+ def setUp(self):
47
+ self.login()
48
+
49
+ def get(self, params={}):
50
+ return self.client.get(reverse("wagtailadmin_collections:index"), params)
51
+
52
+ def test_simple(self):
53
+ response = self.get()
54
+ self.assertEqual(response.status_code, 200)
55
+ self.assertTemplateUsed(response, "wagtailadmin/collections/index.html")
56
+
57
+ # Initially there should be no collections listed
58
+ # (Root should not be shown)
59
+ self.assertContains(response, "No collections have been created.")
60
+
61
+ root_collection = Collection.get_first_root_node()
62
+ self.collection = root_collection.add_child(name="Holiday snaps")
63
+
64
+ # Now the listing should contain our collection
65
+ response = self.get()
66
+ self.assertEqual(response.status_code, 200)
67
+ self.assertTemplateUsed(response, "wagtailadmin/collections/index.html")
68
+ self.assertNotContains(response, "No collections have been created.")
69
+ self.assertContains(response, "Holiday snaps")
70
+
71
+ def test_ordering(self):
72
+ root_collection = Collection.get_first_root_node()
73
+ root_collection.add_child(name="Milk")
74
+ root_collection.add_child(name="Bread")
75
+ root_collection.add_child(name="Avocado")
76
+ response = self.get()
77
+ # Note that the Collections have been automatically sorted by name.
78
+ self.assertEqual(
79
+ [collection.name for collection in response.context["object_list"]],
80
+ ["Avocado", "Bread", "Milk"],
81
+ )
82
+
83
+ def test_nested_ordering(self):
84
+ root_collection = Collection.get_first_root_node()
85
+
86
+ vegetables = root_collection.add_child(name="Vegetable")
87
+ vegetables.add_child(name="Spinach")
88
+ vegetables.add_child(name="Cucumber")
89
+
90
+ animals = root_collection.add_child(name="Animal")
91
+ animals.add_child(name="Dog")
92
+ animals.add_child(name="Cat")
93
+
94
+ response = self.get()
95
+ # Note that while we added the collections at level 1 in reverse-alpha order, they come back out in alpha order.
96
+ # And we added the Collections at level 2 in reverse-alpha order as well, but they were also alphabetized
97
+ # within their respective trees. This is the result of setting Collection.node_order_by = ['name'].
98
+ self.assertEqual(
99
+ [collection.name for collection in response.context["object_list"]],
100
+ ["Animal", "Cat", "Dog", "Vegetable", "Cucumber", "Spinach"],
101
+ )
102
+
103
+
104
+ class TestCollectionsIndexView(CollectionInstanceTestUtils, TestCase, WagtailTestUtils):
105
+ def setUp(self):
106
+ super().setUp()
107
+ self.login(self.marketing_user, password="password")
108
+
109
+ def get(self, params={}):
110
+ return self.client.get(reverse("wagtailadmin_collections:index"), params)
111
+
112
+ def test_marketing_user_no_permissions(self):
113
+ response = self.get()
114
+ self.assertEqual(response.status_code, 302)
115
+ self.assertEqual(
116
+ response.context["message"],
117
+ "Sorry, you do not have permission to access this area.",
118
+ )
119
+
120
+ def test_marketing_user_with_change_permission(self):
121
+ # Grant the marketing group permission to make changes to their collections
122
+ GroupCollectionPermission.objects.create(
123
+ group=self.marketing_group,
124
+ collection=self.marketing_collection,
125
+ permission=self.change_permission,
126
+ )
127
+
128
+ response = self.get()
129
+ self.assertEqual(response.status_code, 200)
130
+ self.assertEqual(
131
+ [collection.name for collection in response.context["object_list"]],
132
+ ["Marketing", "Digital Marketing", "Direct Mail Marketing"],
133
+ )
134
+ self.assertNotContains(response, "Finance")
135
+ self.assertNotContains(response, "Add a collection")
136
+
137
+ def test_marketing_user_with_add_permission(self):
138
+ # Grant the marketing group permission to add to their collections
139
+ GroupCollectionPermission.objects.create(
140
+ group=self.marketing_group,
141
+ collection=self.marketing_collection,
142
+ permission=self.add_permission,
143
+ )
144
+
145
+ response = self.get()
146
+ self.assertEqual(response.status_code, 200)
147
+ self.assertEqual(
148
+ [collection.name for collection in response.context["object_list"]],
149
+ ["Marketing", "Digital Marketing", "Direct Mail Marketing"],
150
+ )
151
+ self.assertNotContains(response, "Finance")
152
+ self.assertContains(response, "Add a collection")
153
+
154
+ def test_marketing_user_with_delete_permission(self):
155
+ # Grant the marketing group permission to add to their collections
156
+ GroupCollectionPermission.objects.create(
157
+ group=self.marketing_group,
158
+ collection=self.marketing_collection,
159
+ permission=self.delete_permission,
160
+ )
161
+
162
+ response = self.get()
163
+ self.assertEqual(response.status_code, 200)
164
+ self.assertEqual(
165
+ [collection.name for collection in response.context["object_list"]],
166
+ ["Marketing", "Digital Marketing", "Direct Mail Marketing"],
167
+ )
168
+ self.assertNotContains(response, "Finance")
169
+ self.assertNotContains(response, "Add a collection")
170
+
171
+ def test_marketing_user_with_add_permission_on_root(self):
172
+ # Grant the marketing group permission to add to root collection
173
+ GroupCollectionPermission.objects.create(
174
+ group=self.marketing_group,
175
+ collection=self.root_collection,
176
+ permission=self.add_permission,
177
+ )
178
+
179
+ response = self.get()
180
+ self.assertEqual(response.status_code, 200)
181
+ # (Root should not be shown)
182
+ self.assertEqual(
183
+ [collection.name for collection in response.context["object_list"]],
184
+ ["Finance", "Marketing", "Digital Marketing", "Direct Mail Marketing"],
185
+ )
186
+ self.assertContains(response, "Add a collection")
187
+
188
+
189
+ class TestAddCollectionAsSuperuser(TestCase, WagtailTestUtils):
190
+ def setUp(self):
191
+ self.login()
192
+ self.root_collection = Collection.get_first_root_node()
193
+
194
+ def get(self, params={}):
195
+ return self.client.get(reverse("wagtailadmin_collections:add"), params)
196
+
197
+ def post(self, post_data={}):
198
+ return self.client.post(reverse("wagtailadmin_collections:add"), post_data)
199
+
200
+ def test_get(self):
201
+ response = self.get()
202
+ self.assertEqual(response.status_code, 200)
203
+ self.assertContains(response, self.root_collection.name)
204
+
205
+ def test_post(self):
206
+ response = self.post(
207
+ {
208
+ "name": "Holiday snaps",
209
+ "parent": self.root_collection.id,
210
+ }
211
+ )
212
+
213
+ # Should redirect back to index
214
+ self.assertRedirects(response, reverse("wagtailadmin_collections:index"))
215
+
216
+ # Check that the collection was created and is a child of root
217
+ self.assertEqual(Collection.objects.filter(name="Holiday snaps").count(), 1)
218
+ self.assertEqual(
219
+ Collection.objects.get(name="Holiday snaps").get_parent(),
220
+ self.root_collection,
221
+ )
222
+
223
+
224
+ class TestAddCollection(CollectionInstanceTestUtils, TestCase, WagtailTestUtils):
225
+ def setUp(self):
226
+ super().setUp()
227
+ self.login(self.marketing_user, password="password")
228
+
229
+ def get(self, params={}):
230
+ return self.client.get(reverse("wagtailadmin_collections:add"), params)
231
+
232
+ def post(self, post_data={}):
233
+ return self.client.post(reverse("wagtailadmin_collections:add"), post_data)
234
+
235
+ def test_marketing_user_no_permissions(self):
236
+ response = self.get()
237
+ self.assertEqual(response.status_code, 302)
238
+ self.assertEqual(
239
+ response.context["message"],
240
+ "Sorry, you do not have permission to access this area.",
241
+ )
242
+
243
+ def test_marketing_user_with_add_permission(self):
244
+ # Grant the marketing group permission to manage their collection
245
+ GroupCollectionPermission.objects.create(
246
+ group=self.marketing_group,
247
+ collection=self.marketing_collection,
248
+ permission=self.add_permission,
249
+ )
250
+
251
+ response = self.post(
252
+ {
253
+ "name": "Affiliate Marketing",
254
+ "parent": self.marketing_collection.id,
255
+ }
256
+ )
257
+
258
+ # Should redirect back to index
259
+ self.assertRedirects(response, reverse("wagtailadmin_collections:index"))
260
+
261
+ # Check that the collection was created and is a child of Marketing
262
+ self.assertEqual(
263
+ Collection.objects.filter(name="Affiliate Marketing").count(), 1
264
+ )
265
+ self.assertEqual(
266
+ Collection.objects.get(name="Affiliate Marketing").get_parent(),
267
+ self.marketing_collection,
268
+ )
269
+
270
+ def test_marketing_user_cannot_add_outside_their_hierarchy(self):
271
+ # Grant the marketing group permission to manage their collection
272
+ GroupCollectionPermission.objects.create(
273
+ group=self.marketing_group,
274
+ collection=self.marketing_collection,
275
+ permission=self.add_permission,
276
+ )
277
+
278
+ # This user can't add to root collection
279
+ response = self.post(
280
+ {
281
+ "name": "Affiliate Marketing",
282
+ "parent": self.root_collection.id,
283
+ }
284
+ )
285
+ self.assertEqual(
286
+ response.context["form"].errors["parent"],
287
+ ["Select a valid choice. That choice is not one of the available choices."],
288
+ )
289
+
290
+
291
+ class TestEditCollectionAsSuperuser(TestCase, WagtailTestUtils):
292
+ def setUp(self):
293
+ self.user = self.login()
294
+ self.root_collection = Collection.get_first_root_node()
295
+ self.collection = self.root_collection.add_child(name="Holiday snaps")
296
+ self.l1 = self.root_collection.add_child(name="Level 1")
297
+ self.l2 = self.l1.add_child(name="Level 2")
298
+ self.l3 = self.l2.add_child(name="Level 3")
299
+
300
+ def get(self, params={}, collection_id=None):
301
+ return self.client.get(
302
+ reverse(
303
+ "wagtailadmin_collections:edit",
304
+ args=(collection_id or self.collection.id,),
305
+ ),
306
+ params,
307
+ )
308
+
309
+ def post(self, post_data={}, collection_id=None):
310
+ return self.client.post(
311
+ reverse(
312
+ "wagtailadmin_collections:edit",
313
+ args=(collection_id or self.collection.id,),
314
+ ),
315
+ post_data,
316
+ )
317
+
318
+ def test_get(self):
319
+ response = self.get()
320
+ self.assertEqual(response.status_code, 200)
321
+ self.assertContains(response, "Delete collection")
322
+
323
+ def test_cannot_edit_root_collection(self):
324
+ response = self.get(collection_id=self.root_collection.id)
325
+ self.assertEqual(response.status_code, 404)
326
+
327
+ def test_admin_url_finder(self):
328
+ expected_url = "/admin/collections/%d/" % self.l2.pk
329
+ url_finder = AdminURLFinder(self.user)
330
+ self.assertEqual(url_finder.get_edit_url(self.l2), expected_url)
331
+
332
+ def test_get_nonexistent_collection(self):
333
+ response = self.get(collection_id=100000)
334
+ self.assertEqual(response.status_code, 404)
335
+
336
+ def test_move_collection(self):
337
+ self.post({"name": "Level 2", "parent": self.root_collection.pk}, self.l2.pk)
338
+ self.assertEqual(
339
+ Collection.objects.get(pk=self.l2.pk).get_parent().pk,
340
+ self.root_collection.pk,
341
+ )
342
+
343
+ def test_cannot_move_parent_collection_to_descendant(self):
344
+ response = self.post({"name": "Level 2", "parent": self.l3.pk}, self.l2.pk)
345
+ self.assertEqual(
346
+ response.context["message"],
347
+ "The collection could not be saved due to errors.",
348
+ )
349
+ self.assertContains(response, "Please select another parent")
350
+
351
+ def test_rename_collection(self):
352
+ data = {"name": "Skiing photos", "parent": self.root_collection.id}
353
+ response = self.post(data, self.collection.pk)
354
+
355
+ # Should redirect back to index
356
+ self.assertRedirects(response, reverse("wagtailadmin_collections:index"))
357
+
358
+ # Check that the collection was edited
359
+ self.assertEqual(
360
+ Collection.objects.get(id=self.collection.id).name, "Skiing photos"
361
+ )
362
+
363
+
364
+ class TestEditCollection(CollectionInstanceTestUtils, TestCase, WagtailTestUtils):
365
+ def setUp(self):
366
+ super().setUp()
367
+ # Grant the marketing group permission to edit their collection
368
+ self.users_change_permission = GroupCollectionPermission.objects.create(
369
+ group=self.marketing_group,
370
+ collection=self.marketing_collection,
371
+ permission=self.change_permission,
372
+ )
373
+ # Grant the marketing group permission to add collections under this collection
374
+ self.users_add_permission = GroupCollectionPermission.objects.create(
375
+ group=self.marketing_group,
376
+ collection=self.marketing_collection,
377
+ permission=self.add_permission,
378
+ )
379
+ self.login(self.marketing_user, password="password")
380
+
381
+ def get(self, collection_id, params={}):
382
+ return self.client.get(
383
+ reverse("wagtailadmin_collections:edit", args=(collection_id,)), params
384
+ )
385
+
386
+ def post(self, collection_id, post_data={}):
387
+ return self.client.post(
388
+ reverse("wagtailadmin_collections:edit", args=(collection_id,)), post_data
389
+ )
390
+
391
+ def test_marketing_user_no_change_permission(self):
392
+ self.users_change_permission.delete()
393
+ response = self.get(collection_id=self.marketing_collection.id)
394
+ self.assertEqual(response.status_code, 302)
395
+ self.assertEqual(
396
+ response.context["message"],
397
+ "Sorry, you do not have permission to access this area.",
398
+ )
399
+
400
+ def test_marketing_user_no_change_permission_post(self):
401
+ self.users_change_permission.delete()
402
+ response = self.post(self.marketing_collection.id, {})
403
+ self.assertEqual(response.status_code, 302)
404
+ self.assertEqual(
405
+ response.context["message"],
406
+ "Sorry, you do not have permission to access this area.",
407
+ )
408
+
409
+ def test_marketing_user_can_move_collection(self):
410
+ # Retrieve edit form and check fields
411
+ response = self.get(collection_id=self.marketing_sub_collection.id)
412
+ self.assertEqual(response.status_code, 200)
413
+ form_fields = response.context["form"].fields
414
+ self.assertEqual(type(form_fields["name"].widget).__name__, "TextInput")
415
+ self.assertEqual(
416
+ type(form_fields["parent"].widget).__name__, "SelectWithDisabledOptions"
417
+ )
418
+ # Now move the collection and check it did get moved and renamed
419
+ self.post(
420
+ self.marketing_sub_collection.pk,
421
+ {
422
+ "name": "New Collection Name",
423
+ "parent": self.marketing_sub_collection_2.pk,
424
+ },
425
+ )
426
+ self.assertEqual(
427
+ Collection.objects.get(pk=self.marketing_sub_collection.pk).name,
428
+ "New Collection Name",
429
+ )
430
+ self.assertEqual(
431
+ Collection.objects.get(pk=self.marketing_sub_collection.pk).get_parent(),
432
+ self.marketing_sub_collection_2,
433
+ )
434
+
435
+ def test_marketing_user_cannot_move_collection_if_no_add_permission(self):
436
+ self.users_add_permission.delete()
437
+ response = self.get(collection_id=self.marketing_sub_collection.id)
438
+ self.assertEqual(response.status_code, 200)
439
+ self.assertEqual(list(response.context["form"].fields.keys()), ["name"])
440
+ # Now try to move the collection and check it did not get moved
441
+
442
+ def test_marketing_user_cannot_move_collection_if_no_add_permission_post(self):
443
+ self.users_add_permission.delete()
444
+ self.post(
445
+ self.marketing_sub_collection.pk,
446
+ {
447
+ "name": "New Collection Name",
448
+ "parent": self.marketing_sub_collection_2.pk,
449
+ },
450
+ )
451
+ edited_collection = Collection.objects.get(pk=self.marketing_sub_collection.id)
452
+ self.assertEqual(edited_collection.name, "New Collection Name")
453
+ self.assertEqual(edited_collection.get_parent(), self.marketing_collection)
454
+
455
+ def test_cannot_move_parent_collection_to_descendant(self):
456
+ self.post(
457
+ self.marketing_collection.pk,
458
+ {
459
+ "name": "New Collection Name",
460
+ "parent": self.marketing_sub_collection_2.pk,
461
+ },
462
+ )
463
+ self.assertEqual(
464
+ Collection.objects.get(pk=self.marketing_collection.pk).get_parent(),
465
+ self.root_collection,
466
+ )
467
+
468
+ def test_marketing_user_cannot_move_collection_permissions_are_assigned_to(self):
469
+ response = self.get(collection_id=self.marketing_collection.id)
470
+ self.assertEqual(response.status_code, 200)
471
+ self.assertEqual(list(response.context["form"].fields.keys()), ["name"])
472
+ self.assertNotContains(response, "Delete collection")
473
+
474
+ def test_marketing_user_cannot_move_collection_permissions_are_assigned_to_post(
475
+ self,
476
+ ):
477
+ # Grant the marketing group permission to another collection so there is a valid destination
478
+ GroupCollectionPermission.objects.create(
479
+ group=self.marketing_group,
480
+ collection=self.finance_collection,
481
+ permission=self.add_permission,
482
+ )
483
+ # We can move nodes lower on the tree
484
+ self.post(
485
+ self.marketing_sub_collection.id,
486
+ {"name": "Moved Sub", "parent": self.finance_collection.id},
487
+ )
488
+ self.assertEqual(
489
+ Collection.objects.get(pk=self.marketing_sub_collection.pk).get_parent(),
490
+ self.finance_collection,
491
+ )
492
+
493
+ # But we can't move the node to which our edit permission was assigned; update is ignored
494
+ self.post(
495
+ self.marketing_collection.id,
496
+ {
497
+ "name": self.marketing_collection.name,
498
+ "parent": self.finance_collection.id,
499
+ },
500
+ )
501
+ self.assertEqual(
502
+ Collection.objects.get(pk=self.marketing_collection.pk).get_parent(),
503
+ self.root_collection,
504
+ )
505
+
506
+ def test_page_shows_delete_link_only_if_delete_permitted(self):
507
+ # Retrieve edit form and check fields
508
+ response = self.get(collection_id=self.marketing_sub_collection.id)
509
+ self.assertNotContains(response, "Delete collection")
510
+ # Add delete permission to parent collection an try again
511
+ GroupCollectionPermission.objects.create(
512
+ group=self.marketing_group,
513
+ collection=self.marketing_collection,
514
+ permission=self.delete_permission,
515
+ )
516
+ response = self.get(collection_id=self.marketing_sub_collection.id)
517
+ self.assertContains(response, "Delete collection")
518
+
519
+
520
+ class TestDeleteCollectionAsSuperuser(TestCase, WagtailTestUtils):
521
+ def setUp(self):
522
+ self.login()
523
+ self.root_collection = Collection.get_first_root_node()
524
+ self.collection = self.root_collection.add_child(name="Holiday snaps")
525
+
526
+ def get(self, params={}, collection_id=None):
527
+ return self.client.get(
528
+ reverse(
529
+ "wagtailadmin_collections:delete",
530
+ args=(collection_id or self.collection.id,),
531
+ ),
532
+ params,
533
+ )
534
+
535
+ def post(self, post_data={}, collection_id=None):
536
+ return self.client.post(
537
+ reverse(
538
+ "wagtailadmin_collections:delete",
539
+ args=(collection_id or self.collection.id,),
540
+ ),
541
+ post_data,
542
+ )
543
+
544
+ def test_get(self):
545
+ response = self.get()
546
+ self.assertEqual(response.status_code, 200)
547
+ self.assertTemplateUsed(response, "wagtailadmin/generic/confirm_delete.html")
548
+
549
+ def test_cannot_delete_root_collection(self):
550
+ response = self.get(collection_id=self.root_collection.id)
551
+ self.assertEqual(response.status_code, 404)
552
+
553
+ def test_get_nonexistent_collection(self):
554
+ response = self.get(collection_id=100000)
555
+ self.assertEqual(response.status_code, 404)
556
+
557
+ def test_get_nonempty_collection(self):
558
+ Document.objects.create(title="Test document", collection=self.collection)
559
+
560
+ response = self.get()
561
+ self.assertEqual(response.status_code, 200)
562
+ self.assertTemplateUsed(
563
+ response, "wagtailadmin/collections/delete_not_empty.html"
564
+ )
565
+
566
+ def test_get_collection_with_descendent(self):
567
+ self.collection.add_child(instance=Collection(name="Test collection"))
568
+
569
+ response = self.get()
570
+ self.assertEqual(response.status_code, 200)
571
+ self.assertTemplateUsed(
572
+ response, "wagtailadmin/collections/delete_not_empty.html"
573
+ )
574
+
575
+ def test_post(self):
576
+ response = self.post()
577
+
578
+ # Should redirect back to index
579
+ self.assertRedirects(response, reverse("wagtailadmin_collections:index"))
580
+
581
+ # Check that the collection was deleted
582
+ with self.assertRaises(Collection.DoesNotExist):
583
+ Collection.objects.get(id=self.collection.id)
584
+
585
+ def test_post_nonempty_collection(self):
586
+ Document.objects.create(title="Test document", collection=self.collection)
587
+
588
+ response = self.post()
589
+ self.assertEqual(response.status_code, 403)
590
+
591
+ # Check that the collection was not deleted
592
+ self.assertTrue(Collection.objects.get(id=self.collection.id))
593
+
594
+ def test_post_collection_with_descendant(self):
595
+ self.collection.add_child(instance=Collection(name="Test collection"))
596
+
597
+ response = self.post()
598
+ self.assertEqual(response.status_code, 403)
599
+
600
+ # Check that the collection was not deleted
601
+ self.assertTrue(Collection.objects.get(id=self.collection.id))
602
+
603
+ def test_post_root_collection(self):
604
+ # first we have to clear out the root collection so it is empty
605
+ self.collection.delete()
606
+
607
+ response = self.post(collection_id=self.root_collection.id)
608
+ self.assertEqual(response.status_code, 404)
609
+ # Check that the collection was not deleted
610
+ self.assertTrue(Collection.objects.get(id=self.root_collection.id))
611
+
612
+
613
+ class TestDeleteCollection(CollectionInstanceTestUtils, TestCase, WagtailTestUtils):
614
+ def setUp(self):
615
+ super().setUp()
616
+ # Grant the marketing group permission to delete
617
+ self.users_delete_permission = GroupCollectionPermission.objects.create(
618
+ group=self.marketing_group,
619
+ collection=self.marketing_collection,
620
+ permission=self.delete_permission,
621
+ )
622
+ self.login(self.marketing_user, password="password")
623
+
624
+ def get(self, collection_id, params={}):
625
+ return self.client.get(
626
+ reverse("wagtailadmin_collections:delete", args=(collection_id,)), params
627
+ )
628
+
629
+ def post(self, collection_id, post_data={}):
630
+ return self.client.post(
631
+ reverse("wagtailadmin_collections:delete", args=(collection_id,)), post_data
632
+ )
633
+
634
+ def test_get(self):
635
+ response = self.get(collection_id=self.marketing_sub_collection.id)
636
+ self.assertEqual(response.status_code, 200)
637
+ self.assertTemplateUsed(response, "wagtailadmin/generic/confirm_delete.html")
638
+
639
+ def test_post(self):
640
+ response = self.post(collection_id=self.marketing_sub_collection.id)
641
+ # Should redirect back to index
642
+ self.assertRedirects(response, reverse("wagtailadmin_collections:index"))
643
+
644
+ # Check that the collection was deleted
645
+ with self.assertRaises(Collection.DoesNotExist):
646
+ Collection.objects.get(id=self.marketing_sub_collection.id)
647
+
648
+ def test_cannot_delete_someone_elses_collection(self):
649
+ response = self.get(self.finance_collection.id)
650
+ self.assertEqual(response.status_code, 404)
651
+
652
+ def test_cannot_delete_someone_elses_collection_post(self):
653
+ response = self.post(self.finance_collection.id)
654
+ self.assertEqual(response.status_code, 404)
655
+ # Check that the collection was not deleted
656
+ self.assertTrue(Collection.objects.get(id=self.marketing_sub_collection.id))
657
+
658
+ def test_cannot_delete_their_own_root_collection(self):
659
+ response = self.get(self.marketing_collection.id)
660
+ self.assertEqual(response.status_code, 404)
661
+
662
+ def test_cannot_delete_their_own_root_collection_post(self):
663
+ response = self.post(self.marketing_collection.id)
664
+ self.assertEqual(response.status_code, 404)
665
+ # Check that the collection was not deleted
666
+ self.assertTrue(Collection.objects.get(id=self.marketing_collection.id))
667
+
668
+ def test_cannot_delete_collection_with_descendants(self):
669
+ self.marketing_sub_collection.add_child(
670
+ instance=Collection(name="Another collection")
671
+ )
672
+
673
+ response = self.get(self.marketing_sub_collection.id)
674
+ self.assertEqual(response.status_code, 200)
675
+ self.assertTemplateUsed(
676
+ response, "wagtailadmin/collections/delete_not_empty.html"
677
+ )
678
+
679
+ def test_cannot_delete_collection_with_descendants_post(self):
680
+ self.marketing_sub_collection.add_child(
681
+ instance=Collection(name="Another collection")
682
+ )
683
+
684
+ response = self.post(self.marketing_sub_collection.id)
685
+ self.assertEqual(response.status_code, 403)
686
+
687
+ # Check that the collection was not deleted
688
+ self.assertTrue(Collection.objects.get(id=self.marketing_sub_collection.id))
testbed/wagtail__wagtail/wagtail/admin/tests/test_compare.py ADDED
@@ -0,0 +1,1553 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+
3
+ from django.test import TestCase
4
+ from django.utils.safestring import SafeString
5
+
6
+ from wagtail.admin import compare
7
+ from wagtail.blocks import StreamValue
8
+ from wagtail.images import get_image_model
9
+ from wagtail.images.tests.utils import get_test_image_file
10
+ from wagtail.test.testapp.models import (
11
+ AdvertWithCustomPrimaryKey,
12
+ EventCategory,
13
+ EventPage,
14
+ EventPageSpeaker,
15
+ HeadCountRelatedModelUsingPK,
16
+ SimplePage,
17
+ SnippetChooserModelWithCustomPrimaryKey,
18
+ StreamPage,
19
+ TaggedPage,
20
+ )
21
+
22
+
23
+ class TestFieldComparison(TestCase):
24
+ comparison_class = compare.FieldComparison
25
+
26
+ def test_hasnt_changed(self):
27
+ comparison = self.comparison_class(
28
+ SimplePage._meta.get_field("content"),
29
+ SimplePage(content="Content"),
30
+ SimplePage(content="Content"),
31
+ )
32
+
33
+ self.assertTrue(comparison.is_field)
34
+ self.assertFalse(comparison.is_child_relation)
35
+ self.assertEqual(comparison.field_label(), "Content")
36
+ self.assertEqual(comparison.htmldiff(), "Content")
37
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
38
+ self.assertFalse(comparison.has_changed())
39
+
40
+ def test_has_changed(self):
41
+ comparison = self.comparison_class(
42
+ SimplePage._meta.get_field("content"),
43
+ SimplePage(content="Original content"),
44
+ SimplePage(content="Modified content"),
45
+ )
46
+
47
+ self.assertEqual(
48
+ comparison.htmldiff(),
49
+ '<span class="deletion">Original content</span><span class="addition">Modified content</span>',
50
+ )
51
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
52
+ self.assertTrue(comparison.has_changed())
53
+
54
+ def test_htmldiff_escapes_value(self):
55
+ comparison = self.comparison_class(
56
+ SimplePage._meta.get_field("content"),
57
+ SimplePage(content="Original content"),
58
+ SimplePage(
59
+ content='<script type="text/javascript">doSomethingBad();</script>'
60
+ ),
61
+ )
62
+
63
+ self.assertEqual(
64
+ comparison.htmldiff(),
65
+ '<span class="deletion">Original content</span><span class="addition">&lt;script type=&quot;text/javascript&quot;&gt;doSomethingBad();&lt;/script&gt;</span>',
66
+ )
67
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
68
+
69
+
70
+ class TestTextFieldComparison(TestFieldComparison):
71
+ comparison_class = compare.TextFieldComparison
72
+
73
+ # Only change from FieldComparison is the HTML diff is performed on words
74
+ # instead of the whole field value.
75
+ def test_has_changed(self):
76
+ comparison = self.comparison_class(
77
+ SimplePage._meta.get_field("content"),
78
+ SimplePage(content="Original content"),
79
+ SimplePage(content="Modified content"),
80
+ )
81
+
82
+ self.assertEqual(
83
+ comparison.htmldiff(),
84
+ '<span class="deletion">Original</span><span class="addition">Modified</span> content',
85
+ )
86
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
87
+ self.assertTrue(comparison.has_changed())
88
+
89
+ def test_from_none_to_value_only_shows_addition(self):
90
+ comparison = self.comparison_class(
91
+ SimplePage._meta.get_field("content"),
92
+ SimplePage(content=None),
93
+ SimplePage(content="Added content"),
94
+ )
95
+
96
+ self.assertEqual(
97
+ comparison.htmldiff(), '<span class="addition">Added content</span>'
98
+ )
99
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
100
+ self.assertTrue(comparison.has_changed())
101
+
102
+ def test_from_value_to_none_only_shows_deletion(self):
103
+ comparison = self.comparison_class(
104
+ SimplePage._meta.get_field("content"),
105
+ SimplePage(content="Removed content"),
106
+ SimplePage(content=None),
107
+ )
108
+
109
+ self.assertEqual(
110
+ comparison.htmldiff(), '<span class="deletion">Removed content</span>'
111
+ )
112
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
113
+ self.assertTrue(comparison.has_changed())
114
+
115
+
116
+ class TestRichTextFieldComparison(TestFieldComparison):
117
+ comparison_class = compare.RichTextFieldComparison
118
+
119
+ # Only change from FieldComparison is the HTML diff is performed on words
120
+ # instead of the whole field value.
121
+ def test_has_changed(self):
122
+ comparison = self.comparison_class(
123
+ SimplePage._meta.get_field("content"),
124
+ SimplePage(content="Original content"),
125
+ SimplePage(content="Modified content"),
126
+ )
127
+
128
+ self.assertEqual(
129
+ comparison.htmldiff(),
130
+ '<span class="deletion">Original</span><span class="addition">Modified</span> content',
131
+ )
132
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
133
+ self.assertTrue(comparison.has_changed())
134
+
135
+ # Only change from FieldComparison is that this comparison disregards HTML tags
136
+ def test_has_changed_html(self):
137
+ comparison = self.comparison_class(
138
+ SimplePage._meta.get_field("content"),
139
+ SimplePage(content="<b>Original</b> content"),
140
+ SimplePage(content="Modified <i>content</i>"),
141
+ )
142
+
143
+ self.assertEqual(
144
+ comparison.htmldiff(),
145
+ '<span class="deletion">Original</span><span class="addition">Modified</span> content',
146
+ )
147
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
148
+ self.assertTrue(comparison.has_changed())
149
+
150
+ def test_htmldiff_escapes_value(self):
151
+ # Need to override this one as the HTML tags are stripped by RichTextFieldComparison
152
+ comparison = self.comparison_class(
153
+ SimplePage._meta.get_field("content"),
154
+ SimplePage(content="Original content"),
155
+ SimplePage(
156
+ content='<script type="text/javascript">doSomethingBad();</script>'
157
+ ),
158
+ )
159
+
160
+ self.assertEqual(
161
+ comparison.htmldiff(),
162
+ '<span class="deletion">Original content</span><span class="addition">doSomethingBad();</span>',
163
+ )
164
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
165
+
166
+
167
+ class TestStreamFieldComparison(TestCase):
168
+ comparison_class = compare.StreamFieldComparison
169
+
170
+ def test_hasnt_changed(self):
171
+ field = StreamPage._meta.get_field("body")
172
+
173
+ comparison = self.comparison_class(
174
+ field,
175
+ StreamPage(
176
+ body=StreamValue(
177
+ field.stream_block,
178
+ [
179
+ ("text", "Content", "1"),
180
+ ],
181
+ )
182
+ ),
183
+ StreamPage(
184
+ body=StreamValue(
185
+ field.stream_block,
186
+ [
187
+ ("text", "Content", "1"),
188
+ ],
189
+ )
190
+ ),
191
+ )
192
+
193
+ self.assertTrue(comparison.is_field)
194
+ self.assertFalse(comparison.is_child_relation)
195
+ self.assertEqual(comparison.field_label(), "Body")
196
+ self.assertEqual(
197
+ comparison.htmldiff(), '<div class="comparison__child-object">Content</div>'
198
+ )
199
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
200
+ self.assertFalse(comparison.has_changed())
201
+
202
+ def test_has_changed(self):
203
+ field = StreamPage._meta.get_field("body")
204
+
205
+ comparison = self.comparison_class(
206
+ field,
207
+ StreamPage(
208
+ body=StreamValue(
209
+ field.stream_block,
210
+ [
211
+ ("text", "Original content", "1"),
212
+ ],
213
+ )
214
+ ),
215
+ StreamPage(
216
+ body=StreamValue(
217
+ field.stream_block,
218
+ [
219
+ ("text", "Modified content", "1"),
220
+ ],
221
+ )
222
+ ),
223
+ )
224
+
225
+ self.assertEqual(
226
+ comparison.htmldiff(),
227
+ '<div class="comparison__child-object"><span class="deletion">Original</span><span class="addition">Modified</span> content</div>',
228
+ )
229
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
230
+ self.assertTrue(comparison.has_changed())
231
+
232
+ def test_add_block(self):
233
+ field = StreamPage._meta.get_field("body")
234
+
235
+ comparison = self.comparison_class(
236
+ field,
237
+ StreamPage(
238
+ body=StreamValue(
239
+ field.stream_block,
240
+ [
241
+ ("text", "Content", "1"),
242
+ ],
243
+ )
244
+ ),
245
+ StreamPage(
246
+ body=StreamValue(
247
+ field.stream_block,
248
+ [
249
+ ("text", "Content", "1"),
250
+ ("text", "New Content", "2"),
251
+ ],
252
+ )
253
+ ),
254
+ )
255
+
256
+ self.assertEqual(
257
+ comparison.htmldiff(),
258
+ '<div class="comparison__child-object">Content</div>\n<div class="comparison__child-object addition">New Content</div>',
259
+ )
260
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
261
+ self.assertTrue(comparison.has_changed())
262
+
263
+ def test_delete_block(self):
264
+ field = StreamPage._meta.get_field("body")
265
+
266
+ comparison = self.comparison_class(
267
+ field,
268
+ StreamPage(
269
+ body=StreamValue(
270
+ field.stream_block,
271
+ [
272
+ ("text", "Content", "1"),
273
+ ("text", "Content Foo", "2"),
274
+ ("text", "Content Bar", "3"),
275
+ ],
276
+ )
277
+ ),
278
+ StreamPage(
279
+ body=StreamValue(
280
+ field.stream_block,
281
+ [
282
+ ("text", "Content", "1"),
283
+ ("text", "Content Bar", "3"),
284
+ ],
285
+ )
286
+ ),
287
+ )
288
+
289
+ self.assertEqual(
290
+ comparison.htmldiff(),
291
+ '<div class="comparison__child-object">Content</div>\n<div class="comparison__child-object deletion">Content Foo</div>\n<div class="comparison__child-object">Content Bar</div>',
292
+ )
293
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
294
+ self.assertTrue(comparison.has_changed())
295
+
296
+ def test_edit_block(self):
297
+ field = StreamPage._meta.get_field("body")
298
+
299
+ comparison = self.comparison_class(
300
+ field,
301
+ StreamPage(
302
+ body=StreamValue(
303
+ field.stream_block,
304
+ [
305
+ ("text", "Content", "1"),
306
+ ("text", "Content Foo", "2"),
307
+ ("text", "Content Bar", "3"),
308
+ ],
309
+ )
310
+ ),
311
+ StreamPage(
312
+ body=StreamValue(
313
+ field.stream_block,
314
+ [
315
+ ("text", "Content", "1"),
316
+ ("text", "Content Baz", "2"),
317
+ ("text", "Content Bar", "3"),
318
+ ],
319
+ )
320
+ ),
321
+ )
322
+
323
+ self.assertEqual(
324
+ comparison.htmldiff(),
325
+ '<div class="comparison__child-object">Content</div>\n<div class="comparison__child-object">Content <span class="deletion">Foo</span><span class="addition">Baz</span></div>\n<div class="comparison__child-object">Content Bar</div>',
326
+ )
327
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
328
+ self.assertTrue(comparison.has_changed())
329
+
330
+ def test_has_changed_richtext(self):
331
+ field = StreamPage._meta.get_field("body")
332
+
333
+ comparison = self.comparison_class(
334
+ field,
335
+ StreamPage(
336
+ body=StreamValue(
337
+ field.stream_block,
338
+ [
339
+ ("rich_text", "<b>Original</b> content", "1"),
340
+ ],
341
+ )
342
+ ),
343
+ StreamPage(
344
+ body=StreamValue(
345
+ field.stream_block,
346
+ [
347
+ ("rich_text", "Modified <i>content</i>", "1"),
348
+ ],
349
+ )
350
+ ),
351
+ )
352
+
353
+ self.assertEqual(
354
+ comparison.htmldiff(),
355
+ '<div class="comparison__child-object"><span class="deletion">Original</span><span class="addition">Modified</span> content</div>',
356
+ )
357
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
358
+ self.assertTrue(comparison.has_changed())
359
+
360
+ def test_htmldiff_escapes_value_on_change(self):
361
+ field = StreamPage._meta.get_field("body")
362
+
363
+ comparison = self.comparison_class(
364
+ field,
365
+ StreamPage(
366
+ body=StreamValue(
367
+ field.stream_block,
368
+ [
369
+ (
370
+ "text",
371
+ "I <b>really</b> like original<i>ish</i> content",
372
+ "1",
373
+ ),
374
+ ],
375
+ )
376
+ ),
377
+ StreamPage(
378
+ body=StreamValue(
379
+ field.stream_block,
380
+ [
381
+ (
382
+ "text",
383
+ 'I <b>really</b> like evil code <script type="text/javascript">doSomethingBad();</script>',
384
+ "1",
385
+ ),
386
+ ],
387
+ )
388
+ ),
389
+ )
390
+
391
+ self.assertEqual(
392
+ comparison.htmldiff(),
393
+ '<div class="comparison__child-object">I &lt;b&gt;really&lt;/b&gt; like <span class="deletion">original&lt;i&gt;ish&lt;/i&gt; content</span><span class="addition">evil code &lt;script type=&quot;text/javascript&quot;&gt;doSomethingBad();&lt;/script&gt;</span></div>',
394
+ )
395
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
396
+
397
+ def test_htmldiff_escapes_value_on_addition(self):
398
+ field = StreamPage._meta.get_field("body")
399
+
400
+ comparison = self.comparison_class(
401
+ field,
402
+ StreamPage(
403
+ body=StreamValue(
404
+ field.stream_block,
405
+ [
406
+ ("text", "Original <em>and unchanged</em> content", "1"),
407
+ ],
408
+ )
409
+ ),
410
+ StreamPage(
411
+ body=StreamValue(
412
+ field.stream_block,
413
+ [
414
+ ("text", "Original <em>and unchanged</em> content", "1"),
415
+ (
416
+ "text",
417
+ '<script type="text/javascript">doSomethingBad();</script>',
418
+ "2",
419
+ ),
420
+ ],
421
+ )
422
+ ),
423
+ )
424
+
425
+ self.assertEqual(
426
+ comparison.htmldiff(),
427
+ '<div class="comparison__child-object">Original &lt;em&gt;and unchanged&lt;/em&gt; content</div>\n<div class="comparison__child-object addition">&lt;script type=&quot;text/javascript&quot;&gt;doSomethingBad();&lt;/script&gt;</div>',
428
+ )
429
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
430
+
431
+ def test_htmldiff_escapes_value_on_deletion(self):
432
+ field = StreamPage._meta.get_field("body")
433
+
434
+ comparison = self.comparison_class(
435
+ field,
436
+ StreamPage(
437
+ body=StreamValue(
438
+ field.stream_block,
439
+ [
440
+ ("text", "Original <em>and unchanged</em> content", "1"),
441
+ (
442
+ "text",
443
+ '<script type="text/javascript">doSomethingBad();</script>',
444
+ "2",
445
+ ),
446
+ ],
447
+ )
448
+ ),
449
+ StreamPage(
450
+ body=StreamValue(
451
+ field.stream_block,
452
+ [
453
+ ("text", "Original <em>and unchanged</em> content", "1"),
454
+ ],
455
+ )
456
+ ),
457
+ )
458
+
459
+ self.assertEqual(
460
+ comparison.htmldiff(),
461
+ '<div class="comparison__child-object">Original &lt;em&gt;and unchanged&lt;/em&gt; content</div>\n<div class="comparison__child-object deletion">&lt;script type=&quot;text/javascript&quot;&gt;doSomethingBad();&lt;/script&gt;</div>',
462
+ )
463
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
464
+
465
+ def test_htmldiff_richtext_strips_tags_on_change(self):
466
+ field = StreamPage._meta.get_field("body")
467
+
468
+ comparison = self.comparison_class(
469
+ field,
470
+ StreamPage(
471
+ body=StreamValue(
472
+ field.stream_block,
473
+ [
474
+ ("rich_text", "I <b>really</b> like Wagtail &lt;3", "1"),
475
+ ],
476
+ )
477
+ ),
478
+ StreamPage(
479
+ body=StreamValue(
480
+ field.stream_block,
481
+ [
482
+ (
483
+ "rich_text",
484
+ 'I <b>really</b> like evil code &gt;_&lt; <script type="text/javascript">doSomethingBad();</script>',
485
+ "1",
486
+ ),
487
+ ],
488
+ )
489
+ ),
490
+ )
491
+
492
+ self.assertEqual(
493
+ comparison.htmldiff(),
494
+ '<div class="comparison__child-object">I really like <span class="deletion">Wagtail &lt;3</span><span class="addition">evil code &gt;_&lt; doSomethingBad();</span></div>',
495
+ )
496
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
497
+
498
+ def test_htmldiff_richtext_strips_tags_on_addition(self):
499
+ field = StreamPage._meta.get_field("body")
500
+
501
+ comparison = self.comparison_class(
502
+ field,
503
+ StreamPage(
504
+ body=StreamValue(
505
+ field.stream_block,
506
+ [
507
+ ("rich_text", "Original <em>and unchanged</em> content", "1"),
508
+ ],
509
+ )
510
+ ),
511
+ StreamPage(
512
+ body=StreamValue(
513
+ field.stream_block,
514
+ [
515
+ ("rich_text", "Original <em>and unchanged</em> content", "1"),
516
+ (
517
+ "rich_text",
518
+ 'I <b>really</b> like evil code &gt;_&lt; <script type="text/javascript">doSomethingBad();</script>',
519
+ "2",
520
+ ),
521
+ ],
522
+ )
523
+ ),
524
+ )
525
+
526
+ self.assertEqual(
527
+ comparison.htmldiff(),
528
+ '<div class="comparison__child-object">Original and unchanged content</div>\n<div class="comparison__child-object addition">I really like evil code &gt;_&lt; doSomethingBad();</div>',
529
+ )
530
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
531
+
532
+ def test_htmldiff_richtext_strips_tags_on_deletion(self):
533
+ field = StreamPage._meta.get_field("body")
534
+
535
+ comparison = self.comparison_class(
536
+ field,
537
+ StreamPage(
538
+ body=StreamValue(
539
+ field.stream_block,
540
+ [
541
+ ("rich_text", "Original <em>and unchanged</em> content", "1"),
542
+ (
543
+ "rich_text",
544
+ 'I <b>really</b> like evil code &gt;_&lt; <script type="text/javascript">doSomethingBad();</script>',
545
+ "2",
546
+ ),
547
+ ],
548
+ )
549
+ ),
550
+ StreamPage(
551
+ body=StreamValue(
552
+ field.stream_block,
553
+ [
554
+ ("rich_text", "Original <em>and unchanged</em> content", "1"),
555
+ ],
556
+ )
557
+ ),
558
+ )
559
+
560
+ self.assertEqual(
561
+ comparison.htmldiff(),
562
+ '<div class="comparison__child-object">Original and unchanged content</div>\n<div class="comparison__child-object deletion">I really like evil code &gt;_&lt; doSomethingBad();</div>',
563
+ )
564
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
565
+
566
+ def test_htmldiff_raw_html_escapes_value_on_change(self):
567
+ field = StreamPage._meta.get_field("body")
568
+
569
+ comparison = self.comparison_class(
570
+ field,
571
+ StreamPage(
572
+ body=StreamValue(
573
+ field.stream_block,
574
+ [
575
+ ("raw_html", "Original<i>ish</i> content", "1"),
576
+ ],
577
+ )
578
+ ),
579
+ StreamPage(
580
+ body=StreamValue(
581
+ field.stream_block,
582
+ [
583
+ (
584
+ "raw_html",
585
+ '<script type="text/javascript">doSomethingBad();</script>',
586
+ "1",
587
+ ),
588
+ ],
589
+ )
590
+ ),
591
+ )
592
+ self.assertEqual(
593
+ comparison.htmldiff(),
594
+ '<div class="comparison__child-object"><span class="deletion">Original&lt;i&gt;ish&lt;/i&gt; content</span><span class="addition">&lt;script type=&quot;text/javascript&quot;&gt;doSomethingBad();&lt;/script&gt;</span></div>',
595
+ )
596
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
597
+
598
+ def test_htmldiff_raw_html_escapes_value_on_addition(self):
599
+ field = StreamPage._meta.get_field("body")
600
+
601
+ comparison = self.comparison_class(
602
+ field,
603
+ StreamPage(
604
+ body=StreamValue(
605
+ field.stream_block,
606
+ [
607
+ ("raw_html", "Original <em>and unchanged</em> content", "1"),
608
+ ],
609
+ )
610
+ ),
611
+ StreamPage(
612
+ body=StreamValue(
613
+ field.stream_block,
614
+ [
615
+ ("raw_html", "Original <em>and unchanged</em> content", "1"),
616
+ (
617
+ "raw_html",
618
+ '<script type="text/javascript">doSomethingBad();</script>',
619
+ "2",
620
+ ),
621
+ ],
622
+ )
623
+ ),
624
+ )
625
+ self.assertEqual(
626
+ comparison.htmldiff(),
627
+ '<div class="comparison__child-object">Original &lt;em&gt;and unchanged&lt;/em&gt; content</div>\n<div class="comparison__child-object addition">&lt;script type=&quot;text/javascript&quot;&gt;doSomethingBad();&lt;/script&gt;</div>',
628
+ )
629
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
630
+
631
+ def test_htmldiff_raw_html_escapes_value_on_deletion(self):
632
+ field = StreamPage._meta.get_field("body")
633
+
634
+ comparison = self.comparison_class(
635
+ field,
636
+ StreamPage(
637
+ body=StreamValue(
638
+ field.stream_block,
639
+ [
640
+ ("raw_html", "Original <em>and unchanged</em> content", "1"),
641
+ (
642
+ "raw_html",
643
+ '<script type="text/javascript">doSomethingBad();</script>',
644
+ "2",
645
+ ),
646
+ ],
647
+ )
648
+ ),
649
+ StreamPage(
650
+ body=StreamValue(
651
+ field.stream_block,
652
+ [
653
+ ("raw_html", "Original <em>and unchanged</em> content", "1"),
654
+ ],
655
+ )
656
+ ),
657
+ )
658
+ self.assertEqual(
659
+ comparison.htmldiff(),
660
+ '<div class="comparison__child-object">Original &lt;em&gt;and unchanged&lt;/em&gt; content</div>\n<div class="comparison__child-object deletion">&lt;script type=&quot;text/javascript&quot;&gt;doSomethingBad();&lt;/script&gt;</div>',
661
+ )
662
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
663
+
664
+ def test_compare_structblock(self):
665
+ field = StreamPage._meta.get_field("body")
666
+
667
+ comparison = self.comparison_class(
668
+ field,
669
+ StreamPage(
670
+ body=StreamValue(
671
+ field.stream_block,
672
+ [
673
+ ("product", {"name": "a packet of rolos", "price": "75p"}, "1"),
674
+ ],
675
+ )
676
+ ),
677
+ StreamPage(
678
+ body=StreamValue(
679
+ field.stream_block,
680
+ [
681
+ ("product", {"name": "a packet of rolos", "price": "85p"}, "1"),
682
+ ],
683
+ )
684
+ ),
685
+ )
686
+
687
+ expected = """
688
+ <div class="comparison__child-object"><dl>
689
+ <dt>Name</dt>
690
+ <dd>a packet of rolos</dd>
691
+ <dt>Price</dt>
692
+ <dd><span class="deletion">75p</span><span class="addition">85p</span></dd>
693
+ </dl></div>
694
+ """
695
+ self.assertHTMLEqual(comparison.htmldiff(), expected)
696
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
697
+ self.assertTrue(comparison.has_changed())
698
+
699
+ def test_compare_nested_streamblock_uses_comparison_class(self):
700
+ field = StreamPage._meta.get_field("body")
701
+ stream_block = field.stream_block.child_blocks["books"]
702
+ comparison = self.comparison_class(
703
+ field,
704
+ StreamPage(
705
+ body=StreamValue(
706
+ field.stream_block,
707
+ [
708
+ (
709
+ "books",
710
+ StreamValue(
711
+ stream_block,
712
+ [("title", "The Old Man and the Sea", "10")],
713
+ ),
714
+ "1",
715
+ ),
716
+ ],
717
+ )
718
+ ),
719
+ StreamPage(
720
+ body=StreamValue(
721
+ field.stream_block,
722
+ [
723
+ (
724
+ "books",
725
+ StreamValue(
726
+ stream_block, [("author", "Oscar Wilde", "11")]
727
+ ),
728
+ "1",
729
+ ),
730
+ ],
731
+ )
732
+ ),
733
+ )
734
+ expected = """
735
+ <div class="comparison__child-object">
736
+ <div class="comparison__child-object addition">Oscar Wilde</div>\n
737
+ <div class="comparison__child-object deletion">The Old Man and the Sea</div>
738
+ </div>
739
+ """
740
+ self.assertHTMLEqual(comparison.htmldiff(), expected)
741
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
742
+ self.assertTrue(comparison.has_changed())
743
+
744
+ def test_compare_imagechooserblock(self):
745
+ image_model = get_image_model()
746
+ test_image_1 = image_model.objects.create(
747
+ title="Test image 1",
748
+ file=get_test_image_file(),
749
+ )
750
+ test_image_2 = image_model.objects.create(
751
+ title="Test image 2",
752
+ file=get_test_image_file(),
753
+ )
754
+
755
+ field = StreamPage._meta.get_field("body")
756
+
757
+ comparison = self.comparison_class(
758
+ field,
759
+ StreamPage(
760
+ body=StreamValue(
761
+ field.stream_block,
762
+ [
763
+ ("image", test_image_1, "1"),
764
+ ],
765
+ )
766
+ ),
767
+ StreamPage(
768
+ body=StreamValue(
769
+ field.stream_block,
770
+ [
771
+ ("image", test_image_2, "1"),
772
+ ],
773
+ )
774
+ ),
775
+ )
776
+
777
+ result = comparison.htmldiff()
778
+ self.assertIn('<div class="preview-image deletion">', result)
779
+ self.assertIn('alt="Test image 1"', result)
780
+ self.assertIn('<div class="preview-image addition">', result)
781
+ self.assertIn('alt="Test image 2"', result)
782
+
783
+ self.assertIsInstance(result, SafeString)
784
+ self.assertTrue(comparison.has_changed())
785
+
786
+
787
+ class TestChoiceFieldComparison(TestCase):
788
+ comparison_class = compare.ChoiceFieldComparison
789
+
790
+ def test_hasnt_changed(self):
791
+ comparison = self.comparison_class(
792
+ EventPage._meta.get_field("audience"),
793
+ EventPage(audience="public"),
794
+ EventPage(audience="public"),
795
+ )
796
+
797
+ self.assertTrue(comparison.is_field)
798
+ self.assertFalse(comparison.is_child_relation)
799
+ self.assertEqual(comparison.field_label(), "Audience")
800
+ self.assertEqual(comparison.htmldiff(), "Public")
801
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
802
+ self.assertFalse(comparison.has_changed())
803
+
804
+ def test_has_changed(self):
805
+ comparison = self.comparison_class(
806
+ EventPage._meta.get_field("audience"),
807
+ EventPage(audience="public"),
808
+ EventPage(audience="private"),
809
+ )
810
+
811
+ self.assertEqual(
812
+ comparison.htmldiff(),
813
+ '<span class="deletion">Public</span><span class="addition">Private</span>',
814
+ )
815
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
816
+ self.assertTrue(comparison.has_changed())
817
+
818
+ def test_from_none_to_value_only_shows_addition(self):
819
+ comparison = self.comparison_class(
820
+ EventPage._meta.get_field("audience"),
821
+ EventPage(audience=None),
822
+ EventPage(audience="private"),
823
+ )
824
+
825
+ self.assertEqual(comparison.htmldiff(), '<span class="addition">Private</span>')
826
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
827
+ self.assertTrue(comparison.has_changed())
828
+
829
+ def test_from_value_to_none_only_shows_deletion(self):
830
+ comparison = self.comparison_class(
831
+ EventPage._meta.get_field("audience"),
832
+ EventPage(audience="public"),
833
+ EventPage(audience=None),
834
+ )
835
+
836
+ self.assertEqual(comparison.htmldiff(), '<span class="deletion">Public</span>')
837
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
838
+ self.assertTrue(comparison.has_changed())
839
+
840
+
841
+ class TestTagsFieldComparison(TestCase):
842
+ comparison_class = compare.TagsFieldComparison
843
+
844
+ def test_hasnt_changed(self):
845
+ a = TaggedPage()
846
+ a.tags.add("wagtail")
847
+ a.tags.add("bird")
848
+
849
+ b = TaggedPage()
850
+ b.tags.add("wagtail")
851
+ b.tags.add("bird")
852
+
853
+ comparison = self.comparison_class(TaggedPage._meta.get_field("tags"), a, b)
854
+
855
+ self.assertTrue(comparison.is_field)
856
+ self.assertFalse(comparison.is_child_relation)
857
+ self.assertEqual(comparison.field_label(), "Tags")
858
+ self.assertEqual(comparison.htmldiff(), "wagtail, bird")
859
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
860
+ self.assertFalse(comparison.has_changed())
861
+
862
+ def test_has_changed(self):
863
+ a = TaggedPage()
864
+ a.tags.add("wagtail")
865
+ a.tags.add("bird")
866
+
867
+ b = TaggedPage()
868
+ b.tags.add("wagtail")
869
+ b.tags.add("motacilla")
870
+
871
+ comparison = self.comparison_class(TaggedPage._meta.get_field("tags"), a, b)
872
+
873
+ self.assertEqual(
874
+ comparison.htmldiff(),
875
+ 'wagtail, <span class="deletion">bird</span>, <span class="addition">motacilla</span>',
876
+ )
877
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
878
+ self.assertTrue(comparison.has_changed())
879
+
880
+
881
+ class TestM2MFieldComparison(TestCase):
882
+ fixtures = ["test.json"]
883
+ comparison_class = compare.M2MFieldComparison
884
+
885
+ def setUp(self):
886
+ self.meetings_category = EventCategory.objects.create(name="Meetings")
887
+ self.parties_category = EventCategory.objects.create(name="Parties")
888
+ self.holidays_category = EventCategory.objects.create(name="Holidays")
889
+
890
+ def test_hasnt_changed(self):
891
+ christmas_event = EventPage.objects.get(url_path="/home/events/christmas/")
892
+ saint_patrick_event = EventPage.objects.get(
893
+ url_path="/home/events/saint-patrick/"
894
+ )
895
+
896
+ christmas_event.categories = [self.meetings_category, self.parties_category]
897
+ saint_patrick_event.categories = [self.meetings_category, self.parties_category]
898
+
899
+ comparison = self.comparison_class(
900
+ EventPage._meta.get_field("categories"),
901
+ christmas_event,
902
+ saint_patrick_event,
903
+ )
904
+
905
+ self.assertTrue(comparison.is_field)
906
+ self.assertFalse(comparison.is_child_relation)
907
+ self.assertEqual(comparison.field_label(), "Categories")
908
+ self.assertFalse(comparison.has_changed())
909
+ self.assertEqual(comparison.htmldiff(), "Meetings, Parties")
910
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
911
+
912
+ def test_has_changed(self):
913
+ christmas_event = EventPage.objects.get(url_path="/home/events/christmas/")
914
+ saint_patrick_event = EventPage.objects.get(
915
+ url_path="/home/events/saint-patrick/"
916
+ )
917
+
918
+ christmas_event.categories = [self.meetings_category, self.parties_category]
919
+ saint_patrick_event.categories = [
920
+ self.meetings_category,
921
+ self.holidays_category,
922
+ ]
923
+
924
+ comparison = self.comparison_class(
925
+ EventPage._meta.get_field("categories"),
926
+ christmas_event,
927
+ saint_patrick_event,
928
+ )
929
+
930
+ self.assertTrue(comparison.has_changed())
931
+ self.assertEqual(
932
+ comparison.htmldiff(),
933
+ 'Meetings, <span class="deletion">Parties</span>, <span class="addition">Holidays</span>',
934
+ )
935
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
936
+
937
+
938
+ class TestForeignObjectComparison(TestCase):
939
+ comparison_class = compare.ForeignObjectComparison
940
+
941
+ @classmethod
942
+ def setUpTestData(cls):
943
+ image_model = get_image_model()
944
+ cls.test_image_1 = image_model.objects.create(
945
+ title="Test image 1",
946
+ file=get_test_image_file(),
947
+ )
948
+ cls.test_image_2 = image_model.objects.create(
949
+ title="Test image 2",
950
+ file=get_test_image_file(),
951
+ )
952
+
953
+ def test_hasnt_changed(self):
954
+ comparison = self.comparison_class(
955
+ EventPage._meta.get_field("feed_image"),
956
+ EventPage(feed_image=self.test_image_1),
957
+ EventPage(feed_image=self.test_image_1),
958
+ )
959
+
960
+ self.assertTrue(comparison.is_field)
961
+ self.assertFalse(comparison.is_child_relation)
962
+ self.assertEqual(comparison.field_label(), "Feed image")
963
+ self.assertEqual(comparison.htmldiff(), "Test image 1")
964
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
965
+ self.assertFalse(comparison.has_changed())
966
+
967
+ def test_has_changed(self):
968
+ comparison = self.comparison_class(
969
+ EventPage._meta.get_field("feed_image"),
970
+ EventPage(feed_image=self.test_image_1),
971
+ EventPage(feed_image=self.test_image_2),
972
+ )
973
+
974
+ self.assertEqual(
975
+ comparison.htmldiff(),
976
+ '<span class="deletion">Test image 1</span><span class="addition">Test image 2</span>',
977
+ )
978
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
979
+ self.assertTrue(comparison.has_changed())
980
+
981
+
982
+ class TestForeignObjectComparisonWithCustomPK(TestCase):
983
+ """ForeignObjectComparison works with models declaring a custom primary key field"""
984
+
985
+ comparison_class = compare.ForeignObjectComparison
986
+
987
+ @classmethod
988
+ def setUpTestData(cls):
989
+ ad1 = AdvertWithCustomPrimaryKey.objects.create(
990
+ advert_id="ad1", text="Advert 1"
991
+ )
992
+ ad2 = AdvertWithCustomPrimaryKey.objects.create(
993
+ advert_id="ad2", text="Advert 2"
994
+ )
995
+ cls.test_obj_1 = SnippetChooserModelWithCustomPrimaryKey.objects.create(
996
+ advertwithcustomprimarykey=ad1
997
+ )
998
+ cls.test_obj_2 = SnippetChooserModelWithCustomPrimaryKey.objects.create(
999
+ advertwithcustomprimarykey=ad2
1000
+ )
1001
+
1002
+ def test_hasnt_changed(self):
1003
+ comparison = self.comparison_class(
1004
+ SnippetChooserModelWithCustomPrimaryKey._meta.get_field(
1005
+ "advertwithcustomprimarykey"
1006
+ ),
1007
+ self.test_obj_1,
1008
+ self.test_obj_1,
1009
+ )
1010
+
1011
+ self.assertTrue(comparison.is_field)
1012
+ self.assertFalse(comparison.is_child_relation)
1013
+ self.assertEqual(comparison.field_label(), "Advertwithcustomprimarykey")
1014
+ self.assertEqual(comparison.htmldiff(), "Advert 1")
1015
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
1016
+ self.assertFalse(comparison.has_changed())
1017
+
1018
+ def test_has_changed(self):
1019
+ comparison = self.comparison_class(
1020
+ SnippetChooserModelWithCustomPrimaryKey._meta.get_field(
1021
+ "advertwithcustomprimarykey"
1022
+ ),
1023
+ self.test_obj_1,
1024
+ self.test_obj_2,
1025
+ )
1026
+
1027
+ self.assertEqual(
1028
+ comparison.htmldiff(),
1029
+ '<span class="deletion">Advert 1</span><span class="addition">Advert 2</span>',
1030
+ )
1031
+ self.assertIsInstance(comparison.htmldiff(), SafeString)
1032
+ self.assertTrue(comparison.has_changed())
1033
+
1034
+
1035
+ class TestChildRelationComparison(TestCase):
1036
+ field_comparison_class = compare.FieldComparison
1037
+ comparison_class = compare.ChildRelationComparison
1038
+
1039
+ def test_hasnt_changed(self):
1040
+ # Two event pages with speaker called "Father Christmas". Neither of
1041
+ # the speaker objects have an ID so this tests that the code can match
1042
+ # the two together by field content.
1043
+ event_page = EventPage(title="Event page", slug="event")
1044
+ event_page.speakers.add(
1045
+ EventPageSpeaker(
1046
+ first_name="Father",
1047
+ last_name="Christmas",
1048
+ )
1049
+ )
1050
+
1051
+ modified_event_page = EventPage(title="Event page", slug="event")
1052
+ modified_event_page.speakers.add(
1053
+ EventPageSpeaker(
1054
+ first_name="Father",
1055
+ last_name="Christmas",
1056
+ )
1057
+ )
1058
+
1059
+ comparison = self.comparison_class(
1060
+ EventPage._meta.get_field("speaker"),
1061
+ [
1062
+ partial(
1063
+ self.field_comparison_class,
1064
+ EventPageSpeaker._meta.get_field("first_name"),
1065
+ ),
1066
+ partial(
1067
+ self.field_comparison_class,
1068
+ EventPageSpeaker._meta.get_field("last_name"),
1069
+ ),
1070
+ ],
1071
+ event_page,
1072
+ modified_event_page,
1073
+ )
1074
+
1075
+ self.assertFalse(comparison.is_field)
1076
+ self.assertTrue(comparison.is_child_relation)
1077
+ self.assertEqual(comparison.field_label(), "Speaker")
1078
+ self.assertFalse(comparison.has_changed())
1079
+
1080
+ # Check mapping
1081
+ objs_a = list(comparison.val_a.all())
1082
+ objs_b = list(comparison.val_b.all())
1083
+ map_forwards, map_backwards, added, deleted = comparison.get_mapping(
1084
+ objs_a, objs_b
1085
+ )
1086
+ self.assertEqual(map_forwards, {0: 0})
1087
+ self.assertEqual(map_backwards, {0: 0})
1088
+ self.assertEqual(added, [])
1089
+ self.assertEqual(deleted, [])
1090
+
1091
+ def test_has_changed(self):
1092
+ # Father Christmas renamed to Santa Claus. And Father Ted added.
1093
+ # Father Christmas should be mapped to Father Ted because they
1094
+ # are most alike. Santa claus should be displayed as "new"
1095
+ event_page = EventPage(title="Event page", slug="event")
1096
+ event_page.speakers.add(
1097
+ EventPageSpeaker(
1098
+ first_name="Father",
1099
+ last_name="Christmas",
1100
+ sort_order=0,
1101
+ )
1102
+ )
1103
+
1104
+ modified_event_page = EventPage(title="Event page", slug="event")
1105
+ modified_event_page.speakers.add(
1106
+ EventPageSpeaker(
1107
+ first_name="Santa",
1108
+ last_name="Claus",
1109
+ sort_order=0,
1110
+ )
1111
+ )
1112
+ modified_event_page.speakers.add(
1113
+ EventPageSpeaker(
1114
+ first_name="Father",
1115
+ last_name="Ted",
1116
+ sort_order=1,
1117
+ )
1118
+ )
1119
+
1120
+ comparison = self.comparison_class(
1121
+ EventPage._meta.get_field("speaker"),
1122
+ [
1123
+ partial(
1124
+ self.field_comparison_class,
1125
+ EventPageSpeaker._meta.get_field("first_name"),
1126
+ ),
1127
+ partial(
1128
+ self.field_comparison_class,
1129
+ EventPageSpeaker._meta.get_field("last_name"),
1130
+ ),
1131
+ ],
1132
+ event_page,
1133
+ modified_event_page,
1134
+ )
1135
+
1136
+ self.assertFalse(comparison.is_field)
1137
+ self.assertTrue(comparison.is_child_relation)
1138
+ self.assertEqual(comparison.field_label(), "Speaker")
1139
+ self.assertTrue(comparison.has_changed())
1140
+
1141
+ # Check mapping
1142
+ objs_a = list(comparison.val_a.all())
1143
+ objs_b = list(comparison.val_b.all())
1144
+ map_forwards, map_backwards, added, deleted = comparison.get_mapping(
1145
+ objs_a, objs_b
1146
+ )
1147
+ self.assertEqual(map_forwards, {0: 1}) # Map Father Christmas to Father Ted
1148
+ self.assertEqual(map_backwards, {1: 0}) # Map Father Ted to Father Christmas
1149
+ self.assertEqual(added, [0]) # Add Santa Claus
1150
+ self.assertEqual(deleted, [])
1151
+
1152
+ def test_has_changed_with_same_id(self):
1153
+ # Father Christmas renamed to Santa Claus, but this time the ID of the
1154
+ # child object remained the same. It should now be detected as the same
1155
+ # object
1156
+ event_page = EventPage(title="Event page", slug="event")
1157
+ event_page.speakers.add(
1158
+ EventPageSpeaker(
1159
+ id=1,
1160
+ first_name="Father",
1161
+ last_name="Christmas",
1162
+ sort_order=0,
1163
+ )
1164
+ )
1165
+
1166
+ modified_event_page = EventPage(title="Event page", slug="event")
1167
+ modified_event_page.speakers.add(
1168
+ EventPageSpeaker(
1169
+ id=1,
1170
+ first_name="Santa",
1171
+ last_name="Claus",
1172
+ sort_order=0,
1173
+ )
1174
+ )
1175
+ modified_event_page.speakers.add(
1176
+ EventPageSpeaker(
1177
+ first_name="Father",
1178
+ last_name="Ted",
1179
+ sort_order=1,
1180
+ )
1181
+ )
1182
+
1183
+ comparison = self.comparison_class(
1184
+ EventPage._meta.get_field("speaker"),
1185
+ [
1186
+ partial(
1187
+ self.field_comparison_class,
1188
+ EventPageSpeaker._meta.get_field("first_name"),
1189
+ ),
1190
+ partial(
1191
+ self.field_comparison_class,
1192
+ EventPageSpeaker._meta.get_field("last_name"),
1193
+ ),
1194
+ ],
1195
+ event_page,
1196
+ modified_event_page,
1197
+ )
1198
+
1199
+ self.assertFalse(comparison.is_field)
1200
+ self.assertTrue(comparison.is_child_relation)
1201
+ self.assertEqual(comparison.field_label(), "Speaker")
1202
+ self.assertTrue(comparison.has_changed())
1203
+
1204
+ # Check mapping
1205
+ objs_a = list(comparison.val_a.all())
1206
+ objs_b = list(comparison.val_b.all())
1207
+ map_forwards, map_backwards, added, deleted = comparison.get_mapping(
1208
+ objs_a, objs_b
1209
+ )
1210
+ self.assertEqual(map_forwards, {0: 0}) # Map Father Christmas to Santa Claus
1211
+ self.assertEqual(map_backwards, {0: 0}) # Map Santa Claus to Father Christmas
1212
+ self.assertEqual(added, [1]) # Add Father Ted
1213
+ self.assertEqual(deleted, [])
1214
+
1215
+ def test_hasnt_changed_with_different_id(self):
1216
+ # Both of the child objects have the same field content but have a
1217
+ # different ID so they should be detected as separate objects
1218
+ event_page = EventPage(title="Event page", slug="event")
1219
+ event_page.speakers.add(
1220
+ EventPageSpeaker(
1221
+ id=1,
1222
+ first_name="Father",
1223
+ last_name="Christmas",
1224
+ )
1225
+ )
1226
+
1227
+ modified_event_page = EventPage(title="Event page", slug="event")
1228
+ modified_event_page.speakers.add(
1229
+ EventPageSpeaker(
1230
+ id=2,
1231
+ first_name="Father",
1232
+ last_name="Christmas",
1233
+ )
1234
+ )
1235
+
1236
+ comparison = self.comparison_class(
1237
+ EventPage._meta.get_field("speaker"),
1238
+ [
1239
+ partial(
1240
+ self.field_comparison_class,
1241
+ EventPageSpeaker._meta.get_field("first_name"),
1242
+ ),
1243
+ partial(
1244
+ self.field_comparison_class,
1245
+ EventPageSpeaker._meta.get_field("last_name"),
1246
+ ),
1247
+ ],
1248
+ event_page,
1249
+ modified_event_page,
1250
+ )
1251
+
1252
+ self.assertFalse(comparison.is_field)
1253
+ self.assertTrue(comparison.is_child_relation)
1254
+ self.assertEqual(comparison.field_label(), "Speaker")
1255
+ self.assertTrue(comparison.has_changed())
1256
+
1257
+ # Check mapping
1258
+ objs_a = list(comparison.val_a.all())
1259
+ objs_b = list(comparison.val_b.all())
1260
+ map_forwards, map_backwards, added, deleted = comparison.get_mapping(
1261
+ objs_a, objs_b
1262
+ )
1263
+ self.assertEqual(map_forwards, {})
1264
+ self.assertEqual(map_backwards, {})
1265
+ self.assertEqual(added, [0]) # Add new Father Christmas
1266
+ self.assertEqual(deleted, [0]) # Delete old Father Christmas
1267
+
1268
+ def test_panel_label_as_field_label(self):
1269
+ # Just to check whether passing `label` changes field_label
1270
+ event_page = EventPage(title="Event page", slug="event")
1271
+ event_page.speakers.add(
1272
+ EventPageSpeaker(
1273
+ first_name="Father",
1274
+ )
1275
+ )
1276
+
1277
+ comparison = self.comparison_class(
1278
+ EventPage._meta.get_field("speaker"),
1279
+ [
1280
+ partial(
1281
+ self.field_comparison_class,
1282
+ EventPageSpeaker._meta.get_field("first_name"),
1283
+ )
1284
+ ],
1285
+ event_page,
1286
+ event_page,
1287
+ label="Speakers",
1288
+ )
1289
+
1290
+ self.assertEqual(comparison.field_label(), "Speakers")
1291
+
1292
+
1293
+ class TestChildObjectComparison(TestCase):
1294
+ field_comparison_class = compare.FieldComparison
1295
+ comparison_class = compare.ChildObjectComparison
1296
+
1297
+ def test_same_object(self):
1298
+ obj_a = EventPageSpeaker(
1299
+ first_name="Father",
1300
+ last_name="Christmas",
1301
+ )
1302
+
1303
+ obj_b = EventPageSpeaker(
1304
+ first_name="Father",
1305
+ last_name="Christmas",
1306
+ )
1307
+
1308
+ comparison = self.comparison_class(
1309
+ EventPageSpeaker,
1310
+ [
1311
+ partial(
1312
+ self.field_comparison_class,
1313
+ EventPageSpeaker._meta.get_field("first_name"),
1314
+ ),
1315
+ partial(
1316
+ self.field_comparison_class,
1317
+ EventPageSpeaker._meta.get_field("last_name"),
1318
+ ),
1319
+ ],
1320
+ obj_a,
1321
+ obj_b,
1322
+ )
1323
+
1324
+ self.assertFalse(comparison.is_addition())
1325
+ self.assertFalse(comparison.is_deletion())
1326
+ self.assertFalse(comparison.has_changed())
1327
+ self.assertEqual(comparison.get_position_change(), 0)
1328
+ self.assertEqual(comparison.get_num_differences(), 0)
1329
+
1330
+ def test_different_object(self):
1331
+ obj_a = EventPageSpeaker(
1332
+ first_name="Father",
1333
+ last_name="Christmas",
1334
+ )
1335
+
1336
+ obj_b = EventPageSpeaker(
1337
+ first_name="Santa",
1338
+ last_name="Claus",
1339
+ )
1340
+
1341
+ comparison = self.comparison_class(
1342
+ EventPageSpeaker,
1343
+ [
1344
+ partial(
1345
+ self.field_comparison_class,
1346
+ EventPageSpeaker._meta.get_field("first_name"),
1347
+ ),
1348
+ partial(
1349
+ self.field_comparison_class,
1350
+ EventPageSpeaker._meta.get_field("last_name"),
1351
+ ),
1352
+ ],
1353
+ obj_a,
1354
+ obj_b,
1355
+ )
1356
+
1357
+ self.assertFalse(comparison.is_addition())
1358
+ self.assertFalse(comparison.is_deletion())
1359
+ self.assertTrue(comparison.has_changed())
1360
+ self.assertEqual(comparison.get_position_change(), 0)
1361
+ self.assertEqual(comparison.get_num_differences(), 2)
1362
+
1363
+ def test_moved_object(self):
1364
+ obj_a = EventPageSpeaker(
1365
+ first_name="Father",
1366
+ last_name="Christmas",
1367
+ sort_order=1,
1368
+ )
1369
+
1370
+ obj_b = EventPageSpeaker(
1371
+ first_name="Father",
1372
+ last_name="Christmas",
1373
+ sort_order=5,
1374
+ )
1375
+
1376
+ comparison = self.comparison_class(
1377
+ EventPageSpeaker,
1378
+ [
1379
+ partial(
1380
+ self.field_comparison_class,
1381
+ EventPageSpeaker._meta.get_field("first_name"),
1382
+ ),
1383
+ partial(
1384
+ self.field_comparison_class,
1385
+ EventPageSpeaker._meta.get_field("last_name"),
1386
+ ),
1387
+ ],
1388
+ obj_a,
1389
+ obj_b,
1390
+ )
1391
+
1392
+ self.assertFalse(comparison.is_addition())
1393
+ self.assertFalse(comparison.is_deletion())
1394
+ self.assertFalse(comparison.has_changed())
1395
+ self.assertEqual(comparison.get_position_change(), 4)
1396
+ self.assertEqual(comparison.get_num_differences(), 0)
1397
+
1398
+ def test_addition(self):
1399
+ obj = EventPageSpeaker(
1400
+ first_name="Father",
1401
+ last_name="Christmas",
1402
+ )
1403
+
1404
+ comparison = self.comparison_class(
1405
+ EventPageSpeaker,
1406
+ [
1407
+ partial(
1408
+ self.field_comparison_class,
1409
+ EventPageSpeaker._meta.get_field("first_name"),
1410
+ ),
1411
+ partial(
1412
+ self.field_comparison_class,
1413
+ EventPageSpeaker._meta.get_field("last_name"),
1414
+ ),
1415
+ ],
1416
+ None,
1417
+ obj,
1418
+ )
1419
+
1420
+ self.assertTrue(comparison.is_addition())
1421
+ self.assertFalse(comparison.is_deletion())
1422
+ self.assertFalse(comparison.has_changed())
1423
+ self.assertIsNone(comparison.get_position_change(), 0)
1424
+ self.assertEqual(comparison.get_num_differences(), 0)
1425
+
1426
+ def test_deletion(self):
1427
+ obj = EventPageSpeaker(
1428
+ first_name="Father",
1429
+ last_name="Christmas",
1430
+ )
1431
+
1432
+ comparison = self.comparison_class(
1433
+ EventPageSpeaker,
1434
+ [
1435
+ partial(
1436
+ self.field_comparison_class,
1437
+ EventPageSpeaker._meta.get_field("first_name"),
1438
+ ),
1439
+ partial(
1440
+ self.field_comparison_class,
1441
+ EventPageSpeaker._meta.get_field("last_name"),
1442
+ ),
1443
+ ],
1444
+ obj,
1445
+ None,
1446
+ )
1447
+
1448
+ self.assertFalse(comparison.is_addition())
1449
+ self.assertTrue(comparison.is_deletion())
1450
+ self.assertFalse(comparison.has_changed())
1451
+ self.assertIsNone(comparison.get_position_change())
1452
+ self.assertEqual(comparison.get_num_differences(), 0)
1453
+
1454
+
1455
+ class TestChildRelationComparisonUsingPK(TestCase):
1456
+ """Test related objects can be compred if they do not use id for primary key"""
1457
+
1458
+ field_comparison_class = compare.FieldComparison
1459
+ comparison_class = compare.ChildRelationComparison
1460
+
1461
+ def test_has_changed_with_same_id(self):
1462
+ # Head Count was changed but the PK of the child object remained the same.
1463
+ # It should be detected as the same object
1464
+
1465
+ event_page = EventPage(title="Semi Finals", slug="semi-finals-2018")
1466
+ event_page.head_counts.add(
1467
+ HeadCountRelatedModelUsingPK(
1468
+ custom_id=1,
1469
+ head_count=22,
1470
+ )
1471
+ )
1472
+
1473
+ modified_event_page = EventPage(title="Semi Finals", slug="semi-finals-2018")
1474
+ modified_event_page.head_counts.add(
1475
+ HeadCountRelatedModelUsingPK(
1476
+ custom_id=1,
1477
+ head_count=23,
1478
+ )
1479
+ )
1480
+ modified_event_page.head_counts.add(
1481
+ HeadCountRelatedModelUsingPK(
1482
+ head_count=25,
1483
+ )
1484
+ )
1485
+
1486
+ comparison = self.comparison_class(
1487
+ EventPage._meta.get_field("head_counts"),
1488
+ [
1489
+ partial(
1490
+ self.field_comparison_class,
1491
+ HeadCountRelatedModelUsingPK._meta.get_field("head_count"),
1492
+ )
1493
+ ],
1494
+ event_page,
1495
+ modified_event_page,
1496
+ )
1497
+
1498
+ self.assertFalse(comparison.is_field)
1499
+ self.assertTrue(comparison.is_child_relation)
1500
+ self.assertEqual(comparison.field_label(), "Head counts")
1501
+ self.assertTrue(comparison.has_changed())
1502
+
1503
+ # Check mapping
1504
+ objs_a = list(comparison.val_a.all())
1505
+ objs_b = list(comparison.val_b.all())
1506
+ map_forwards, map_backwards, added, deleted = comparison.get_mapping(
1507
+ objs_a, objs_b
1508
+ )
1509
+ self.assertEqual(map_forwards, {0: 0}) # map head count 22 to 23
1510
+ self.assertEqual(map_backwards, {0: 0}) # map head count 23 to 22
1511
+ self.assertEqual(added, [1]) # add second head count
1512
+ self.assertEqual(deleted, [])
1513
+
1514
+ def test_hasnt_changed_with_different_id(self):
1515
+ # Both of the child objects have the same field content but have a
1516
+ # different PK (ID) so they should be detected as separate objects
1517
+ event_page = EventPage(title="Finals", slug="finals-event-abc")
1518
+ event_page.head_counts.add(
1519
+ HeadCountRelatedModelUsingPK(custom_id=1, head_count=220)
1520
+ )
1521
+
1522
+ modified_event_page = EventPage(title="Finals", slug="finals-event-abc")
1523
+ modified_event_page.head_counts.add(
1524
+ HeadCountRelatedModelUsingPK(custom_id=2, head_count=220)
1525
+ )
1526
+
1527
+ comparison = self.comparison_class(
1528
+ EventPage._meta.get_field("head_counts"),
1529
+ [
1530
+ partial(
1531
+ self.field_comparison_class,
1532
+ HeadCountRelatedModelUsingPK._meta.get_field("head_count"),
1533
+ )
1534
+ ],
1535
+ event_page,
1536
+ modified_event_page,
1537
+ )
1538
+
1539
+ self.assertFalse(comparison.is_field)
1540
+ self.assertTrue(comparison.is_child_relation)
1541
+ self.assertEqual(comparison.field_label(), "Head counts")
1542
+ self.assertTrue(comparison.has_changed())
1543
+
1544
+ # Check mapping
1545
+ objs_a = list(comparison.val_a.all())
1546
+ objs_b = list(comparison.val_b.all())
1547
+ map_forwards, map_backwards, added, deleted = comparison.get_mapping(
1548
+ objs_a, objs_b
1549
+ )
1550
+ self.assertEqual(map_forwards, {})
1551
+ self.assertEqual(map_backwards, {})
1552
+ self.assertEqual(added, [0]) # Add new head count
1553
+ self.assertEqual(deleted, [0]) # Delete old head count
testbed/wagtail__wagtail/wagtail/admin/tests/test_contentstate.py ADDED
@@ -0,0 +1,2085 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from unittest.mock import patch
3
+
4
+ from django.test import TestCase
5
+ from draftjs_exporter.dom import DOM
6
+ from draftjs_exporter.html import HTML as HTMLExporter
7
+
8
+ from wagtail.admin.rich_text.converters.contentstate import (
9
+ ContentstateConverter,
10
+ persist_key_for_block,
11
+ )
12
+ from wagtail.embeds.models import Embed
13
+
14
+
15
+ def content_state_equal(v1, v2, match_keys=False):
16
+ "Test whether two contentState structures are equal, ignoring 'key' properties if match_keys=False"
17
+ if type(v1) != type(v2):
18
+ return False
19
+
20
+ if isinstance(v1, dict):
21
+ if set(v1.keys()) != set(v2.keys()):
22
+ return False
23
+ return all(
24
+ (k == "key" and not match_keys)
25
+ or content_state_equal(v, v2[k], match_keys=match_keys)
26
+ for k, v in v1.items()
27
+ )
28
+ elif isinstance(v1, list):
29
+ if len(v1) != len(v2):
30
+ return False
31
+ return all(
32
+ content_state_equal(a, b, match_keys=match_keys) for a, b in zip(v1, v2)
33
+ )
34
+ else:
35
+ return v1 == v2
36
+
37
+
38
+ class TestHtmlToContentState(TestCase):
39
+ fixtures = ["test.json"]
40
+
41
+ def assertContentStateEqual(self, v1, v2, match_keys=False):
42
+ "Assert that two contentState structures are equal, ignoring 'key' properties if match_keys is False"
43
+ self.assertTrue(
44
+ content_state_equal(v1, v2, match_keys=match_keys),
45
+ "%s does not match %s"
46
+ % (json.dumps(v1, indent=4), json.dumps(v2, indent=4)),
47
+ )
48
+
49
+ def test_paragraphs(self):
50
+ converter = ContentstateConverter(features=[])
51
+ result = json.loads(
52
+ converter.from_database_format(
53
+ """
54
+ <p data-block-key='00000'>Hello world!</p>
55
+ <p data-block-key='00001'>Goodbye world!</p>
56
+ """
57
+ )
58
+ )
59
+ self.assertContentStateEqual(
60
+ result,
61
+ {
62
+ "entityMap": {},
63
+ "blocks": [
64
+ {
65
+ "inlineStyleRanges": [],
66
+ "text": "Hello world!",
67
+ "depth": 0,
68
+ "type": "unstyled",
69
+ "key": "00000",
70
+ "entityRanges": [],
71
+ },
72
+ {
73
+ "inlineStyleRanges": [],
74
+ "text": "Goodbye world!",
75
+ "depth": 0,
76
+ "type": "unstyled",
77
+ "key": "00001",
78
+ "entityRanges": [],
79
+ },
80
+ ],
81
+ },
82
+ match_keys=True,
83
+ )
84
+
85
+ def test_unknown_block_becomes_paragraph(self):
86
+ converter = ContentstateConverter(features=[])
87
+ result = json.loads(
88
+ converter.from_database_format(
89
+ """
90
+ <foo>Hello world!</foo>
91
+ <foo>I said hello world!</foo>
92
+ <p>Goodbye world!</p>
93
+ """
94
+ )
95
+ )
96
+ self.assertContentStateEqual(
97
+ result,
98
+ {
99
+ "entityMap": {},
100
+ "blocks": [
101
+ {
102
+ "inlineStyleRanges": [],
103
+ "text": "Hello world!",
104
+ "depth": 0,
105
+ "type": "unstyled",
106
+ "key": "00000",
107
+ "entityRanges": [],
108
+ },
109
+ {
110
+ "inlineStyleRanges": [],
111
+ "text": "I said hello world!",
112
+ "depth": 0,
113
+ "type": "unstyled",
114
+ "key": "00000",
115
+ "entityRanges": [],
116
+ },
117
+ {
118
+ "inlineStyleRanges": [],
119
+ "text": "Goodbye world!",
120
+ "depth": 0,
121
+ "type": "unstyled",
122
+ "key": "00000",
123
+ "entityRanges": [],
124
+ },
125
+ ],
126
+ },
127
+ )
128
+
129
+ def test_bare_text_becomes_paragraph(self):
130
+ converter = ContentstateConverter(features=[])
131
+ result = json.loads(
132
+ converter.from_database_format(
133
+ """
134
+ before
135
+ <p>paragraph</p>
136
+ between
137
+ <p>paragraph</p>
138
+ after
139
+ """
140
+ )
141
+ )
142
+ self.assertContentStateEqual(
143
+ result,
144
+ {
145
+ "entityMap": {},
146
+ "blocks": [
147
+ {
148
+ "inlineStyleRanges": [],
149
+ "text": "before",
150
+ "depth": 0,
151
+ "type": "unstyled",
152
+ "key": "00000",
153
+ "entityRanges": [],
154
+ },
155
+ {
156
+ "inlineStyleRanges": [],
157
+ "text": "paragraph",
158
+ "depth": 0,
159
+ "type": "unstyled",
160
+ "key": "00000",
161
+ "entityRanges": [],
162
+ },
163
+ {
164
+ "inlineStyleRanges": [],
165
+ "text": "between",
166
+ "depth": 0,
167
+ "type": "unstyled",
168
+ "key": "00000",
169
+ "entityRanges": [],
170
+ },
171
+ {
172
+ "inlineStyleRanges": [],
173
+ "text": "paragraph",
174
+ "depth": 0,
175
+ "type": "unstyled",
176
+ "key": "00000",
177
+ "entityRanges": [],
178
+ },
179
+ {
180
+ "inlineStyleRanges": [],
181
+ "text": "after",
182
+ "depth": 0,
183
+ "type": "unstyled",
184
+ "key": "00000",
185
+ "entityRanges": [],
186
+ },
187
+ ],
188
+ },
189
+ )
190
+
191
+ def test_ignore_unrecognised_tags_in_blocks(self):
192
+ converter = ContentstateConverter(features=[])
193
+ result = json.loads(
194
+ converter.from_database_format(
195
+ """
196
+ <p>Hello <foo>frabjuous</foo> world!</p>
197
+ """
198
+ )
199
+ )
200
+ self.assertContentStateEqual(
201
+ result,
202
+ {
203
+ "entityMap": {},
204
+ "blocks": [
205
+ {
206
+ "inlineStyleRanges": [],
207
+ "text": "Hello frabjuous world!",
208
+ "depth": 0,
209
+ "type": "unstyled",
210
+ "key": "00000",
211
+ "entityRanges": [],
212
+ },
213
+ ],
214
+ },
215
+ )
216
+
217
+ def test_inline_styles(self):
218
+ converter = ContentstateConverter(features=["bold", "italic"])
219
+ result = json.loads(
220
+ converter.from_database_format(
221
+ """
222
+ <p>You <b>do <em>not</em> talk</b> about Fight Club.</p>
223
+ """
224
+ )
225
+ )
226
+ self.assertContentStateEqual(
227
+ result,
228
+ {
229
+ "entityMap": {},
230
+ "blocks": [
231
+ {
232
+ "inlineStyleRanges": [
233
+ {"offset": 4, "length": 11, "style": "BOLD"},
234
+ {"offset": 7, "length": 3, "style": "ITALIC"},
235
+ ],
236
+ "text": "You do not talk about Fight Club.",
237
+ "depth": 0,
238
+ "type": "unstyled",
239
+ "key": "00000",
240
+ "entityRanges": [],
241
+ },
242
+ ],
243
+ },
244
+ )
245
+
246
+ def test_inline_styles_at_top_level(self):
247
+ converter = ContentstateConverter(features=["bold", "italic"])
248
+ result = json.loads(
249
+ converter.from_database_format(
250
+ """
251
+ You <b>do <em>not</em> talk</b> about Fight Club.
252
+ """
253
+ )
254
+ )
255
+ self.assertContentStateEqual(
256
+ result,
257
+ {
258
+ "entityMap": {},
259
+ "blocks": [
260
+ {
261
+ "inlineStyleRanges": [
262
+ {"offset": 4, "length": 11, "style": "BOLD"},
263
+ {"offset": 7, "length": 3, "style": "ITALIC"},
264
+ ],
265
+ "text": "You do not talk about Fight Club.",
266
+ "depth": 0,
267
+ "type": "unstyled",
268
+ "key": "00000",
269
+ "entityRanges": [],
270
+ },
271
+ ],
272
+ },
273
+ )
274
+
275
+ def test_inline_styles_at_start_of_bare_block(self):
276
+ converter = ContentstateConverter(features=["bold", "italic"])
277
+ result = json.loads(
278
+ converter.from_database_format(
279
+ """<b>Seriously</b>, stop talking about <i>Fight Club</i> already."""
280
+ )
281
+ )
282
+ self.assertContentStateEqual(
283
+ result,
284
+ {
285
+ "entityMap": {},
286
+ "blocks": [
287
+ {
288
+ "inlineStyleRanges": [
289
+ {"offset": 0, "length": 9, "style": "BOLD"},
290
+ {"offset": 30, "length": 10, "style": "ITALIC"},
291
+ ],
292
+ "text": "Seriously, stop talking about Fight Club already.",
293
+ "depth": 0,
294
+ "type": "unstyled",
295
+ "key": "00000",
296
+ "entityRanges": [],
297
+ },
298
+ ],
299
+ },
300
+ )
301
+
302
+ def test_inline_styles_depend_on_features(self):
303
+ converter = ContentstateConverter(features=["italic", "just-made-it-up"])
304
+ result = json.loads(
305
+ converter.from_database_format(
306
+ """
307
+ <p>You <b>do <em>not</em> talk</b> about Fight Club.</p>
308
+ """
309
+ )
310
+ )
311
+ self.assertContentStateEqual(
312
+ result,
313
+ {
314
+ "entityMap": {},
315
+ "blocks": [
316
+ {
317
+ "inlineStyleRanges": [
318
+ {"offset": 7, "length": 3, "style": "ITALIC"}
319
+ ],
320
+ "text": "You do not talk about Fight Club.",
321
+ "depth": 0,
322
+ "type": "unstyled",
323
+ "key": "00000",
324
+ "entityRanges": [],
325
+ },
326
+ ],
327
+ },
328
+ )
329
+
330
+ def test_ordered_list(self):
331
+ converter = ContentstateConverter(features=["h1", "ol", "bold", "italic"])
332
+ result = json.loads(
333
+ converter.from_database_format(
334
+ """
335
+ <h1 data-block-key='00000'>The rules of Fight Club</h1>
336
+ <ol>
337
+ <li data-block-key='00001'>You do not talk about Fight Club.</li>
338
+ <li data-block-key='00002'>You <b>do <em>not</em> talk</b> about Fight Club.</li>
339
+ </ol>
340
+ """
341
+ )
342
+ )
343
+ self.assertContentStateEqual(
344
+ result,
345
+ {
346
+ "entityMap": {},
347
+ "blocks": [
348
+ {
349
+ "inlineStyleRanges": [],
350
+ "text": "The rules of Fight Club",
351
+ "depth": 0,
352
+ "type": "header-one",
353
+ "key": "00000",
354
+ "entityRanges": [],
355
+ },
356
+ {
357
+ "inlineStyleRanges": [],
358
+ "text": "You do not talk about Fight Club.",
359
+ "depth": 0,
360
+ "type": "ordered-list-item",
361
+ "key": "00001",
362
+ "entityRanges": [],
363
+ },
364
+ {
365
+ "inlineStyleRanges": [
366
+ {"offset": 4, "length": 11, "style": "BOLD"},
367
+ {"offset": 7, "length": 3, "style": "ITALIC"},
368
+ ],
369
+ "text": "You do not talk about Fight Club.",
370
+ "depth": 0,
371
+ "type": "ordered-list-item",
372
+ "key": "00002",
373
+ "entityRanges": [],
374
+ },
375
+ ],
376
+ },
377
+ match_keys=True,
378
+ )
379
+
380
+ def test_nested_list(self):
381
+ converter = ContentstateConverter(features=["h1", "ul"])
382
+ result = json.loads(
383
+ converter.from_database_format(
384
+ """
385
+ <h1 data-block-key='00000'>Shopping list</h1>
386
+ <ul>
387
+ <li data-block-key='00001'>Milk</li>
388
+ <li data-block-key='00002'>
389
+ Flour
390
+ <ul>
391
+ <li data-block-key='00003'>Plain</li>
392
+ <li data-block-key='00004'>Self-raising</li>
393
+ </ul>
394
+ </li>
395
+ <li data-block-key='00005'>Eggs</li>
396
+ </ul>
397
+ """
398
+ )
399
+ )
400
+ self.assertContentStateEqual(
401
+ result,
402
+ {
403
+ "entityMap": {},
404
+ "blocks": [
405
+ {
406
+ "inlineStyleRanges": [],
407
+ "text": "Shopping list",
408
+ "depth": 0,
409
+ "type": "header-one",
410
+ "key": "00000",
411
+ "entityRanges": [],
412
+ },
413
+ {
414
+ "inlineStyleRanges": [],
415
+ "text": "Milk",
416
+ "depth": 0,
417
+ "type": "unordered-list-item",
418
+ "key": "00001",
419
+ "entityRanges": [],
420
+ },
421
+ {
422
+ "inlineStyleRanges": [],
423
+ "text": "Flour",
424
+ "depth": 0,
425
+ "type": "unordered-list-item",
426
+ "key": "00002",
427
+ "entityRanges": [],
428
+ },
429
+ {
430
+ "inlineStyleRanges": [],
431
+ "text": "Plain",
432
+ "depth": 1,
433
+ "type": "unordered-list-item",
434
+ "key": "00003",
435
+ "entityRanges": [],
436
+ },
437
+ {
438
+ "inlineStyleRanges": [],
439
+ "text": "Self-raising",
440
+ "depth": 1,
441
+ "type": "unordered-list-item",
442
+ "key": "00004",
443
+ "entityRanges": [],
444
+ },
445
+ {
446
+ "inlineStyleRanges": [],
447
+ "text": "Eggs",
448
+ "depth": 0,
449
+ "type": "unordered-list-item",
450
+ "key": "00005",
451
+ "entityRanges": [],
452
+ },
453
+ ],
454
+ },
455
+ match_keys=True,
456
+ )
457
+
458
+ def test_external_link(self):
459
+ converter = ContentstateConverter(features=["link"])
460
+ result = json.loads(
461
+ converter.from_database_format(
462
+ """
463
+ <p>an <a href="http://wagtail.org">external</a> link</p>
464
+ """
465
+ )
466
+ )
467
+ self.assertContentStateEqual(
468
+ result,
469
+ {
470
+ "entityMap": {
471
+ "0": {
472
+ "mutability": "MUTABLE",
473
+ "type": "LINK",
474
+ "data": {"url": "http://wagtail.org"},
475
+ }
476
+ },
477
+ "blocks": [
478
+ {
479
+ "inlineStyleRanges": [],
480
+ "text": "an external link",
481
+ "depth": 0,
482
+ "type": "unstyled",
483
+ "key": "00000",
484
+ "entityRanges": [{"offset": 3, "length": 8, "key": 0}],
485
+ },
486
+ ],
487
+ },
488
+ )
489
+
490
+ def test_link_in_bare_text(self):
491
+ converter = ContentstateConverter(features=["link"])
492
+ result = json.loads(
493
+ converter.from_database_format(
494
+ """an <a href="http://wagtail.org">external</a> link"""
495
+ )
496
+ )
497
+ self.assertContentStateEqual(
498
+ result,
499
+ {
500
+ "entityMap": {
501
+ "0": {
502
+ "mutability": "MUTABLE",
503
+ "type": "LINK",
504
+ "data": {"url": "http://wagtail.org"},
505
+ }
506
+ },
507
+ "blocks": [
508
+ {
509
+ "inlineStyleRanges": [],
510
+ "text": "an external link",
511
+ "depth": 0,
512
+ "type": "unstyled",
513
+ "key": "00000",
514
+ "entityRanges": [{"offset": 3, "length": 8, "key": 0}],
515
+ },
516
+ ],
517
+ },
518
+ )
519
+
520
+ def test_link_at_start_of_bare_text(self):
521
+ converter = ContentstateConverter(features=["link"])
522
+ result = json.loads(
523
+ converter.from_database_format(
524
+ """<a href="http://wagtail.org">an external link</a> and <a href="http://torchbox.com">another</a>"""
525
+ )
526
+ )
527
+ self.assertContentStateEqual(
528
+ result,
529
+ {
530
+ "entityMap": {
531
+ "0": {
532
+ "mutability": "MUTABLE",
533
+ "type": "LINK",
534
+ "data": {"url": "http://wagtail.org"},
535
+ },
536
+ "1": {
537
+ "mutability": "MUTABLE",
538
+ "type": "LINK",
539
+ "data": {"url": "http://torchbox.com"},
540
+ },
541
+ },
542
+ "blocks": [
543
+ {
544
+ "inlineStyleRanges": [],
545
+ "text": "an external link and another",
546
+ "depth": 0,
547
+ "type": "unstyled",
548
+ "key": "00000",
549
+ "entityRanges": [
550
+ {"offset": 0, "length": 16, "key": 0},
551
+ {"offset": 21, "length": 7, "key": 1},
552
+ ],
553
+ },
554
+ ],
555
+ },
556
+ )
557
+
558
+ def test_page_link(self):
559
+ converter = ContentstateConverter(features=["link"])
560
+ result = json.loads(
561
+ converter.from_database_format(
562
+ """
563
+ <p>an <a linktype="page" id="3">internal</a> link</p>
564
+ """
565
+ )
566
+ )
567
+ self.assertContentStateEqual(
568
+ result,
569
+ {
570
+ "entityMap": {
571
+ "0": {
572
+ "mutability": "MUTABLE",
573
+ "type": "LINK",
574
+ "data": {"id": 3, "url": "/events/", "parentId": 2},
575
+ }
576
+ },
577
+ "blocks": [
578
+ {
579
+ "inlineStyleRanges": [],
580
+ "text": "an internal link",
581
+ "depth": 0,
582
+ "type": "unstyled",
583
+ "key": "00000",
584
+ "entityRanges": [{"offset": 3, "length": 8, "key": 0}],
585
+ },
586
+ ],
587
+ },
588
+ )
589
+
590
+ def test_broken_page_link(self):
591
+ converter = ContentstateConverter(features=["link"])
592
+ result = json.loads(
593
+ converter.from_database_format(
594
+ """
595
+ <p>an <a linktype="page" id="9999">internal</a> link</p>
596
+ """
597
+ )
598
+ )
599
+ self.assertContentStateEqual(
600
+ result,
601
+ {
602
+ "entityMap": {
603
+ "0": {
604
+ "mutability": "MUTABLE",
605
+ "type": "LINK",
606
+ "data": {
607
+ "id": 9999,
608
+ "url": None,
609
+ "parentId": None,
610
+ },
611
+ }
612
+ },
613
+ "blocks": [
614
+ {
615
+ "inlineStyleRanges": [],
616
+ "text": "an internal link",
617
+ "depth": 0,
618
+ "type": "unstyled",
619
+ "key": "00000",
620
+ "entityRanges": [{"offset": 3, "length": 8, "key": 0}],
621
+ },
622
+ ],
623
+ },
624
+ )
625
+
626
+ def test_link_to_root_page(self):
627
+ converter = ContentstateConverter(features=["link"])
628
+ result = json.loads(
629
+ converter.from_database_format(
630
+ """
631
+ <p>an <a linktype="page" id="1">internal</a> link</p>
632
+ """
633
+ )
634
+ )
635
+ self.assertContentStateEqual(
636
+ result,
637
+ {
638
+ "entityMap": {
639
+ "0": {
640
+ "mutability": "MUTABLE",
641
+ "type": "LINK",
642
+ "data": {"id": 1, "url": None, "parentId": None},
643
+ }
644
+ },
645
+ "blocks": [
646
+ {
647
+ "inlineStyleRanges": [],
648
+ "text": "an internal link",
649
+ "depth": 0,
650
+ "type": "unstyled",
651
+ "key": "00000",
652
+ "entityRanges": [{"offset": 3, "length": 8, "key": 0}],
653
+ },
654
+ ],
655
+ },
656
+ )
657
+
658
+ def test_document_link(self):
659
+ converter = ContentstateConverter(features=["document-link"])
660
+ result = json.loads(
661
+ converter.from_database_format(
662
+ """
663
+ <p>a <a linktype="document" id="1">document</a> link</p>
664
+ """
665
+ )
666
+ )
667
+ self.assertContentStateEqual(
668
+ result,
669
+ {
670
+ "entityMap": {
671
+ "0": {
672
+ "mutability": "MUTABLE",
673
+ "type": "DOCUMENT",
674
+ "data": {
675
+ "id": 1,
676
+ "url": "/documents/1/test.pdf",
677
+ "filename": "test.pdf",
678
+ },
679
+ }
680
+ },
681
+ "blocks": [
682
+ {
683
+ "inlineStyleRanges": [],
684
+ "text": "a document link",
685
+ "depth": 0,
686
+ "type": "unstyled",
687
+ "key": "00000",
688
+ "entityRanges": [{"offset": 2, "length": 8, "key": 0}],
689
+ },
690
+ ],
691
+ },
692
+ )
693
+
694
+ def test_broken_document_link(self):
695
+ converter = ContentstateConverter(features=["document-link"])
696
+ result = json.loads(
697
+ converter.from_database_format(
698
+ """
699
+ <p>a <a linktype="document" id="9999">document</a> link</p>
700
+ """
701
+ )
702
+ )
703
+ self.assertContentStateEqual(
704
+ result,
705
+ {
706
+ "entityMap": {
707
+ "0": {
708
+ "mutability": "MUTABLE",
709
+ "type": "DOCUMENT",
710
+ "data": {"id": 9999},
711
+ }
712
+ },
713
+ "blocks": [
714
+ {
715
+ "inlineStyleRanges": [],
716
+ "text": "a document link",
717
+ "depth": 0,
718
+ "type": "unstyled",
719
+ "key": "00000",
720
+ "entityRanges": [{"offset": 2, "length": 8, "key": 0}],
721
+ },
722
+ ],
723
+ },
724
+ )
725
+
726
+ def test_document_link_with_missing_id(self):
727
+ converter = ContentstateConverter(features=["document-link"])
728
+ result = json.loads(
729
+ converter.from_database_format(
730
+ """
731
+ <p>a <a linktype="document">document</a> link</p>
732
+ """
733
+ )
734
+ )
735
+ self.assertContentStateEqual(
736
+ result,
737
+ {
738
+ "entityMap": {
739
+ "0": {"mutability": "MUTABLE", "type": "DOCUMENT", "data": {}}
740
+ },
741
+ "blocks": [
742
+ {
743
+ "inlineStyleRanges": [],
744
+ "text": "a document link",
745
+ "depth": 0,
746
+ "type": "unstyled",
747
+ "key": "00000",
748
+ "entityRanges": [{"offset": 2, "length": 8, "key": 0}],
749
+ },
750
+ ],
751
+ },
752
+ )
753
+
754
+ def test_image_embed(self):
755
+ converter = ContentstateConverter(features=["image"])
756
+ result = json.loads(
757
+ converter.from_database_format(
758
+ """
759
+ <p>before</p>
760
+ <embed embedtype="image" alt="an image" id="1" format="left" />
761
+ <p>after</p>
762
+ """
763
+ )
764
+ )
765
+ self.assertContentStateEqual(
766
+ result,
767
+ {
768
+ "blocks": [
769
+ {
770
+ "key": "00000",
771
+ "inlineStyleRanges": [],
772
+ "entityRanges": [],
773
+ "depth": 0,
774
+ "text": "before",
775
+ "type": "unstyled",
776
+ },
777
+ {
778
+ "key": "00000",
779
+ "inlineStyleRanges": [],
780
+ "entityRanges": [{"key": 0, "offset": 0, "length": 1}],
781
+ "depth": 0,
782
+ "text": " ",
783
+ "type": "atomic",
784
+ },
785
+ {
786
+ "key": "00000",
787
+ "inlineStyleRanges": [],
788
+ "entityRanges": [],
789
+ "depth": 0,
790
+ "text": "after",
791
+ "type": "unstyled",
792
+ },
793
+ ],
794
+ "entityMap": {
795
+ "0": {
796
+ "data": {
797
+ "format": "left",
798
+ "alt": "an image",
799
+ "id": "1",
800
+ "src": "/media/not-found",
801
+ },
802
+ "mutability": "IMMUTABLE",
803
+ "type": "IMAGE",
804
+ }
805
+ },
806
+ },
807
+ )
808
+
809
+ def test_add_spacer_paragraph_between_image_embeds(self):
810
+ converter = ContentstateConverter(features=["image"])
811
+ result = json.loads(
812
+ converter.from_database_format(
813
+ """
814
+ <embed embedtype="image" alt="an image" id="1" format="left" />
815
+ <embed embedtype="image" alt="an image" id="1" format="left" />
816
+ """
817
+ )
818
+ )
819
+ self.assertContentStateEqual(
820
+ result,
821
+ {
822
+ "blocks": [
823
+ {
824
+ "key": "00000",
825
+ "inlineStyleRanges": [],
826
+ "entityRanges": [],
827
+ "depth": 0,
828
+ "text": "",
829
+ "type": "unstyled",
830
+ },
831
+ {
832
+ "key": "00000",
833
+ "inlineStyleRanges": [],
834
+ "entityRanges": [{"key": 0, "offset": 0, "length": 1}],
835
+ "depth": 0,
836
+ "text": " ",
837
+ "type": "atomic",
838
+ },
839
+ {
840
+ "key": "00000",
841
+ "inlineStyleRanges": [],
842
+ "entityRanges": [],
843
+ "depth": 0,
844
+ "text": "",
845
+ "type": "unstyled",
846
+ },
847
+ {
848
+ "key": "00000",
849
+ "inlineStyleRanges": [],
850
+ "entityRanges": [{"key": 1, "offset": 0, "length": 1}],
851
+ "depth": 0,
852
+ "text": " ",
853
+ "type": "atomic",
854
+ },
855
+ {
856
+ "key": "00000",
857
+ "inlineStyleRanges": [],
858
+ "entityRanges": [],
859
+ "depth": 0,
860
+ "text": "",
861
+ "type": "unstyled",
862
+ },
863
+ ],
864
+ "entityMap": {
865
+ "0": {
866
+ "data": {
867
+ "format": "left",
868
+ "alt": "an image",
869
+ "id": "1",
870
+ "src": "/media/not-found",
871
+ },
872
+ "mutability": "IMMUTABLE",
873
+ "type": "IMAGE",
874
+ },
875
+ "1": {
876
+ "data": {
877
+ "format": "left",
878
+ "alt": "an image",
879
+ "id": "1",
880
+ "src": "/media/not-found",
881
+ },
882
+ "mutability": "IMMUTABLE",
883
+ "type": "IMAGE",
884
+ },
885
+ },
886
+ },
887
+ )
888
+
889
+ def test_image_after_list(self):
890
+ """
891
+ There should be no spacer paragraph inserted between a list and an image
892
+ """
893
+ converter = ContentstateConverter(features=["ul", "image"])
894
+ result = json.loads(
895
+ converter.from_database_format(
896
+ """
897
+ <ul>
898
+ <li>Milk</li>
899
+ <li>Eggs</li>
900
+ </ul>
901
+ <embed embedtype="image" alt="an image" id="1" format="left" />
902
+ <ul>
903
+ <li>More milk</li>
904
+ <li>More eggs</li>
905
+ </ul>
906
+ """
907
+ )
908
+ )
909
+ self.assertContentStateEqual(
910
+ result,
911
+ {
912
+ "entityMap": {
913
+ "0": {
914
+ "data": {
915
+ "format": "left",
916
+ "alt": "an image",
917
+ "id": "1",
918
+ "src": "/media/not-found",
919
+ },
920
+ "mutability": "IMMUTABLE",
921
+ "type": "IMAGE",
922
+ },
923
+ },
924
+ "blocks": [
925
+ {
926
+ "inlineStyleRanges": [],
927
+ "text": "Milk",
928
+ "depth": 0,
929
+ "type": "unordered-list-item",
930
+ "key": "00000",
931
+ "entityRanges": [],
932
+ },
933
+ {
934
+ "inlineStyleRanges": [],
935
+ "text": "Eggs",
936
+ "depth": 0,
937
+ "type": "unordered-list-item",
938
+ "key": "00000",
939
+ "entityRanges": [],
940
+ },
941
+ {
942
+ "key": "00000",
943
+ "inlineStyleRanges": [],
944
+ "entityRanges": [{"key": 1, "offset": 0, "length": 1}],
945
+ "depth": 0,
946
+ "text": " ",
947
+ "type": "atomic",
948
+ },
949
+ {
950
+ "inlineStyleRanges": [],
951
+ "text": "More milk",
952
+ "depth": 0,
953
+ "type": "unordered-list-item",
954
+ "key": "00000",
955
+ "entityRanges": [],
956
+ },
957
+ {
958
+ "inlineStyleRanges": [],
959
+ "text": "More eggs",
960
+ "depth": 0,
961
+ "type": "unordered-list-item",
962
+ "key": "00000",
963
+ "entityRanges": [],
964
+ },
965
+ ],
966
+ },
967
+ )
968
+
969
+ @patch("wagtail.embeds.embeds.get_embed")
970
+ def test_media_embed(self, get_embed):
971
+ get_embed.return_value = Embed(
972
+ url="https://www.youtube.com/watch?v=Kh0Y2hVe_bw",
973
+ max_width=None,
974
+ type="video",
975
+ html="test html",
976
+ title="what are birds",
977
+ author_name="look around you",
978
+ provider_name="YouTube",
979
+ thumbnail_url="http://test/thumbnail.url",
980
+ width=1000,
981
+ height=1000,
982
+ )
983
+
984
+ converter = ContentstateConverter(features=["embed"])
985
+ result = json.loads(
986
+ converter.from_database_format(
987
+ """
988
+ <p>before</p>
989
+ <embed embedtype="media" url="https://www.youtube.com/watch?v=Kh0Y2hVe_bw" />
990
+ <p>after</p>
991
+ """
992
+ )
993
+ )
994
+ self.assertContentStateEqual(
995
+ result,
996
+ {
997
+ "blocks": [
998
+ {
999
+ "key": "00000",
1000
+ "inlineStyleRanges": [],
1001
+ "entityRanges": [],
1002
+ "depth": 0,
1003
+ "text": "before",
1004
+ "type": "unstyled",
1005
+ },
1006
+ {
1007
+ "key": "00000",
1008
+ "inlineStyleRanges": [],
1009
+ "entityRanges": [{"key": 0, "offset": 0, "length": 1}],
1010
+ "depth": 0,
1011
+ "text": " ",
1012
+ "type": "atomic",
1013
+ },
1014
+ {
1015
+ "key": "00000",
1016
+ "inlineStyleRanges": [],
1017
+ "entityRanges": [],
1018
+ "depth": 0,
1019
+ "text": "after",
1020
+ "type": "unstyled",
1021
+ },
1022
+ ],
1023
+ "entityMap": {
1024
+ "0": {
1025
+ "data": {
1026
+ "thumbnail": "http://test/thumbnail.url",
1027
+ "embedType": "video",
1028
+ "providerName": "YouTube",
1029
+ "title": "what are birds",
1030
+ "authorName": "look around you",
1031
+ "url": "https://www.youtube.com/watch?v=Kh0Y2hVe_bw",
1032
+ },
1033
+ "mutability": "IMMUTABLE",
1034
+ "type": "EMBED",
1035
+ }
1036
+ },
1037
+ },
1038
+ )
1039
+
1040
+ @patch("wagtail.embeds.embeds.get_embed")
1041
+ def test_add_spacer_paras_between_media_embeds(self, get_embed):
1042
+ get_embed.return_value = Embed(
1043
+ url="https://www.youtube.com/watch?v=Kh0Y2hVe_bw",
1044
+ max_width=None,
1045
+ type="video",
1046
+ html="test html",
1047
+ title="what are birds",
1048
+ author_name="look around you",
1049
+ provider_name="YouTube",
1050
+ thumbnail_url="http://test/thumbnail.url",
1051
+ width=1000,
1052
+ height=1000,
1053
+ )
1054
+
1055
+ converter = ContentstateConverter(features=["embed"])
1056
+ result = json.loads(
1057
+ converter.from_database_format(
1058
+ """
1059
+ <embed embedtype="media" url="https://www.youtube.com/watch?v=Kh0Y2hVe_bw" />
1060
+ <embed embedtype="media" url="https://www.youtube.com/watch?v=Kh0Y2hVe_bw" />
1061
+ """
1062
+ )
1063
+ )
1064
+ self.assertContentStateEqual(
1065
+ result,
1066
+ {
1067
+ "blocks": [
1068
+ {
1069
+ "key": "00000",
1070
+ "inlineStyleRanges": [],
1071
+ "entityRanges": [],
1072
+ "depth": 0,
1073
+ "text": "",
1074
+ "type": "unstyled",
1075
+ },
1076
+ {
1077
+ "key": "00000",
1078
+ "inlineStyleRanges": [],
1079
+ "entityRanges": [{"key": 0, "offset": 0, "length": 1}],
1080
+ "depth": 0,
1081
+ "text": " ",
1082
+ "type": "atomic",
1083
+ },
1084
+ {
1085
+ "key": "00000",
1086
+ "inlineStyleRanges": [],
1087
+ "entityRanges": [],
1088
+ "depth": 0,
1089
+ "text": "",
1090
+ "type": "unstyled",
1091
+ },
1092
+ {
1093
+ "key": "00000",
1094
+ "inlineStyleRanges": [],
1095
+ "entityRanges": [{"key": 1, "offset": 0, "length": 1}],
1096
+ "depth": 0,
1097
+ "text": " ",
1098
+ "type": "atomic",
1099
+ },
1100
+ {
1101
+ "key": "00000",
1102
+ "inlineStyleRanges": [],
1103
+ "entityRanges": [],
1104
+ "depth": 0,
1105
+ "text": "",
1106
+ "type": "unstyled",
1107
+ },
1108
+ ],
1109
+ "entityMap": {
1110
+ "0": {
1111
+ "data": {
1112
+ "thumbnail": "http://test/thumbnail.url",
1113
+ "embedType": "video",
1114
+ "providerName": "YouTube",
1115
+ "title": "what are birds",
1116
+ "authorName": "look around you",
1117
+ "url": "https://www.youtube.com/watch?v=Kh0Y2hVe_bw",
1118
+ },
1119
+ "mutability": "IMMUTABLE",
1120
+ "type": "EMBED",
1121
+ },
1122
+ "1": {
1123
+ "data": {
1124
+ "thumbnail": "http://test/thumbnail.url",
1125
+ "embedType": "video",
1126
+ "providerName": "YouTube",
1127
+ "title": "what are birds",
1128
+ "authorName": "look around you",
1129
+ "url": "https://www.youtube.com/watch?v=Kh0Y2hVe_bw",
1130
+ },
1131
+ "mutability": "IMMUTABLE",
1132
+ "type": "EMBED",
1133
+ },
1134
+ },
1135
+ },
1136
+ )
1137
+
1138
+ def test_hr(self):
1139
+ converter = ContentstateConverter(features=["hr"])
1140
+ result = json.loads(
1141
+ converter.from_database_format(
1142
+ """
1143
+ <p>before</p>
1144
+ <hr />
1145
+ <p>after</p>
1146
+ """
1147
+ )
1148
+ )
1149
+ self.assertContentStateEqual(
1150
+ result,
1151
+ {
1152
+ "blocks": [
1153
+ {
1154
+ "key": "00000",
1155
+ "inlineStyleRanges": [],
1156
+ "entityRanges": [],
1157
+ "depth": 0,
1158
+ "text": "before",
1159
+ "type": "unstyled",
1160
+ },
1161
+ {
1162
+ "key": "00000",
1163
+ "inlineStyleRanges": [],
1164
+ "entityRanges": [{"key": 0, "offset": 0, "length": 1}],
1165
+ "depth": 0,
1166
+ "text": " ",
1167
+ "type": "atomic",
1168
+ },
1169
+ {
1170
+ "key": "00000",
1171
+ "inlineStyleRanges": [],
1172
+ "entityRanges": [],
1173
+ "depth": 0,
1174
+ "text": "after",
1175
+ "type": "unstyled",
1176
+ },
1177
+ ],
1178
+ "entityMap": {
1179
+ "0": {
1180
+ "data": {},
1181
+ "mutability": "IMMUTABLE",
1182
+ "type": "HORIZONTAL_RULE",
1183
+ }
1184
+ },
1185
+ },
1186
+ )
1187
+
1188
+ def test_add_spacer_paragraph_between_hrs(self):
1189
+ converter = ContentstateConverter(features=["hr"])
1190
+ result = json.loads(
1191
+ converter.from_database_format(
1192
+ """
1193
+ <hr />
1194
+ <hr />
1195
+ """
1196
+ )
1197
+ )
1198
+ self.assertContentStateEqual(
1199
+ result,
1200
+ {
1201
+ "blocks": [
1202
+ {
1203
+ "key": "00000",
1204
+ "inlineStyleRanges": [],
1205
+ "entityRanges": [],
1206
+ "depth": 0,
1207
+ "text": "",
1208
+ "type": "unstyled",
1209
+ },
1210
+ {
1211
+ "key": "00000",
1212
+ "inlineStyleRanges": [],
1213
+ "entityRanges": [{"key": 0, "offset": 0, "length": 1}],
1214
+ "depth": 0,
1215
+ "text": " ",
1216
+ "type": "atomic",
1217
+ },
1218
+ {
1219
+ "key": "00000",
1220
+ "inlineStyleRanges": [],
1221
+ "entityRanges": [],
1222
+ "depth": 0,
1223
+ "text": "",
1224
+ "type": "unstyled",
1225
+ },
1226
+ {
1227
+ "key": "00000",
1228
+ "inlineStyleRanges": [],
1229
+ "entityRanges": [{"key": 1, "offset": 0, "length": 1}],
1230
+ "depth": 0,
1231
+ "text": " ",
1232
+ "type": "atomic",
1233
+ },
1234
+ {
1235
+ "key": "00000",
1236
+ "inlineStyleRanges": [],
1237
+ "entityRanges": [],
1238
+ "depth": 0,
1239
+ "text": "",
1240
+ "type": "unstyled",
1241
+ },
1242
+ ],
1243
+ "entityMap": {
1244
+ "0": {
1245
+ "data": {},
1246
+ "mutability": "IMMUTABLE",
1247
+ "type": "HORIZONTAL_RULE",
1248
+ },
1249
+ "1": {
1250
+ "data": {},
1251
+ "mutability": "IMMUTABLE",
1252
+ "type": "HORIZONTAL_RULE",
1253
+ },
1254
+ },
1255
+ },
1256
+ )
1257
+
1258
+ def test_block_element_in_paragraph(self):
1259
+ converter = ContentstateConverter(features=["hr"])
1260
+ result = json.loads(
1261
+ converter.from_database_format(
1262
+ """
1263
+ <p>before<hr />after</p>
1264
+ """
1265
+ )
1266
+ )
1267
+ self.assertContentStateEqual(
1268
+ result,
1269
+ {
1270
+ "blocks": [
1271
+ {
1272
+ "key": "00000",
1273
+ "inlineStyleRanges": [],
1274
+ "entityRanges": [],
1275
+ "depth": 0,
1276
+ "text": "before",
1277
+ "type": "unstyled",
1278
+ },
1279
+ {
1280
+ "key": "00000",
1281
+ "inlineStyleRanges": [],
1282
+ "entityRanges": [{"key": 0, "offset": 0, "length": 1}],
1283
+ "depth": 0,
1284
+ "text": " ",
1285
+ "type": "atomic",
1286
+ },
1287
+ {
1288
+ "key": "00000",
1289
+ "inlineStyleRanges": [],
1290
+ "entityRanges": [],
1291
+ "depth": 0,
1292
+ "text": "after",
1293
+ "type": "unstyled",
1294
+ },
1295
+ ],
1296
+ "entityMap": {
1297
+ "0": {
1298
+ "data": {},
1299
+ "mutability": "IMMUTABLE",
1300
+ "type": "HORIZONTAL_RULE",
1301
+ }
1302
+ },
1303
+ },
1304
+ )
1305
+
1306
+ def test_br_element_in_paragraph(self):
1307
+ converter = ContentstateConverter(features=[])
1308
+ result = json.loads(
1309
+ converter.from_database_format(
1310
+ """
1311
+ <p>before<br/>after</p>
1312
+ """
1313
+ )
1314
+ )
1315
+ self.assertContentStateEqual(
1316
+ result,
1317
+ {
1318
+ "entityMap": {},
1319
+ "blocks": [
1320
+ {
1321
+ "key": "00000",
1322
+ "inlineStyleRanges": [],
1323
+ "entityRanges": [],
1324
+ "depth": 0,
1325
+ "text": "before\nafter",
1326
+ "type": "unstyled",
1327
+ }
1328
+ ],
1329
+ },
1330
+ )
1331
+
1332
+ def test_br_element_between_paragraphs(self):
1333
+ converter = ContentstateConverter(features=[])
1334
+ result = json.loads(
1335
+ converter.from_database_format(
1336
+ """
1337
+ <p>before</p>
1338
+ <br />
1339
+ <p>after</p>
1340
+ """
1341
+ )
1342
+ )
1343
+ self.assertContentStateEqual(
1344
+ result,
1345
+ {
1346
+ "entityMap": {},
1347
+ "blocks": [
1348
+ {
1349
+ "key": "00000",
1350
+ "inlineStyleRanges": [],
1351
+ "entityRanges": [],
1352
+ "depth": 0,
1353
+ "text": "before",
1354
+ "type": "unstyled",
1355
+ },
1356
+ {
1357
+ "key": "00000",
1358
+ "inlineStyleRanges": [],
1359
+ "entityRanges": [],
1360
+ "depth": 0,
1361
+ "text": "after",
1362
+ "type": "unstyled",
1363
+ },
1364
+ ],
1365
+ },
1366
+ )
1367
+
1368
+ def test_block_element_in_empty_paragraph(self):
1369
+ converter = ContentstateConverter(features=["hr"])
1370
+ result = json.loads(
1371
+ converter.from_database_format(
1372
+ """
1373
+ <p><hr /></p>
1374
+ """
1375
+ )
1376
+ )
1377
+ # ignoring the paragraph completely would probably be better,
1378
+ # but we'll settle for an empty preceding paragraph and not crashing as the next best thing...
1379
+ # (and if it's the first/last block we actually do want a spacer paragraph anyhow)
1380
+ self.assertContentStateEqual(
1381
+ result,
1382
+ {
1383
+ "blocks": [
1384
+ {
1385
+ "key": "00000",
1386
+ "inlineStyleRanges": [],
1387
+ "entityRanges": [],
1388
+ "depth": 0,
1389
+ "text": "",
1390
+ "type": "unstyled",
1391
+ },
1392
+ {
1393
+ "key": "00000",
1394
+ "inlineStyleRanges": [],
1395
+ "entityRanges": [{"key": 0, "offset": 0, "length": 1}],
1396
+ "depth": 0,
1397
+ "text": " ",
1398
+ "type": "atomic",
1399
+ },
1400
+ {
1401
+ "key": "00000",
1402
+ "inlineStyleRanges": [],
1403
+ "entityRanges": [],
1404
+ "depth": 0,
1405
+ "text": "",
1406
+ "type": "unstyled",
1407
+ },
1408
+ ],
1409
+ "entityMap": {
1410
+ "0": {
1411
+ "data": {},
1412
+ "mutability": "IMMUTABLE",
1413
+ "type": "HORIZONTAL_RULE",
1414
+ }
1415
+ },
1416
+ },
1417
+ )
1418
+
1419
+ def test_html_entities(self):
1420
+ converter = ContentstateConverter(features=[])
1421
+ result = json.loads(
1422
+ converter.from_database_format(
1423
+ """
1424
+ <p>Arthur &quot;two sheds&quot; Jackson &lt;the third&gt; &amp; his wife</p>
1425
+ """
1426
+ )
1427
+ )
1428
+ self.assertContentStateEqual(
1429
+ result,
1430
+ {
1431
+ "entityMap": {},
1432
+ "blocks": [
1433
+ {
1434
+ "inlineStyleRanges": [],
1435
+ "text": 'Arthur "two sheds" Jackson <the third> & his wife',
1436
+ "depth": 0,
1437
+ "type": "unstyled",
1438
+ "key": "00000",
1439
+ "entityRanges": [],
1440
+ },
1441
+ ],
1442
+ },
1443
+ )
1444
+
1445
+ def test_collapse_targeted_whitespace_characters(self):
1446
+ # We expect all targeted whitespace characters (one or more consecutively)
1447
+ # to be replaced by a single space. (\xa0 is a non-breaking whitespace)
1448
+ converter = ContentstateConverter(features=[])
1449
+ result = json.loads(
1450
+ converter.from_database_format(
1451
+ """
1452
+ <p>Multiple whitespaces: should be reduced</p>
1453
+ <p>Multiple non-breaking whitespace characters: \xa0\xa0\xa0 should be preserved</p>
1454
+ """
1455
+ )
1456
+ )
1457
+ self.assertContentStateEqual(
1458
+ result,
1459
+ {
1460
+ "entityMap": {},
1461
+ "blocks": [
1462
+ {
1463
+ "inlineStyleRanges": [],
1464
+ "text": "Multiple whitespaces: should be reduced",
1465
+ "depth": 0,
1466
+ "type": "unstyled",
1467
+ "key": "00000",
1468
+ "entityRanges": [],
1469
+ },
1470
+ {
1471
+ "inlineStyleRanges": [],
1472
+ "text": "Multiple non-breaking whitespace characters: \xa0\xa0\xa0 should be preserved",
1473
+ "depth": 0,
1474
+ "type": "unstyled",
1475
+ "key": "00000",
1476
+ "entityRanges": [],
1477
+ },
1478
+ ],
1479
+ },
1480
+ )
1481
+
1482
+ def test_extra_end_tag_before(self):
1483
+ converter = ContentstateConverter(features=[])
1484
+ result = json.loads(
1485
+ converter.from_database_format(
1486
+ """
1487
+ </p>
1488
+ <p>Before</p>
1489
+ """
1490
+ )
1491
+ )
1492
+ # The leading </p> tag should be ignored instead of blowing up with a
1493
+ # pop from empty list error
1494
+ self.assertContentStateEqual(
1495
+ result,
1496
+ {
1497
+ "entityMap": {},
1498
+ "blocks": [
1499
+ {
1500
+ "inlineStyleRanges": [],
1501
+ "text": "Before",
1502
+ "depth": 0,
1503
+ "type": "unstyled",
1504
+ "key": "00000",
1505
+ "entityRanges": [],
1506
+ },
1507
+ ],
1508
+ },
1509
+ )
1510
+
1511
+ def test_extra_end_tag_after(self):
1512
+ converter = ContentstateConverter(features=[])
1513
+ result = json.loads(
1514
+ converter.from_database_format(
1515
+ """
1516
+ <p>After</p>
1517
+ </p>
1518
+ """
1519
+ )
1520
+ )
1521
+ # The tailing </p> tag should be ignored instead of blowing up with a
1522
+ # pop from empty list error
1523
+ self.assertContentStateEqual(
1524
+ result,
1525
+ {
1526
+ "entityMap": {},
1527
+ "blocks": [
1528
+ {
1529
+ "inlineStyleRanges": [],
1530
+ "text": "After",
1531
+ "depth": 0,
1532
+ "type": "unstyled",
1533
+ "key": "00000",
1534
+ "entityRanges": [],
1535
+ },
1536
+ ],
1537
+ },
1538
+ )
1539
+
1540
+ def test_p_with_class(self):
1541
+ # Test support for custom conversion rules which require correct treatment of
1542
+ # CSS precedence in HTMLRuleset. Here, <p class="intro"> should match the
1543
+ # 'p[class="intro"]' rule rather than 'p' and thus become an 'intro-paragraph' block
1544
+ converter = ContentstateConverter(features=["intro"])
1545
+ result = json.loads(
1546
+ converter.from_database_format(
1547
+ """
1548
+ <p class="intro">before</p>
1549
+ <p>after</p>
1550
+ """
1551
+ )
1552
+ )
1553
+ self.assertContentStateEqual(
1554
+ result,
1555
+ {
1556
+ "blocks": [
1557
+ {
1558
+ "key": "00000",
1559
+ "inlineStyleRanges": [],
1560
+ "entityRanges": [],
1561
+ "depth": 0,
1562
+ "text": "before",
1563
+ "type": "intro-paragraph",
1564
+ },
1565
+ {
1566
+ "key": "00000",
1567
+ "inlineStyleRanges": [],
1568
+ "entityRanges": [],
1569
+ "depth": 0,
1570
+ "text": "after",
1571
+ "type": "unstyled",
1572
+ },
1573
+ ],
1574
+ "entityMap": {},
1575
+ },
1576
+ )
1577
+
1578
+ def test_image_inside_paragraph(self):
1579
+ # In Draftail's data model, images are block-level elements and therefore
1580
+ # split up preceding / following text into their own paragraphs
1581
+ converter = ContentstateConverter(features=["image"])
1582
+ result = json.loads(
1583
+ converter.from_database_format(
1584
+ """
1585
+ <p>before <embed embedtype="image" alt="an image" id="1" format="left" /> after</p>
1586
+ """
1587
+ )
1588
+ )
1589
+ self.assertContentStateEqual(
1590
+ result,
1591
+ {
1592
+ "blocks": [
1593
+ {
1594
+ "key": "00000",
1595
+ "inlineStyleRanges": [],
1596
+ "entityRanges": [],
1597
+ "depth": 0,
1598
+ "text": "before",
1599
+ "type": "unstyled",
1600
+ },
1601
+ {
1602
+ "key": "00000",
1603
+ "inlineStyleRanges": [],
1604
+ "entityRanges": [{"key": 0, "offset": 0, "length": 1}],
1605
+ "depth": 0,
1606
+ "text": " ",
1607
+ "type": "atomic",
1608
+ },
1609
+ {
1610
+ "key": "00000",
1611
+ "inlineStyleRanges": [],
1612
+ "entityRanges": [],
1613
+ "depth": 0,
1614
+ "text": "after",
1615
+ "type": "unstyled",
1616
+ },
1617
+ ],
1618
+ "entityMap": {
1619
+ "0": {
1620
+ "data": {
1621
+ "format": "left",
1622
+ "alt": "an image",
1623
+ "id": "1",
1624
+ "src": "/media/not-found",
1625
+ },
1626
+ "mutability": "IMMUTABLE",
1627
+ "type": "IMAGE",
1628
+ }
1629
+ },
1630
+ },
1631
+ )
1632
+
1633
+ def test_image_inside_style(self):
1634
+ # https://github.com/wagtail/wagtail/issues/4602 - ensure that an <embed> inside
1635
+ # an inline style is handled. This is not valid in Draftail as images are block-level,
1636
+ # but should be handled without errors, splitting the image into its own block
1637
+ converter = ContentstateConverter(features=["image", "italic"])
1638
+ result = json.loads(
1639
+ converter.from_database_format(
1640
+ """
1641
+ <p><i>before <embed embedtype="image" alt="an image" id="1" format="left" /> after</i></p>
1642
+ <p><i><embed embedtype="image" alt="an image" id="1" format="left" /></i></p>
1643
+ """
1644
+ )
1645
+ )
1646
+ self.assertContentStateEqual(
1647
+ result,
1648
+ {
1649
+ "blocks": [
1650
+ {
1651
+ "key": "00000",
1652
+ "inlineStyleRanges": [
1653
+ {"offset": 0, "length": 6, "style": "ITALIC"}
1654
+ ],
1655
+ "entityRanges": [],
1656
+ "depth": 0,
1657
+ "text": "before",
1658
+ "type": "unstyled",
1659
+ },
1660
+ {
1661
+ "key": "00000",
1662
+ "inlineStyleRanges": [],
1663
+ "entityRanges": [{"key": 0, "offset": 0, "length": 1}],
1664
+ "depth": 0,
1665
+ "text": " ",
1666
+ "type": "atomic",
1667
+ },
1668
+ {
1669
+ "key": "00000",
1670
+ "inlineStyleRanges": [
1671
+ {"offset": 0, "length": 5, "style": "ITALIC"}
1672
+ ],
1673
+ "entityRanges": [],
1674
+ "depth": 0,
1675
+ "text": "after",
1676
+ "type": "unstyled",
1677
+ },
1678
+ {
1679
+ "key": "00000",
1680
+ "inlineStyleRanges": [
1681
+ {"offset": 0, "length": 0, "style": "ITALIC"}
1682
+ ],
1683
+ "entityRanges": [],
1684
+ "depth": 0,
1685
+ "text": "",
1686
+ "type": "unstyled",
1687
+ },
1688
+ {
1689
+ "key": "00000",
1690
+ "inlineStyleRanges": [],
1691
+ "entityRanges": [{"key": 1, "offset": 0, "length": 1}],
1692
+ "depth": 0,
1693
+ "text": " ",
1694
+ "type": "atomic",
1695
+ },
1696
+ {
1697
+ "key": "00000",
1698
+ "inlineStyleRanges": [
1699
+ {"offset": 0, "length": 0, "style": "ITALIC"}
1700
+ ],
1701
+ "entityRanges": [],
1702
+ "depth": 0,
1703
+ "text": "",
1704
+ "type": "unstyled",
1705
+ },
1706
+ ],
1707
+ "entityMap": {
1708
+ "0": {
1709
+ "data": {
1710
+ "format": "left",
1711
+ "alt": "an image",
1712
+ "id": "1",
1713
+ "src": "/media/not-found",
1714
+ },
1715
+ "mutability": "IMMUTABLE",
1716
+ "type": "IMAGE",
1717
+ },
1718
+ "1": {
1719
+ "data": {
1720
+ "format": "left",
1721
+ "alt": "an image",
1722
+ "id": "1",
1723
+ "src": "/media/not-found",
1724
+ },
1725
+ "mutability": "IMMUTABLE",
1726
+ "type": "IMAGE",
1727
+ },
1728
+ },
1729
+ },
1730
+ )
1731
+
1732
+ def test_image_inside_link(self):
1733
+ # https://github.com/wagtail/wagtail/issues/4602 - ensure that an <embed> inside
1734
+ # a link is handled. This is not valid in Draftail as images are block-level,
1735
+ # but should be handled without errors, splitting the image into its own block
1736
+ converter = ContentstateConverter(features=["image", "link"])
1737
+ result = json.loads(
1738
+ converter.from_database_format(
1739
+ """
1740
+ <p><a href="https://wagtail.org">before <embed embedtype="image" alt="an image" id="1" format="left" /> after</a></p>
1741
+ <p><a href="https://wagtail.org"><embed embedtype="image" alt="an image" id="1" format="left" /></a></p>
1742
+ """
1743
+ )
1744
+ )
1745
+ self.assertContentStateEqual(
1746
+ result,
1747
+ {
1748
+ "blocks": [
1749
+ {
1750
+ "key": "00000",
1751
+ "inlineStyleRanges": [],
1752
+ "entityRanges": [{"key": 0, "offset": 0, "length": 6}],
1753
+ "depth": 0,
1754
+ "text": "before",
1755
+ "type": "unstyled",
1756
+ },
1757
+ {
1758
+ "key": "00000",
1759
+ "inlineStyleRanges": [],
1760
+ "entityRanges": [{"key": 1, "offset": 0, "length": 1}],
1761
+ "depth": 0,
1762
+ "text": " ",
1763
+ "type": "atomic",
1764
+ },
1765
+ {
1766
+ "key": "00000",
1767
+ "inlineStyleRanges": [],
1768
+ "entityRanges": [{"key": 0, "offset": 0, "length": 5}],
1769
+ "depth": 0,
1770
+ "text": "after",
1771
+ "type": "unstyled",
1772
+ },
1773
+ {
1774
+ "key": "00000",
1775
+ "inlineStyleRanges": [],
1776
+ "entityRanges": [{"key": 2, "offset": 0, "length": 0}],
1777
+ "depth": 0,
1778
+ "text": "",
1779
+ "type": "unstyled",
1780
+ },
1781
+ {
1782
+ "key": "00000",
1783
+ "inlineStyleRanges": [],
1784
+ "entityRanges": [{"key": 3, "offset": 0, "length": 1}],
1785
+ "depth": 0,
1786
+ "text": " ",
1787
+ "type": "atomic",
1788
+ },
1789
+ {
1790
+ "key": "00000",
1791
+ "inlineStyleRanges": [],
1792
+ "entityRanges": [{"key": 2, "offset": 0, "length": 0}],
1793
+ "depth": 0,
1794
+ "text": "",
1795
+ "type": "unstyled",
1796
+ },
1797
+ ],
1798
+ "entityMap": {
1799
+ "0": {
1800
+ "mutability": "MUTABLE",
1801
+ "type": "LINK",
1802
+ "data": {"url": "https://wagtail.org"},
1803
+ },
1804
+ "1": {
1805
+ "data": {
1806
+ "format": "left",
1807
+ "alt": "an image",
1808
+ "id": "1",
1809
+ "src": "/media/not-found",
1810
+ },
1811
+ "mutability": "IMMUTABLE",
1812
+ "type": "IMAGE",
1813
+ },
1814
+ "2": {
1815
+ "mutability": "MUTABLE",
1816
+ "type": "LINK",
1817
+ "data": {"url": "https://wagtail.org"},
1818
+ },
1819
+ "3": {
1820
+ "data": {
1821
+ "format": "left",
1822
+ "alt": "an image",
1823
+ "id": "1",
1824
+ "src": "/media/not-found",
1825
+ },
1826
+ "mutability": "IMMUTABLE",
1827
+ "type": "IMAGE",
1828
+ },
1829
+ },
1830
+ },
1831
+ )
1832
+
1833
+
1834
+ class TestContentStateToHtml(TestCase):
1835
+ def test_external_link(self):
1836
+ converter = ContentstateConverter(features=["link"])
1837
+ contentstate_json = json.dumps(
1838
+ {
1839
+ "entityMap": {
1840
+ "0": {
1841
+ "mutability": "MUTABLE",
1842
+ "type": "LINK",
1843
+ "data": {"url": "http://wagtail.org"},
1844
+ }
1845
+ },
1846
+ "blocks": [
1847
+ {
1848
+ "inlineStyleRanges": [],
1849
+ "text": "an external link",
1850
+ "depth": 0,
1851
+ "type": "unstyled",
1852
+ "key": "00000",
1853
+ "entityRanges": [{"offset": 3, "length": 8, "key": 0}],
1854
+ },
1855
+ ],
1856
+ }
1857
+ )
1858
+
1859
+ result = converter.to_database_format(contentstate_json)
1860
+ self.assertEqual(
1861
+ result,
1862
+ '<p data-block-key="00000">an <a href="http://wagtail.org">external</a> link</p>',
1863
+ )
1864
+
1865
+ def test_local_link(self):
1866
+ converter = ContentstateConverter(features=["link"])
1867
+ contentstate_json = json.dumps(
1868
+ {
1869
+ "entityMap": {
1870
+ "0": {
1871
+ "mutability": "MUTABLE",
1872
+ "type": "LINK",
1873
+ "data": {"url": "/some/local/path/"},
1874
+ }
1875
+ },
1876
+ "blocks": [
1877
+ {
1878
+ "inlineStyleRanges": [],
1879
+ "text": "an external link",
1880
+ "depth": 0,
1881
+ "type": "unstyled",
1882
+ "key": "00000",
1883
+ "entityRanges": [{"offset": 3, "length": 8, "key": 0}],
1884
+ },
1885
+ ],
1886
+ }
1887
+ )
1888
+
1889
+ result = converter.to_database_format(contentstate_json)
1890
+ self.assertEqual(
1891
+ result,
1892
+ '<p data-block-key="00000">an <a href="/some/local/path/">external</a> link</p>',
1893
+ )
1894
+
1895
+ def test_reject_javascript_link(self):
1896
+ converter = ContentstateConverter(features=["link"])
1897
+ contentstate_json = json.dumps(
1898
+ {
1899
+ "entityMap": {
1900
+ "0": {
1901
+ "mutability": "MUTABLE",
1902
+ "type": "LINK",
1903
+ "data": {"url": "javascript:alert('oh no')"},
1904
+ }
1905
+ },
1906
+ "blocks": [
1907
+ {
1908
+ "inlineStyleRanges": [],
1909
+ "text": "an external link",
1910
+ "depth": 0,
1911
+ "type": "unstyled",
1912
+ "key": "00000",
1913
+ "entityRanges": [{"offset": 3, "length": 8, "key": 0}],
1914
+ },
1915
+ ],
1916
+ }
1917
+ )
1918
+
1919
+ result = converter.to_database_format(contentstate_json)
1920
+ self.assertEqual(
1921
+ result, '<p data-block-key="00000">an <a>external</a> link</p>'
1922
+ )
1923
+
1924
+ def test_paragraphs_retain_keys(self):
1925
+ converter = ContentstateConverter(features=[])
1926
+ contentState = json.dumps(
1927
+ {
1928
+ "entityMap": {},
1929
+ "blocks": [
1930
+ {
1931
+ "inlineStyleRanges": [],
1932
+ "text": "Hello world!",
1933
+ "depth": 0,
1934
+ "type": "unstyled",
1935
+ "key": "00000",
1936
+ "entityRanges": [],
1937
+ },
1938
+ {
1939
+ "inlineStyleRanges": [],
1940
+ "text": "Goodbye world!",
1941
+ "depth": 0,
1942
+ "type": "unstyled",
1943
+ "key": "00001",
1944
+ "entityRanges": [],
1945
+ },
1946
+ ],
1947
+ }
1948
+ )
1949
+ result = converter.to_database_format(contentState)
1950
+ self.assertHTMLEqual(
1951
+ result,
1952
+ """
1953
+ <p data-block-key='00000'>Hello world!</p>
1954
+ <p data-block-key='00001'>Goodbye world!</p>
1955
+ """,
1956
+ )
1957
+
1958
+ def test_wrapped_block_retains_key(self):
1959
+ # Test a block which uses a wrapper correctly receives the key defined on the inner element
1960
+ converter = ContentstateConverter(features=["h1", "ol", "bold", "italic"])
1961
+ result = converter.to_database_format(
1962
+ json.dumps(
1963
+ {
1964
+ "entityMap": {},
1965
+ "blocks": [
1966
+ {
1967
+ "inlineStyleRanges": [],
1968
+ "text": "The rules of Fight Club",
1969
+ "depth": 0,
1970
+ "type": "header-one",
1971
+ "key": "00000",
1972
+ "entityRanges": [],
1973
+ },
1974
+ {
1975
+ "inlineStyleRanges": [],
1976
+ "text": "You do not talk about Fight Club.",
1977
+ "depth": 0,
1978
+ "type": "ordered-list-item",
1979
+ "key": "00001",
1980
+ "entityRanges": [],
1981
+ },
1982
+ {
1983
+ "inlineStyleRanges": [],
1984
+ "text": "You do not talk about Fight Club.",
1985
+ "depth": 0,
1986
+ "type": "ordered-list-item",
1987
+ "key": "00002",
1988
+ "entityRanges": [],
1989
+ },
1990
+ ],
1991
+ }
1992
+ )
1993
+ )
1994
+ self.assertHTMLEqual(
1995
+ result,
1996
+ """
1997
+ <h1 data-block-key='00000'>The rules of Fight Club</h1>
1998
+ <ol>
1999
+ <li data-block-key='00001'>You do not talk about Fight Club.</li>
2000
+ <li data-block-key='00002'>You do not talk about Fight Club.</li>
2001
+ </ol>
2002
+ """,
2003
+ )
2004
+
2005
+ def test_wrap_block_function(self):
2006
+ # Draft JS exporter's block_map config can also contain a function to handle a particular block
2007
+ # Test that persist_key_for_block still works with such a function, making the resultant conversion
2008
+ # keep the same block key between html and contentstate
2009
+ exporter_config = {
2010
+ "block_map": {
2011
+ "unstyled": persist_key_for_block(
2012
+ lambda props: DOM.create_element("p", {}, props["children"])
2013
+ ),
2014
+ },
2015
+ "style_map": {},
2016
+ "entity_decorators": {},
2017
+ "composite_decorators": [],
2018
+ "engine": DOM.STRING,
2019
+ }
2020
+ contentState = {
2021
+ "entityMap": {},
2022
+ "blocks": [
2023
+ {
2024
+ "inlineStyleRanges": [],
2025
+ "text": "Hello world!",
2026
+ "depth": 0,
2027
+ "type": "unstyled",
2028
+ "key": "00000",
2029
+ "entityRanges": [],
2030
+ },
2031
+ {
2032
+ "inlineStyleRanges": [],
2033
+ "text": "Goodbye world!",
2034
+ "depth": 0,
2035
+ "type": "unstyled",
2036
+ "key": "00001",
2037
+ "entityRanges": [],
2038
+ },
2039
+ ],
2040
+ }
2041
+ result = HTMLExporter(exporter_config).render(contentState)
2042
+ self.assertHTMLEqual(
2043
+ result,
2044
+ """
2045
+ <p data-block-key='00000'>Hello world!</p>
2046
+ <p data-block-key='00001'>Goodbye world!</p>
2047
+ """,
2048
+ )
2049
+
2050
+ def test_style_fallback(self):
2051
+ # Test a block which uses an invalid inline style, and will be removed
2052
+ converter = ContentstateConverter(features=[])
2053
+
2054
+ with self.assertLogs(level="WARNING") as log_output:
2055
+ result = converter.to_database_format(
2056
+ json.dumps(
2057
+ {
2058
+ "entityMap": {},
2059
+ "blocks": [
2060
+ {
2061
+ "inlineStyleRanges": [
2062
+ {"offset": 0, "length": 12, "style": "UNDERLINE"}
2063
+ ],
2064
+ "text": "Hello world!",
2065
+ "depth": 0,
2066
+ "type": "unstyled",
2067
+ "key": "00000",
2068
+ "entityRanges": [],
2069
+ },
2070
+ ],
2071
+ }
2072
+ )
2073
+ )
2074
+
2075
+ self.assertHTMLEqual(
2076
+ result,
2077
+ """
2078
+ <p data-block-key="00000">
2079
+ Hello world!
2080
+ </p>
2081
+ """,
2082
+ )
2083
+ self.assertIn(
2084
+ 'Missing config for "UNDERLINE". Deleting style.', log_output.output[0]
2085
+ )
testbed/wagtail__wagtail/wagtail/admin/tests/test_dbwhitelister.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from bs4 import BeautifulSoup
2
+ from django.test import TestCase
3
+
4
+ from wagtail.admin.rich_text.converters.editor_html import EditorHTMLConverter
5
+
6
+
7
+ class TestDbWhitelisterMethods(TestCase):
8
+ def setUp(self):
9
+ self.whitelister = EditorHTMLConverter().whitelister
10
+
11
+ def test_clean_tag_node_div(self):
12
+ soup = BeautifulSoup("<div>foo</div>", "html5lib")
13
+ tag = soup.div
14
+ self.assertEqual(tag.name, "div")
15
+ self.whitelister.clean_tag_node(soup, tag)
16
+ self.assertEqual(tag.name, "p")
17
+
18
+ def test_clean_tag_node_with_data_embedtype(self):
19
+ soup = BeautifulSoup(
20
+ '<p><a data-embedtype="image" data-id=1 data-format="left" data-alt="bar" irrelevant="baz">foo</a></p>',
21
+ "html5lib",
22
+ )
23
+ tag = soup.p
24
+ self.whitelister.clean_tag_node(soup, tag)
25
+ self.assertEqual(
26
+ str(tag), '<p><embed alt="bar" embedtype="image" format="left" id="1"/></p>'
27
+ )
28
+
29
+ def test_clean_tag_node_with_data_linktype(self):
30
+ soup = BeautifulSoup(
31
+ '<a data-linktype="document" data-id="1" irrelevant="baz">foo</a>',
32
+ "html5lib",
33
+ )
34
+ tag = soup.a
35
+ self.whitelister.clean_tag_node(soup, tag)
36
+ self.assertEqual(str(tag), '<a id="1" linktype="document">foo</a>')
37
+
38
+ def test_clean_tag_node(self):
39
+ soup = BeautifulSoup('<a irrelevant="baz">foo</a>', "html5lib")
40
+ tag = soup.a
41
+ self.whitelister.clean_tag_node(soup, tag)
42
+ self.assertEqual(str(tag), "<a>foo</a>")
43
+
44
+
45
+ class TestDbWhitelister(TestCase):
46
+ def setUp(self):
47
+ self.whitelister = EditorHTMLConverter().whitelister
48
+
49
+ def assertHtmlEqual(self, str1, str2):
50
+ """
51
+ Assert that two HTML strings are equal at the DOM level
52
+ (necessary because we can't guarantee the order that attributes are output in)
53
+ """
54
+ self.assertEqual(
55
+ BeautifulSoup(str1, "html5lib"), BeautifulSoup(str2, "html5lib")
56
+ )
57
+
58
+ def test_page_link_is_rewritten(self):
59
+ input_html = (
60
+ '<p>Look at the <a data-linktype="page" data-id="2" href="/">lovely homepage</a>'
61
+ ' of my <a href="http://wagtail.org/">Wagtail</a> site</p>'
62
+ )
63
+ output_html = self.whitelister.clean(input_html)
64
+ expected = (
65
+ '<p>Look at the <a linktype="page" id="2">lovely homepage</a>'
66
+ ' of my <a href="http://wagtail.org/">Wagtail</a> site</p>'
67
+ )
68
+ self.assertHtmlEqual(expected, output_html)
69
+
70
+ def test_document_link_is_rewritten(self):
71
+ input_html = (
72
+ '<p>Look at our <a data-linktype="document" data-id="1" href="/documents/1/brochure.pdf">'
73
+ "horribly oversized brochure</a></p>"
74
+ )
75
+ output_html = self.whitelister.clean(input_html)
76
+ expected = '<p>Look at our <a linktype="document" id="1">horribly oversized brochure</a></p>'
77
+ self.assertHtmlEqual(expected, output_html)
78
+
79
+ def test_image_embed_is_rewritten(self):
80
+ input_html = (
81
+ '<p>OMG look at this picture of a kitten:</p><figure data-embedtype="image" data-id="5"'
82
+ ' data-format="image-with-caption" data-alt="A cute kitten" class="fancy-image">'
83
+ '<img src="/media/images/kitten.jpg" width="320" height="200" alt="A cute kitten" />'
84
+ "<figcaption>A kitten, yesterday.</figcaption></figure>"
85
+ )
86
+ output_html = self.whitelister.clean(input_html)
87
+ expected = (
88
+ '<p>OMG look at this picture of a kitten:</p><embed embedtype="image" id="5"'
89
+ ' format="image-with-caption" alt="A cute kitten" />'
90
+ )
91
+ self.assertHtmlEqual(expected, output_html)
92
+
93
+ def test_media_embed_is_rewritten(self):
94
+ input_html = (
95
+ "<p>OMG look at this video of a kitten: "
96
+ '<iframe data-embedtype="media" data-url="https://www.youtube.com/watch?v=dQw4w9WgXcQ" width="640"'
97
+ ' height="480" src="//www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allowfullscreen></iframe></p>'
98
+ )
99
+ output_html = self.whitelister.clean(input_html)
100
+ expected = (
101
+ "<p>OMG look at this video of a kitten:"
102
+ ' <embed embedtype="media" url="https://www.youtube.com/watch?v=dQw4w9WgXcQ" /></p>'
103
+ )
104
+ self.assertHtmlEqual(expected, output_html)
105
+
106
+ def test_div_conversion(self):
107
+ # DIVs should be converted to P, and all whitelist / conversion rules still applied
108
+ input_html = (
109
+ '<p>before</p><div class="shiny">OMG <b>look</b> at this <blink>video</blink> of a kitten: '
110
+ '<iframe data-embedtype="media" data-url="https://www.youtube.com/watch?v=dQw4w9WgXcQ"'
111
+ ' width="640" height="480"'
112
+ ' src="//www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allowfullscreen></iframe></div><p>after</p>'
113
+ )
114
+ output_html = self.whitelister.clean(input_html)
115
+ expected = (
116
+ "<p>before</p><p>OMG <b>look</b> at this video of a kitten:"
117
+ ' <embed embedtype="media" url="https://www.youtube.com/watch?v=dQw4w9WgXcQ" /></p><p>after</p>'
118
+ )
119
+ self.assertHtmlEqual(expected, output_html)
120
+
121
+ def test_whitelist_with_feature_list(self):
122
+ converter = EditorHTMLConverter(
123
+ features=["h1", "bold", "link", "something_i_just_made_up"]
124
+ )
125
+ input_html = (
126
+ "<h1>this heading is allowed</h1> <h2>but not this one</h2> "
127
+ "<p><b>bold</b> <i>italic</i></p>"
128
+ '<p><a href="http://torchbox.com">external link</a> <a data-linktype="page" data-id="2" href="/">internal link</a></p>'
129
+ )
130
+ output_html = converter.to_database_format(input_html)
131
+ expected = (
132
+ "<h1>this heading is allowed</h1> but not this one "
133
+ "<p><b>bold</b> italic</p>"
134
+ '<p><a href="http://torchbox.com">external link</a> <a linktype="page" id="2">internal link</a></p>'
135
+ )
136
+ self.assertHtmlEqual(expected, output_html)
testbed/wagtail__wagtail/wagtail/admin/tests/test_dismissibles.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.test import TestCase
2
+ from django.urls import reverse
3
+
4
+ from wagtail.test.utils import WagtailTestUtils
5
+ from wagtail.users.models import UserProfile
6
+
7
+
8
+ class TestDismissiblesView(TestCase, WagtailTestUtils):
9
+ def setUp(self):
10
+ self.user = self.login()
11
+ self.profile = UserProfile.get_for_user(self.user)
12
+ self.url = reverse("wagtailadmin_dismissibles")
13
+
14
+ def test_get_initial(self):
15
+ response = self.client.get(self.url)
16
+ self.profile.refresh_from_db()
17
+ self.assertEqual(response.status_code, 200)
18
+ self.assertEqual(response.json(), {})
19
+ self.assertEqual(self.user.wagtail_userprofile.dismissibles, {})
20
+
21
+ def test_patch_valid(self):
22
+ response = self.client.patch(
23
+ self.url, data={"foo": "bar"}, content_type="application/json"
24
+ )
25
+ self.profile.refresh_from_db()
26
+ self.assertEqual(response.status_code, 200)
27
+ self.assertEqual(response.json(), {"foo": "bar"})
28
+ self.assertEqual(self.user.wagtail_userprofile.dismissibles, {"foo": "bar"})
29
+
30
+ def test_patch_invalid(self):
31
+ response = self.client.patch(
32
+ self.url, data="invalid", content_type="application/json"
33
+ )
34
+ self.profile.refresh_from_db()
35
+ self.assertEqual(response.status_code, 400)
36
+ self.assertEqual(self.user.wagtail_userprofile.dismissibles, {})
37
+
38
+ def test_post(self):
39
+ # The view only accepts GET and PATCH
40
+ response = self.client.post(self.url, data={"foo": "bar"})
41
+ self.profile.refresh_from_db()
42
+ self.assertEqual(response.status_code, 405)
43
+ self.assertEqual(self.user.wagtail_userprofile.dismissibles, {})
44
+
45
+ def test_get_without_userprofile(self):
46
+ # GET should work even if the user doesn't have a UserProfile,
47
+ # but it shouldn't create one
48
+ self.profile.delete()
49
+ response = self.client.get(self.url)
50
+ self.user.refresh_from_db()
51
+ self.assertEqual(response.status_code, 200)
52
+ self.assertEqual(response.json(), {})
53
+ self.assertIsNone(getattr(self.user, "wagtail_userprofile", None))
54
+
55
+ def test_patch_without_userprofile(self):
56
+ # PATCH should work even if the user doesn't have a UserProfile,
57
+ # in which case it should create one
58
+ self.profile.delete()
59
+ response = self.client.patch(
60
+ self.url, data={"foo": "bar"}, content_type="application/json"
61
+ )
62
+ self.user.refresh_from_db()
63
+ self.assertEqual(response.status_code, 200)
64
+ self.assertEqual(response.json(), {"foo": "bar"})
65
+ self.assertEqual(self.user.wagtail_userprofile.dismissibles, {"foo": "bar"})
testbed/wagtail__wagtail/wagtail/admin/tests/test_edit_handlers.py ADDED
@@ -0,0 +1,1746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import date, datetime
2
+ from functools import wraps
3
+ from unittest import mock
4
+
5
+ from django import forms
6
+ from django.conf import settings
7
+ from django.contrib.auth import get_user_model
8
+ from django.contrib.auth.models import AnonymousUser, Permission
9
+ from django.core import checks
10
+ from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured
11
+ from django.test import RequestFactory, TestCase, override_settings
12
+ from django.utils.html import json_script
13
+ from freezegun import freeze_time
14
+ from pytz import utc
15
+
16
+ from wagtail.admin.forms import WagtailAdminModelForm, WagtailAdminPageForm
17
+ from wagtail.admin.panels import (
18
+ CommentPanel,
19
+ FieldPanel,
20
+ FieldRowPanel,
21
+ InlinePanel,
22
+ MultiFieldPanel,
23
+ ObjectList,
24
+ PageChooserPanel,
25
+ PublishingPanel,
26
+ TabbedInterface,
27
+ extract_panel_definitions_from_model_class,
28
+ get_form_for_model,
29
+ )
30
+ from wagtail.admin.rich_text import DraftailRichTextArea
31
+ from wagtail.admin.widgets import (
32
+ AdminAutoHeightTextInput,
33
+ AdminDateInput,
34
+ AdminPageChooser,
35
+ )
36
+ from wagtail.models import Comment, CommentReply, Page, Site
37
+ from wagtail.test.testapp.forms import ValidatedPageForm
38
+ from wagtail.test.testapp.models import (
39
+ EventPage,
40
+ EventPageChooserModel,
41
+ EventPageSpeaker,
42
+ PageChooserModel,
43
+ RestaurantPage,
44
+ RestaurantTag,
45
+ SimplePage,
46
+ ValidatedPage,
47
+ )
48
+ from wagtail.test.utils import WagtailTestUtils
49
+
50
+
51
+ class TestGetFormForModel(TestCase):
52
+ def test_get_form_without_model(self):
53
+ edit_handler = ObjectList()
54
+ with self.assertRaisesMessage(
55
+ AttributeError,
56
+ "ObjectList is not bound to a model yet. "
57
+ "Use `.bind_to_model(model)` before using this method.",
58
+ ):
59
+ edit_handler.get_form_class()
60
+
61
+ def test_get_form_for_model_without_explicit_fields(self):
62
+ # Failing to pass a 'fields' argument to get_form_for_model IS valid, and should result in
63
+ # a form with no fields.
64
+ EventPageForm = get_form_for_model(
65
+ EventPage,
66
+ form_class=WagtailAdminPageForm,
67
+ )
68
+ self.assertTrue(issubclass(EventPageForm, WagtailAdminPageForm))
69
+ form = EventPageForm()
70
+ self.assertNotIn("title", form.fields)
71
+ self.assertNotIn("path", form.fields)
72
+
73
+ def test_get_form_for_model_without_formsets(self):
74
+ EventPageForm = get_form_for_model(
75
+ EventPage,
76
+ form_class=WagtailAdminPageForm,
77
+ fields=["title", "slug", "date_from", "date_to"],
78
+ )
79
+ form = EventPageForm()
80
+
81
+ # form should be a subclass of WagtailAdminModelForm
82
+ self.assertTrue(issubclass(EventPageForm, WagtailAdminModelForm))
83
+ # form should contain a title field (from the base Page)
84
+ self.assertEqual(type(form.fields["title"]), forms.CharField)
85
+ # and 'date_from' from EventPage
86
+ self.assertEqual(type(form.fields["date_from"]), forms.DateField)
87
+ # the widget should be overridden with AdminDateInput as per FORM_FIELD_OVERRIDES
88
+ self.assertEqual(type(form.fields["date_from"].widget), AdminDateInput)
89
+
90
+ # treebeard's 'path' field should be excluded
91
+ self.assertNotIn("path", form.fields)
92
+
93
+ def test_get_form_for_model_with_formsets(self):
94
+ EventPageForm = get_form_for_model(
95
+ EventPage,
96
+ form_class=WagtailAdminPageForm,
97
+ fields=["title", "slug", "date_from", "date_to"],
98
+ formsets=["speakers", "related_links"],
99
+ )
100
+ form = EventPageForm()
101
+
102
+ # all child relations become formsets by default
103
+ self.assertIn("speakers", form.formsets)
104
+ self.assertIn("related_links", form.formsets)
105
+
106
+ def test_direct_form_field_overrides(self):
107
+ # Test that field overrides defined through DIRECT_FORM_FIELD_OVERRIDES
108
+ # are applied
109
+
110
+ SimplePageForm = get_form_for_model(
111
+ SimplePage,
112
+ form_class=WagtailAdminPageForm,
113
+ fields=["title", "slug", "content"],
114
+ )
115
+ self.assertTrue(issubclass(SimplePageForm, WagtailAdminPageForm))
116
+ simple_form = SimplePageForm()
117
+ # plain TextFields should use AdminAutoHeightTextInput as the widget
118
+ self.assertEqual(
119
+ type(simple_form.fields["content"].widget), AdminAutoHeightTextInput
120
+ )
121
+
122
+ # This override should NOT be applied to subclasses of TextField such as
123
+ # RichTextField - they should retain their default widgets
124
+ EventPageForm = get_form_for_model(
125
+ EventPage, form_class=WagtailAdminPageForm, fields=["title", "slug", "body"]
126
+ )
127
+ event_form = EventPageForm()
128
+ self.assertEqual(type(event_form.fields["body"].widget), DraftailRichTextArea)
129
+
130
+ def test_get_form_for_model_with_specific_fields(self):
131
+ EventPageForm = get_form_for_model(
132
+ EventPage,
133
+ form_class=WagtailAdminPageForm,
134
+ fields=["date_from"],
135
+ formsets=["speakers"],
136
+ )
137
+ form = EventPageForm()
138
+
139
+ # form should contain date_from but not title
140
+ self.assertEqual(type(form.fields["date_from"]), forms.DateField)
141
+ self.assertEqual(type(form.fields["date_from"].widget), AdminDateInput)
142
+ self.assertNotIn("title", form.fields)
143
+
144
+ # formsets should include speakers but not related_links
145
+ self.assertIn("speakers", form.formsets)
146
+ self.assertNotIn("related_links", form.formsets)
147
+
148
+ def test_get_form_for_model_without_explicit_formsets(self):
149
+ # omitting the 'formsets' argument from get_form_for_model should return a form with no
150
+ # formsets, rather than a form with ALL OF THE FORMSETS which somehow seemed like a good
151
+ # idea once
152
+ EventPageForm = get_form_for_model(
153
+ EventPage,
154
+ form_class=WagtailAdminPageForm,
155
+ fields=["date_from"],
156
+ )
157
+ form = EventPageForm()
158
+
159
+ self.assertNotIn("speakers", form.formsets)
160
+ self.assertNotIn("related_links", form.formsets)
161
+
162
+ def test_get_form_for_model_with_excluded_fields(self):
163
+ EventPageForm = get_form_for_model(
164
+ EventPage,
165
+ form_class=WagtailAdminPageForm,
166
+ exclude=["title"],
167
+ exclude_formsets=["related_links"],
168
+ )
169
+ form = EventPageForm()
170
+
171
+ # form should contain date_from but not title
172
+ self.assertEqual(type(form.fields["date_from"]), forms.DateField)
173
+ self.assertEqual(type(form.fields["date_from"].widget), AdminDateInput)
174
+ self.assertNotIn("title", form.fields)
175
+
176
+ # formsets should include speakers but not related_links
177
+ self.assertIn("speakers", form.formsets)
178
+ self.assertNotIn("related_links", form.formsets)
179
+
180
+ def test_get_form_for_model_with_widget_overides_by_class(self):
181
+ EventPageForm = get_form_for_model(
182
+ EventPage,
183
+ form_class=WagtailAdminPageForm,
184
+ fields=["date_to", "date_from"],
185
+ widgets={"date_from": forms.PasswordInput},
186
+ )
187
+ form = EventPageForm()
188
+
189
+ self.assertEqual(type(form.fields["date_from"]), forms.DateField)
190
+ self.assertEqual(type(form.fields["date_from"].widget), forms.PasswordInput)
191
+
192
+ def test_get_form_for_model_with_widget_overides_by_instance(self):
193
+ EventPageForm = get_form_for_model(
194
+ EventPage,
195
+ form_class=WagtailAdminPageForm,
196
+ fields=["date_to", "date_from"],
197
+ widgets={"date_from": forms.PasswordInput()},
198
+ )
199
+ form = EventPageForm()
200
+
201
+ self.assertEqual(type(form.fields["date_from"]), forms.DateField)
202
+ self.assertEqual(type(form.fields["date_from"].widget), forms.PasswordInput)
203
+
204
+ def test_tag_widget_is_passed_tag_model(self):
205
+ RestaurantPageForm = get_form_for_model(
206
+ RestaurantPage,
207
+ form_class=WagtailAdminPageForm,
208
+ fields=["title", "slug", "tags"],
209
+ )
210
+ form_html = RestaurantPageForm().as_p()
211
+ self.assertIn("/admin/tag\\u002Dautocomplete/tests/restauranttag/", form_html)
212
+
213
+ # widget should pick up the free_tagging=False attribute on the tag model
214
+ # and set itself to autocomplete only
215
+ self.assertIn('"autocompleteOnly": true', form_html)
216
+
217
+ # Free tagging should also be disabled at the form field validation level
218
+ RestaurantTag.objects.create(name="Italian", slug="italian")
219
+ RestaurantTag.objects.create(name="Indian", slug="indian")
220
+
221
+ form = RestaurantPageForm(
222
+ {
223
+ "title": "Buonasera",
224
+ "slug": "buonasera",
225
+ "tags": "Italian, delicious",
226
+ }
227
+ )
228
+ self.assertTrue(form.is_valid())
229
+ self.assertEqual(form.cleaned_data["tags"], ["Italian"])
230
+
231
+
232
+ def clear_edit_handler(page_cls):
233
+ def decorator(fn):
234
+ @wraps(fn)
235
+ def decorated(*args, **kwargs):
236
+ # Clear any old panel definitions generated
237
+ page_cls.get_edit_handler.cache_clear()
238
+ try:
239
+ fn(*args, **kwargs)
240
+ finally:
241
+ # Clear the bad panel definition generated just now
242
+ page_cls.get_edit_handler.cache_clear()
243
+
244
+ return decorated
245
+
246
+ return decorator
247
+
248
+
249
+ class TestPageEditHandlers(TestCase):
250
+ @clear_edit_handler(EventPage)
251
+ def test_get_edit_handler(self):
252
+ """
253
+ Forms for pages should have a base class of WagtailAdminPageForm.
254
+ """
255
+ edit_handler = EventPage.get_edit_handler()
256
+ EventPageForm = edit_handler.get_form_class()
257
+
258
+ # The generated form should inherit from WagtailAdminPageForm
259
+ self.assertTrue(issubclass(EventPageForm, WagtailAdminPageForm))
260
+
261
+ @clear_edit_handler(ValidatedPage)
262
+ def test_get_form_for_page_with_custom_base(self):
263
+ """
264
+ ValidatedPage sets a custom base_form_class. This should be used as the
265
+ base class when constructing a form for ValidatedPages
266
+ """
267
+ edit_handler = ValidatedPage.get_edit_handler()
268
+ GeneratedValidatedPageForm = edit_handler.get_form_class()
269
+
270
+ # The generated form should inherit from ValidatedPageForm, because
271
+ # ValidatedPage.base_form_class == ValidatedPageForm
272
+ self.assertTrue(issubclass(GeneratedValidatedPageForm, ValidatedPageForm))
273
+
274
+ @clear_edit_handler(ValidatedPage)
275
+ def test_check_invalid_base_form_class(self):
276
+ class BadFormClass:
277
+ pass
278
+
279
+ invalid_base_form = checks.Error(
280
+ "ValidatedPage.base_form_class does not extend WagtailAdminPageForm",
281
+ hint="Ensure that wagtail.admin.tests.test_edit_handlers.BadFormClass extends WagtailAdminPageForm",
282
+ obj=ValidatedPage,
283
+ id="wagtailadmin.E001",
284
+ )
285
+
286
+ invalid_edit_handler = checks.Error(
287
+ "ValidatedPage.get_edit_handler().get_form_class() does not extend WagtailAdminPageForm",
288
+ hint="Ensure that the panel definition for ValidatedPage creates a subclass of WagtailAdminPageForm",
289
+ obj=ValidatedPage,
290
+ id="wagtailadmin.E002",
291
+ )
292
+
293
+ with mock.patch.object(ValidatedPage, "base_form_class", new=BadFormClass):
294
+ errors = checks.run_checks()
295
+
296
+ # Only look at errors (e.g. ignore warnings about CSS not being built)
297
+ errors = [e for e in errors if e.level >= checks.ERROR]
298
+
299
+ # Errors may appear out of order, so sort them by id
300
+ errors.sort(key=lambda e: e.id)
301
+
302
+ self.assertEqual(errors, [invalid_base_form, invalid_edit_handler])
303
+
304
+ @clear_edit_handler(ValidatedPage)
305
+ def test_custom_edit_handler_form_class(self):
306
+ """
307
+ Set a custom edit handler on a Page class, but dont customise
308
+ ValidatedPage.base_form_class, or provide a custom form class for the
309
+ edit handler. Check the generated form class is of the correct type.
310
+ """
311
+ ValidatedPage.edit_handler = TabbedInterface()
312
+ with mock.patch.object(
313
+ ValidatedPage, "edit_handler", new=TabbedInterface(), create=True
314
+ ):
315
+ form_class = ValidatedPage.get_edit_handler().get_form_class()
316
+ self.assertTrue(issubclass(form_class, WagtailAdminPageForm))
317
+ errors = ValidatedPage.check()
318
+ self.assertEqual(errors, [])
319
+
320
+ @clear_edit_handler(ValidatedPage)
321
+ def test_repr(self):
322
+ edit_handler = ValidatedPage.get_edit_handler()
323
+
324
+ handler_repr = repr(edit_handler)
325
+
326
+ self.assertIn(
327
+ "model=<class 'wagtail.test.testapp.models.ValidatedPage'>",
328
+ handler_repr,
329
+ )
330
+
331
+ bound_handler = edit_handler.get_bound_panel(
332
+ instance=None, request=None, form=None
333
+ )
334
+ bound_handler_repr = repr(bound_handler)
335
+ self.assertIn(
336
+ "model=<class 'wagtail.test.testapp.models.ValidatedPage'>",
337
+ bound_handler_repr,
338
+ )
339
+
340
+ self.assertIn("instance=None", bound_handler_repr)
341
+ self.assertIn("request=None", bound_handler_repr)
342
+ self.assertIn("form=None", bound_handler_repr)
343
+
344
+
345
+ class TestExtractPanelDefinitionsFromModelClass(TestCase):
346
+ def test_can_extract_panel_property(self):
347
+ # A class with a 'panels' property defined should return that list
348
+ result = extract_panel_definitions_from_model_class(EventPageSpeaker)
349
+ self.assertEqual(len(result), 5)
350
+ self.assertTrue(any([isinstance(panel, MultiFieldPanel) for panel in result]))
351
+
352
+ def test_exclude(self):
353
+ panels = extract_panel_definitions_from_model_class(Site, exclude=["hostname"])
354
+ for panel in panels:
355
+ self.assertNotEqual(panel.field_name, "hostname")
356
+
357
+ def test_can_build_panel_list(self):
358
+ # EventPage has no 'panels' definition, so one should be derived from the field list
359
+ panels = extract_panel_definitions_from_model_class(EventPage)
360
+
361
+ self.assertTrue(
362
+ any(
363
+ [
364
+ isinstance(panel, FieldPanel) and panel.field_name == "date_from"
365
+ for panel in panels
366
+ ]
367
+ )
368
+ )
369
+
370
+
371
+ class TestTabbedInterface(TestCase, WagtailTestUtils):
372
+ def setUp(self):
373
+ self.request = RequestFactory().get("/")
374
+ user = self.create_superuser(username="admin")
375
+ self.request.user = user
376
+ self.user = self.login()
377
+ self.other_user = self.create_user(username="admin2", email="test2@email.com")
378
+ p = Permission.objects.get(codename="custom_see_panel_setting")
379
+ self.other_user.user_permissions.add(p)
380
+ # a custom tabbed interface for EventPage
381
+ self.event_page_tabbed_interface = TabbedInterface(
382
+ [
383
+ ObjectList(
384
+ [
385
+ FieldPanel("title", widget=forms.Textarea),
386
+ FieldPanel("date_from"),
387
+ FieldPanel("date_to"),
388
+ ],
389
+ heading="Event details",
390
+ classname="shiny",
391
+ ),
392
+ ObjectList(
393
+ [
394
+ InlinePanel("speakers", label="Speakers"),
395
+ ],
396
+ heading="Speakers",
397
+ ),
398
+ ObjectList(
399
+ [
400
+ FieldPanel("cost", permission="superuser"),
401
+ ],
402
+ heading="Secret",
403
+ ),
404
+ ObjectList(
405
+ [
406
+ FieldPanel("cost"),
407
+ ],
408
+ permission="tests.custom_see_panel_setting",
409
+ heading="Custom Setting",
410
+ ),
411
+ ObjectList(
412
+ [
413
+ FieldPanel("cost"),
414
+ ],
415
+ permission="tests.other_custom_see_panel_setting",
416
+ heading="Other Custom Setting",
417
+ ),
418
+ ]
419
+ ).bind_to_model(EventPage)
420
+
421
+ def test_get_form_class(self):
422
+ EventPageForm = self.event_page_tabbed_interface.get_form_class()
423
+ form = EventPageForm()
424
+
425
+ # form must include the 'speakers' formset required by the speakers InlinePanel
426
+ self.assertIn("speakers", form.formsets)
427
+
428
+ # form must respect any overridden widgets
429
+ self.assertEqual(type(form.fields["title"].widget), forms.Textarea)
430
+
431
+ def test_render(self):
432
+ EventPageForm = self.event_page_tabbed_interface.get_form_class()
433
+ event = EventPage(title="Abergavenny sheepdog trials")
434
+ form = EventPageForm(instance=event)
435
+
436
+ tabbed_interface = self.event_page_tabbed_interface.get_bound_panel(
437
+ instance=event,
438
+ form=form,
439
+ request=self.request,
440
+ )
441
+
442
+ result = tabbed_interface.render_html()
443
+
444
+ # result should contain tab buttons
445
+ self.assertIn(
446
+ '<a id="tab-label-event_details" href="#tab-event_details" class="w-tabs__tab shiny" role="tab" aria-selected="false" tabindex="-1">',
447
+ result,
448
+ )
449
+ self.assertIn(
450
+ '<a id="tab-label-speakers" href="#tab-speakers" class="w-tabs__tab " role="tab" aria-selected="false" tabindex="-1">',
451
+ result,
452
+ )
453
+
454
+ # result should contain tab panels
455
+ self.assertIn('aria-labelledby="tab-label-event_details"', result)
456
+ self.assertIn('aria-labelledby="tab-label-speakers"', result)
457
+
458
+ # result should contain rendered content from descendants
459
+ self.assertIn("Abergavenny sheepdog trials</textarea>", result)
460
+
461
+ # this result should not include fields that are not covered by the panel definition
462
+ self.assertNotIn("signup_link", result)
463
+
464
+ def test_required_fields(self):
465
+ # get_form_options should report the set of form fields to be rendered recursively by children of TabbedInterface
466
+ result = set(self.event_page_tabbed_interface.get_form_options()["fields"])
467
+ self.assertEqual(result, {"title", "date_from", "date_to", "cost"})
468
+
469
+ def test_render_form_content(self):
470
+ EventPageForm = self.event_page_tabbed_interface.get_form_class()
471
+ event = EventPage(title="Abergavenny sheepdog trials")
472
+ form = EventPageForm(instance=event)
473
+
474
+ tabbed_interface = self.event_page_tabbed_interface.get_bound_panel(
475
+ instance=event,
476
+ form=form,
477
+ request=self.request,
478
+ )
479
+
480
+ result = tabbed_interface.render_form_content()
481
+ # rendered output should contain field content as above
482
+ self.assertIn("Abergavenny sheepdog trials</textarea>", result)
483
+ # rendered output should NOT include fields that are in the model but not represented
484
+ # in the panel definition
485
+ self.assertNotIn("signup_link", result)
486
+
487
+ def test_tabs_permissions(self):
488
+ """
489
+ test that three tabs show when the current user has permission to see all three
490
+ test that two tabs show when the current user does not have permission to see all three
491
+ """
492
+
493
+ EventPageForm = self.event_page_tabbed_interface.get_form_class()
494
+ event = EventPage(title="Abergavenny sheepdog trials")
495
+ form = EventPageForm(instance=event)
496
+
497
+ with self.subTest("Super user test"):
498
+ # when signed in as a superuser all tabs should be visible
499
+ tabbed_interface = self.event_page_tabbed_interface.get_bound_panel(
500
+ instance=event,
501
+ form=form,
502
+ request=self.request,
503
+ )
504
+ result = tabbed_interface.render_html()
505
+ self.assertIn(
506
+ '<a id="tab-label-event_details" href="#tab-event_details" class="w-tabs__tab shiny" role="tab" aria-selected="false" tabindex="-1">',
507
+ result,
508
+ )
509
+ self.assertIn(
510
+ '<a id="tab-label-speakers" href="#tab-speakers" class="w-tabs__tab " role="tab" aria-selected="false" tabindex="-1">',
511
+ result,
512
+ )
513
+ self.assertIn(
514
+ '<a id="tab-label-secret" href="#tab-secret" ',
515
+ result,
516
+ )
517
+ self.assertIn(
518
+ '<a id="tab-label-custom_setting" href="#tab-custom_setting" ',
519
+ result,
520
+ )
521
+ self.assertIn(
522
+ '<a id="tab-label-other_custom_setting" href="#tab-other_custom_setting" ',
523
+ result,
524
+ )
525
+
526
+ with self.subTest("Not superuser permissions"):
527
+ """
528
+ The super user panel should not show, nor should the panel they dont have
529
+ permission for.
530
+ """
531
+ self.request.user = self.other_user
532
+
533
+ tabbed_interface = self.event_page_tabbed_interface.get_bound_panel(
534
+ instance=event,
535
+ form=form,
536
+ request=self.request,
537
+ )
538
+ result = tabbed_interface.render_html()
539
+ self.assertIn(
540
+ '<a id="tab-label-event_details" href="#tab-event_details" class="w-tabs__tab shiny" role="tab" aria-selected="false" tabindex="-1">',
541
+ result,
542
+ )
543
+ self.assertIn(
544
+ '<a id="tab-label-speakers" href="#tab-speakers" class="w-tabs__tab " role="tab" aria-selected="false" tabindex="-1">',
545
+ result,
546
+ )
547
+ self.assertNotIn(
548
+ '<a id="tab-label-secret" href="#tab-secret" ',
549
+ result,
550
+ )
551
+ self.assertIn(
552
+ '<a id="tab-label-custom_setting" href="#tab-custom_setting" ',
553
+ result,
554
+ )
555
+ self.assertNotIn(
556
+ '<a id="tab-label-other_custom_setting" href="#tab-other-custom_setting" ',
557
+ result,
558
+ )
559
+
560
+ with self.subTest("Non superuser"):
561
+ # Login as non superuser to check that the third tab does not show
562
+ user = (
563
+ AnonymousUser()
564
+ ) # technically, Anonymous users cannot access the admin
565
+ self.request.user = user
566
+ tabbed_interface = self.event_page_tabbed_interface.get_bound_panel(
567
+ instance=event,
568
+ form=form,
569
+ request=self.request,
570
+ )
571
+ result = tabbed_interface.render_html()
572
+ self.assertIn(
573
+ '<a id="tab-label-event_details" href="#tab-event_details" class="w-tabs__tab shiny" role="tab" aria-selected="false" tabindex="-1">',
574
+ result,
575
+ )
576
+ self.assertIn(
577
+ '<a id="tab-label-speakers" href="#tab-speakers" class="w-tabs__tab " role="tab" aria-selected="false" tabindex="-1">',
578
+ result,
579
+ )
580
+ self.assertNotIn(
581
+ '<a id="tab-label-secret" href="#tab-secret" ',
582
+ result,
583
+ )
584
+ self.assertNotIn(
585
+ '<a id="tab-label-custom_setting" href="#tab-custom_setting" ',
586
+ result,
587
+ )
588
+ self.assertNotIn(
589
+ '<a id="tab-label-other_custom_setting" href="#tab-other-custom_setting" ',
590
+ result,
591
+ )
592
+
593
+
594
+ class TestObjectList(TestCase):
595
+ def setUp(self):
596
+ self.request = RequestFactory().get("/")
597
+ user = AnonymousUser() # technically, Anonymous users cannot access the admin
598
+ self.request.user = user
599
+ # a custom ObjectList for EventPage
600
+ self.event_page_object_list = ObjectList(
601
+ [
602
+ FieldPanel("title", widget=forms.Textarea),
603
+ FieldPanel("date_from"),
604
+ FieldPanel("date_to"),
605
+ InlinePanel("speakers", label="Speakers"),
606
+ ],
607
+ heading="Event details",
608
+ classname="shiny",
609
+ ).bind_to_model(EventPage)
610
+
611
+ def test_get_form_class(self):
612
+ EventPageForm = self.event_page_object_list.get_form_class()
613
+ form = EventPageForm()
614
+
615
+ # form must include the 'speakers' formset required by the speakers InlinePanel
616
+ self.assertIn("speakers", form.formsets)
617
+
618
+ # form must respect any overridden widgets
619
+ self.assertEqual(type(form.fields["title"].widget), forms.Textarea)
620
+
621
+ def test_render(self):
622
+ EventPageForm = self.event_page_object_list.get_form_class()
623
+ event = EventPage(title="Abergavenny sheepdog trials")
624
+ form = EventPageForm(instance=event)
625
+
626
+ object_list = self.event_page_object_list.get_bound_panel(
627
+ instance=event,
628
+ form=form,
629
+ request=self.request,
630
+ )
631
+
632
+ result = object_list.render_html()
633
+
634
+ # result should contain ObjectList furniture
635
+ self.assertIn('<div class="w-panel__header">', result)
636
+
637
+ # result should contain labels for children
638
+ self.assertIn(
639
+ '<label for="id_date_from" id="id_date_from-label">',
640
+ result,
641
+ )
642
+
643
+ # result should include help text for children
644
+ self.assertInHTML(
645
+ '<div class="help">Not required if event is on a single day</div>',
646
+ result,
647
+ )
648
+
649
+ # result should contain rendered content from descendants
650
+ self.assertIn("Abergavenny sheepdog trials</textarea>", result)
651
+
652
+ # this result should not include fields that are not covered by the panel definition
653
+ self.assertNotIn("signup_link", result)
654
+
655
+
656
+ class TestFieldPanel(TestCase):
657
+ def setUp(self):
658
+ self.request = RequestFactory().get("/")
659
+ user = AnonymousUser() # technically, Anonymous users cannot access the admin
660
+ self.request.user = user
661
+
662
+ self.EventPageForm = get_form_for_model(
663
+ EventPage,
664
+ form_class=WagtailAdminPageForm,
665
+ fields=["title", "slug", "date_from", "date_to"],
666
+ formsets=[],
667
+ )
668
+ self.event = EventPage(
669
+ title="Abergavenny sheepdog trials",
670
+ date_from=date(2014, 7, 20),
671
+ date_to=date(2014, 7, 21),
672
+ )
673
+
674
+ self.end_date_panel = FieldPanel(
675
+ "date_to", classname="full-width"
676
+ ).bind_to_model(EventPage)
677
+
678
+ def test_non_model_field(self):
679
+ # defining a FieldPanel for a field which isn't part of a model is OK,
680
+ # because it might be defined on the form instead
681
+ field_panel = FieldPanel("barbecue").bind_to_model(Page)
682
+
683
+ # however, accessing db_field will fail
684
+ with self.assertRaises(FieldDoesNotExist):
685
+ field_panel.db_field
686
+
687
+ def test_override_heading(self):
688
+ # unless heading is specified in keyword arguments, an edit handler with bound form should take its
689
+ # heading from the bound field label
690
+ bound_panel = self.end_date_panel.get_bound_panel(
691
+ form=self.EventPageForm(), request=self.request, instance=self.event
692
+ )
693
+ self.assertEqual(bound_panel.heading, bound_panel.bound_field.label)
694
+
695
+ # if heading is explicitly provided to constructor, that heading should be taken in
696
+ # preference to the field's label
697
+ end_date_panel_with_overridden_heading = FieldPanel(
698
+ "date_to", classname="full-width", heading="New heading"
699
+ ).bind_to_model(EventPage)
700
+ end_date_panel_with_overridden_heading = (
701
+ end_date_panel_with_overridden_heading.get_bound_panel(
702
+ request=self.request, form=self.EventPageForm(), instance=self.event
703
+ )
704
+ )
705
+ self.assertEqual(end_date_panel_with_overridden_heading.heading, "New heading")
706
+ self.assertEqual(
707
+ end_date_panel_with_overridden_heading.bound_field.label, "New heading"
708
+ )
709
+
710
+ def test_render_html(self):
711
+ form = self.EventPageForm(
712
+ {
713
+ "title": "Pontypridd sheepdog trials",
714
+ "date_from": "2014-07-20",
715
+ "date_to": "2014-07-22",
716
+ },
717
+ instance=self.event,
718
+ )
719
+
720
+ form.is_valid()
721
+
722
+ field_panel = self.end_date_panel.get_bound_panel(
723
+ instance=self.event,
724
+ form=form,
725
+ request=self.request,
726
+ )
727
+ result = field_panel.render_html()
728
+
729
+ self.assertIn("Not required if event is on a single day", result)
730
+
731
+ # check that the populated form field is included
732
+ self.assertIn('value="2014-07-22"', result)
733
+
734
+ # there should be no errors on this field
735
+ self.assertNotIn("error-message", result)
736
+
737
+ def test_required_fields(self):
738
+ result = self.end_date_panel.get_form_options()["fields"]
739
+ self.assertEqual(result, ["date_to"])
740
+
741
+ def test_error_message_is_rendered(self):
742
+ form = self.EventPageForm(
743
+ {
744
+ "title": "Pontypridd sheepdog trials",
745
+ "date_from": "2014-07-20",
746
+ "date_to": "2014-07-33",
747
+ },
748
+ instance=self.event,
749
+ )
750
+
751
+ form.is_valid()
752
+
753
+ field_panel = self.end_date_panel.get_bound_panel(
754
+ instance=self.event,
755
+ form=form,
756
+ request=self.request,
757
+ )
758
+ result = field_panel.render_html()
759
+
760
+ self.assertIn("Enter a valid date.", result)
761
+
762
+ def test_repr(self):
763
+ form = self.EventPageForm()
764
+ field_panel = self.end_date_panel.get_bound_panel(
765
+ form=form,
766
+ instance=self.event,
767
+ request=self.request,
768
+ )
769
+
770
+ field_panel_repr = repr(field_panel)
771
+
772
+ self.assertIn(
773
+ "model=<class 'wagtail.test.testapp.models.EventPage'>", field_panel_repr
774
+ )
775
+ self.assertIn("instance=Abergavenny sheepdog trials", field_panel_repr)
776
+ self.assertIn("request=<WSGIRequest: GET '/'>", field_panel_repr)
777
+ self.assertIn("form=EventPageForm", field_panel_repr)
778
+
779
+
780
+ class TestFieldRowPanel(TestCase):
781
+ def setUp(self):
782
+ self.request = RequestFactory().get("/")
783
+ user = AnonymousUser() # technically, Anonymous users cannot access the admin
784
+ self.request.user = user
785
+
786
+ self.EventPageForm = get_form_for_model(
787
+ EventPage,
788
+ form_class=WagtailAdminPageForm,
789
+ fields=["title", "slug", "date_from", "date_to"],
790
+ formsets=[],
791
+ )
792
+ self.event = EventPage(
793
+ title="Abergavenny sheepdog trials",
794
+ date_from=date(2014, 7, 20),
795
+ date_to=date(2014, 7, 21),
796
+ )
797
+
798
+ self.dates_panel = FieldRowPanel(
799
+ [
800
+ FieldPanel("date_from", classname="col4", heading="Start"),
801
+ FieldPanel("date_to", classname="coltwo"),
802
+ ],
803
+ help_text="Confirmed event dates only",
804
+ ).bind_to_model(EventPage)
805
+
806
+ def test_render_html(self):
807
+ form = self.EventPageForm(
808
+ {
809
+ "title": "Pontypridd sheepdog trials",
810
+ "date_from": "2014-07-20",
811
+ "date_to": "2014-07-22",
812
+ },
813
+ instance=self.event,
814
+ )
815
+
816
+ form.is_valid()
817
+
818
+ field_panel = self.dates_panel.get_bound_panel(
819
+ instance=self.event,
820
+ form=form,
821
+ request=self.request,
822
+ )
823
+ result = field_panel.render_html()
824
+
825
+ # check that label is output in the 'field' style
826
+ self.assertIn(
827
+ '<label class="w-field__label" for="id_date_to" id="id_date_to-label">',
828
+ result,
829
+ )
830
+
831
+ # check that field help text is included
832
+ self.assertIn("Not required if event is on a single day", result)
833
+
834
+ # check that row help text is included
835
+ self.assertIn("Confirmed event dates only", result)
836
+
837
+ # check that the populated form field is included
838
+ self.assertIn('value="2014-07-22"', result)
839
+
840
+ # there should be no errors on this field
841
+ self.assertNotIn("error-message", result)
842
+
843
+ def test_error_message_is_rendered(self):
844
+ form = self.EventPageForm(
845
+ {
846
+ "title": "Pontypridd sheepdog trials",
847
+ "date_from": "2014-07-20",
848
+ "date_to": "2014-07-33",
849
+ },
850
+ instance=self.event,
851
+ )
852
+
853
+ form.is_valid()
854
+
855
+ field_panel = self.dates_panel.get_bound_panel(
856
+ instance=self.event,
857
+ form=form,
858
+ request=self.request,
859
+ )
860
+ result = field_panel.render_html()
861
+
862
+ self.assertIn("Enter a valid date.", result)
863
+
864
+
865
+ class TestFieldRowPanelWithChooser(TestCase):
866
+ def setUp(self):
867
+ self.request = RequestFactory().get("/")
868
+ user = AnonymousUser() # technically, Anonymous users cannot access the admin
869
+ self.request.user = user
870
+
871
+ self.EventPageForm = get_form_for_model(
872
+ EventPage,
873
+ form_class=WagtailAdminPageForm,
874
+ fields=["title", "slug", "date_from", "date_to"],
875
+ formsets=[],
876
+ )
877
+ self.event = EventPage(
878
+ title="Abergavenny sheepdog trials",
879
+ date_from=date(2014, 7, 19),
880
+ date_to=date(2014, 7, 21),
881
+ )
882
+
883
+ self.dates_panel = FieldRowPanel(
884
+ [
885
+ FieldPanel("date_from"),
886
+ FieldPanel("feed_image"),
887
+ ]
888
+ ).bind_to_model(EventPage)
889
+
890
+ def test_render_html(self):
891
+ form = self.EventPageForm(
892
+ {
893
+ "title": "Pontypridd sheepdog trials",
894
+ "date_from": "2014-07-20",
895
+ "date_to": "2014-07-22",
896
+ },
897
+ instance=self.event,
898
+ )
899
+
900
+ form.is_valid()
901
+
902
+ field_panel = self.dates_panel.get_bound_panel(
903
+ instance=self.event,
904
+ form=form,
905
+ request=self.request,
906
+ )
907
+ result = field_panel.render_html()
908
+
909
+ # check that the populated form field is included
910
+ self.assertIn('value="2014-07-20"', result)
911
+
912
+ # there should be no errors on this field
913
+ self.assertNotIn("error-message", result)
914
+
915
+
916
+ class TestPageChooserPanel(TestCase):
917
+ fixtures = ["test.json"]
918
+
919
+ def setUp(self):
920
+ self.request = RequestFactory().get("/")
921
+ user = AnonymousUser() # technically, Anonymous users cannot access the admin
922
+ self.request.user = user
923
+
924
+ model = PageChooserModel # a model with a foreign key to Page which we want to render as a page chooser
925
+
926
+ # a PageChooserPanel class that works on PageChooserModel's 'page' field
927
+ self.edit_handler = ObjectList([PageChooserPanel("page")]).bind_to_model(
928
+ PageChooserModel
929
+ )
930
+ self.my_page_chooser_panel = self.edit_handler.children[0]
931
+
932
+ # build a form class containing the fields that MyPageChooserPanel wants
933
+ self.PageChooserForm = self.edit_handler.get_form_class()
934
+
935
+ # a test instance of PageChooserModel, pointing to the 'christmas' page
936
+ self.christmas_page = Page.objects.get(slug="christmas")
937
+ self.events_index_page = Page.objects.get(slug="events")
938
+ self.test_instance = model.objects.create(page=self.christmas_page)
939
+
940
+ self.form = self.PageChooserForm(instance=self.test_instance)
941
+ self.page_chooser_panel = self.my_page_chooser_panel.get_bound_panel(
942
+ instance=self.test_instance, form=self.form, request=self.request
943
+ )
944
+
945
+ def test_page_chooser_uses_correct_widget(self):
946
+ self.assertEqual(type(self.form.fields["page"].widget), AdminPageChooser)
947
+
948
+ def test_render_js_init(self):
949
+ result = self.page_chooser_panel.render_html()
950
+ expected_js = 'new PageChooser("{id}", {parent}, {{"model_names": ["{model}"], "can_choose_root": false, "user_perms": null}});'.format(
951
+ id="id_page", model="wagtailcore.page", parent=self.events_index_page.id
952
+ )
953
+
954
+ self.assertIn(expected_js, result)
955
+
956
+ def test_render_js_init_with_can_choose_root_true(self):
957
+ # construct an alternative page chooser panel object, with can_choose_root=True
958
+
959
+ my_page_object_list = ObjectList(
960
+ [PageChooserPanel("page", can_choose_root=True)]
961
+ ).bind_to_model(PageChooserModel)
962
+ my_page_chooser_panel = my_page_object_list.children[0]
963
+ PageChooserForm = my_page_object_list.get_form_class()
964
+
965
+ form = PageChooserForm(instance=self.test_instance)
966
+ page_chooser_panel = my_page_chooser_panel.get_bound_panel(
967
+ instance=self.test_instance, form=form, request=self.request
968
+ )
969
+ result = page_chooser_panel.render_html()
970
+
971
+ # the canChooseRoot flag on PageChooser should now be true
972
+ expected_js = 'new PageChooser("{id}", {parent}, {{"model_names": ["{model}"], "can_choose_root": true, "user_perms": null}});'.format(
973
+ id="id_page", model="wagtailcore.page", parent=self.events_index_page.id
974
+ )
975
+ self.assertIn(expected_js, result)
976
+
977
+ def test_render_html(self):
978
+ result = self.page_chooser_panel.render_html()
979
+ self.assertIn('<div class="help">help text</div>', result)
980
+ self.assertIn(
981
+ '<div class="chooser__title" data-chooser-title id="id_page-title">Christmas</div>',
982
+ result,
983
+ )
984
+ self.assertIn(
985
+ '<a href="/admin/pages/%d/edit/" aria-describedby="id_page-title" class="edit-link button button-small button-secondary" target="_blank" rel="noreferrer">Edit this page</a>'
986
+ % self.christmas_page.id,
987
+ result,
988
+ )
989
+
990
+ def test_render_as_empty_field(self):
991
+ test_instance = PageChooserModel()
992
+ form = self.PageChooserForm(instance=test_instance)
993
+ page_chooser_panel = self.my_page_chooser_panel.get_bound_panel(
994
+ instance=test_instance, form=form, request=self.request
995
+ )
996
+ result = page_chooser_panel.render_html()
997
+
998
+ self.assertIn('<div class="help">help text</div>', result)
999
+ self.assertIn(
1000
+ '<div class="chooser__title" data-chooser-title id="id_page-title"></div>',
1001
+ result,
1002
+ )
1003
+ self.assertIn("Choose a page", result)
1004
+
1005
+ def test_render_error(self):
1006
+ form = self.PageChooserForm({"page": ""}, instance=self.test_instance)
1007
+ self.assertFalse(form.is_valid())
1008
+
1009
+ page_chooser_panel = self.my_page_chooser_panel.get_bound_panel(
1010
+ instance=self.test_instance, form=form, request=self.request
1011
+ )
1012
+ self.assertIn("error-message", page_chooser_panel.render_html())
1013
+
1014
+ def test_override_page_type(self):
1015
+ # Model has a foreign key to Page, but we specify EventPage in the PageChooserPanel
1016
+ # to restrict the chooser to that page type
1017
+ my_page_object_list = ObjectList(
1018
+ [PageChooserPanel("page", "tests.EventPage")]
1019
+ ).bind_to_model(EventPageChooserModel)
1020
+ my_page_chooser_panel = my_page_object_list.children[0]
1021
+ PageChooserForm = my_page_object_list.get_form_class()
1022
+ form = PageChooserForm(instance=self.test_instance)
1023
+ page_chooser_panel = my_page_chooser_panel.get_bound_panel(
1024
+ instance=self.test_instance, form=form, request=self.request
1025
+ )
1026
+
1027
+ result = page_chooser_panel.render_html()
1028
+ expected_js = 'new PageChooser("{id}", {parent}, {{"model_names": ["{model}"], "can_choose_root": false, "user_perms": null}});'.format(
1029
+ id="id_page", model="tests.eventpage", parent=self.events_index_page.id
1030
+ )
1031
+
1032
+ self.assertIn(expected_js, result)
1033
+
1034
+ def test_autodetect_page_type(self):
1035
+ # Model has a foreign key to EventPage, which we want to autodetect
1036
+ # instead of specifying the page type in PageChooserPanel
1037
+ my_page_object_list = ObjectList([PageChooserPanel("page")]).bind_to_model(
1038
+ EventPageChooserModel,
1039
+ )
1040
+ my_page_chooser_panel = my_page_object_list.children[0]
1041
+ PageChooserForm = my_page_object_list.get_form_class()
1042
+ form = PageChooserForm(instance=self.test_instance)
1043
+ page_chooser_panel = my_page_chooser_panel.get_bound_panel(
1044
+ instance=self.test_instance, form=form, request=self.request
1045
+ )
1046
+
1047
+ result = page_chooser_panel.render_html()
1048
+ expected_js = 'new PageChooser("{id}", {parent}, {{"model_names": ["{model}"], "can_choose_root": false, "user_perms": null}});'.format(
1049
+ id="id_page", model="tests.eventpage", parent=self.events_index_page.id
1050
+ )
1051
+
1052
+ self.assertIn(expected_js, result)
1053
+
1054
+ def test_target_models(self):
1055
+ panel = PageChooserPanel("page", "wagtailcore.site").bind_to_model(
1056
+ PageChooserModel
1057
+ )
1058
+ widget = panel.get_form_options()["widgets"]["page"]
1059
+ self.assertEqual(widget.target_models, [Site])
1060
+
1061
+ def test_target_models_malformed_type(self):
1062
+ panel = PageChooserPanel("page", "snowman").bind_to_model(PageChooserModel)
1063
+ self.assertRaises(ImproperlyConfigured, panel.get_form_options)
1064
+
1065
+ def test_target_models_nonexistent_type(self):
1066
+ panel = PageChooserPanel("page", "snowman.lorry").bind_to_model(
1067
+ PageChooserModel
1068
+ )
1069
+ self.assertRaises(ImproperlyConfigured, panel.get_form_options)
1070
+
1071
+
1072
+ class TestInlinePanel(TestCase, WagtailTestUtils):
1073
+ fixtures = ["test.json"]
1074
+
1075
+ def setUp(self):
1076
+ self.request = RequestFactory().get("/")
1077
+ user = AnonymousUser() # technically, Anonymous users cannot access the admin
1078
+ self.request.user = user
1079
+
1080
+ def test_render(self):
1081
+ """
1082
+ Check that the inline panel renders the panels set on the model
1083
+ when no 'panels' parameter is passed in the InlinePanel definition
1084
+ """
1085
+ speaker_object_list = ObjectList(
1086
+ [
1087
+ InlinePanel(
1088
+ "speakers", label="Speakers", classname="classname-for-speakers"
1089
+ )
1090
+ ]
1091
+ ).bind_to_model(EventPage)
1092
+ EventPageForm = speaker_object_list.get_form_class()
1093
+
1094
+ # SpeakerInlinePanel should instruct the form class to include a 'speakers' formset
1095
+ self.assertEqual(["speakers"], list(EventPageForm.formsets.keys()))
1096
+
1097
+ event_page = EventPage.objects.get(slug="christmas")
1098
+
1099
+ form = EventPageForm(instance=event_page)
1100
+ panel = speaker_object_list.get_bound_panel(
1101
+ instance=event_page, form=form, request=self.request
1102
+ )
1103
+
1104
+ result = panel.render_html()
1105
+
1106
+ # FIXME: reinstate when we pass classnames to the template again
1107
+ # self.assertIn('<li class="object classname-for-speakers">', result)
1108
+ self.assertIn(
1109
+ '<label class="w-field__label" for="id_speakers-0-first_name" id="id_speakers-0-first_name-label">',
1110
+ result,
1111
+ )
1112
+ self.assertIn('value="Father"', result)
1113
+ self.assertIn(
1114
+ '<label class="w-field__label" for="id_speakers-0-last_name" id="id_speakers-0-last_name-label">',
1115
+ result,
1116
+ )
1117
+ self.assertIn(
1118
+ '<label class="w-field__label" for="id_speakers-0-image" id="id_speakers-0-image-label">',
1119
+ result,
1120
+ )
1121
+ self.assertIn("Choose an image", result)
1122
+
1123
+ # rendered panel must also contain hidden fields for id, DELETE and ORDER
1124
+ self.assertTagInHTML(
1125
+ '<input id="id_speakers-0-id" name="speakers-0-id" type="hidden">',
1126
+ result,
1127
+ allow_extra_attrs=True,
1128
+ )
1129
+ self.assertTagInHTML(
1130
+ '<input id="id_speakers-0-DELETE" name="speakers-0-DELETE" type="hidden">',
1131
+ result,
1132
+ allow_extra_attrs=True,
1133
+ )
1134
+ self.assertTagInHTML(
1135
+ '<input id="id_speakers-0-ORDER" name="speakers-0-ORDER" type="hidden">',
1136
+ result,
1137
+ allow_extra_attrs=True,
1138
+ )
1139
+
1140
+ # rendered panel must contain maintenance form for the formset
1141
+ self.assertTagInHTML(
1142
+ '<input id="id_speakers-TOTAL_FORMS" name="speakers-TOTAL_FORMS" type="hidden">',
1143
+ result,
1144
+ allow_extra_attrs=True,
1145
+ )
1146
+
1147
+ # rendered panel must include the JS initializer
1148
+ self.assertIn("var panel = new InlinePanel({", result)
1149
+
1150
+ def test_render_with_panel_overrides(self):
1151
+ """
1152
+ Check that inline panel renders the panels listed in the InlinePanel definition
1153
+ where one is specified
1154
+ """
1155
+ speaker_object_list = ObjectList(
1156
+ [
1157
+ InlinePanel(
1158
+ "speakers",
1159
+ label="Speakers",
1160
+ panels=[
1161
+ FieldPanel("first_name", widget=forms.Textarea),
1162
+ FieldPanel("image"),
1163
+ ],
1164
+ ),
1165
+ ]
1166
+ ).bind_to_model(EventPage)
1167
+ speaker_inline_panel = speaker_object_list.children[0]
1168
+ EventPageForm = speaker_object_list.get_form_class()
1169
+
1170
+ # speaker_inline_panel should instruct the form class to include a 'speakers' formset
1171
+ self.assertEqual(["speakers"], list(EventPageForm.formsets.keys()))
1172
+
1173
+ event_page = EventPage.objects.get(slug="christmas")
1174
+
1175
+ form = EventPageForm(instance=event_page)
1176
+ panel = speaker_inline_panel.get_bound_panel(
1177
+ instance=event_page, form=form, request=self.request
1178
+ )
1179
+
1180
+ result = panel.render_html()
1181
+
1182
+ # rendered panel should contain first_name rendered as a text area, but no last_name field
1183
+ self.assertIn(
1184
+ '<label class="w-field__label" for="id_speakers-0-first_name" id="id_speakers-0-first_name-label">',
1185
+ result,
1186
+ )
1187
+ self.assertIn("Father</textarea>", result)
1188
+ self.assertNotIn(
1189
+ '<label class="w-field__label" for="id_speakers-0-last_name" id="id_speakers-0-last_name-label">',
1190
+ result,
1191
+ )
1192
+
1193
+ # test for #338: surname field should not be rendered as a 'stray' label-less field
1194
+ self.assertTagInHTML(
1195
+ '<input id="id_speakers-0-last_name">',
1196
+ result,
1197
+ count=0,
1198
+ allow_extra_attrs=True,
1199
+ )
1200
+
1201
+ self.assertIn(
1202
+ '<label class="w-field__label" for="id_speakers-0-image" id="id_speakers-0-image-label">',
1203
+ result,
1204
+ )
1205
+ self.assertIn("Choose an image", result)
1206
+
1207
+ # rendered panel must also contain hidden fields for id, DELETE and ORDER
1208
+ self.assertTagInHTML(
1209
+ '<input id="id_speakers-0-id" name="speakers-0-id" type="hidden">',
1210
+ result,
1211
+ allow_extra_attrs=True,
1212
+ )
1213
+ self.assertTagInHTML(
1214
+ '<input id="id_speakers-0-DELETE" name="speakers-0-DELETE" type="hidden">',
1215
+ result,
1216
+ allow_extra_attrs=True,
1217
+ )
1218
+ self.assertTagInHTML(
1219
+ '<input id="id_speakers-0-ORDER" name="speakers-0-ORDER" type="hidden">',
1220
+ result,
1221
+ allow_extra_attrs=True,
1222
+ )
1223
+
1224
+ # rendered panel must contain maintenance form for the formset
1225
+ self.assertTagInHTML(
1226
+ '<input id="id_speakers-TOTAL_FORMS" name="speakers-TOTAL_FORMS" type="hidden">',
1227
+ result,
1228
+ allow_extra_attrs=True,
1229
+ )
1230
+
1231
+ # render_js_init must provide the JS initializer
1232
+ self.assertIn("var panel = new InlinePanel({", panel.render_html())
1233
+
1234
+ @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True)
1235
+ def test_no_thousand_separators_in_js(self):
1236
+ """
1237
+ Test that the USE_THOUSAND_SEPARATOR setting does not screw up the rendering of numbers
1238
+ (specifically maxForms=1000) in the JS initializer:
1239
+ https://github.com/wagtail/wagtail/pull/2699
1240
+ https://github.com/wagtail/wagtail/issues/3227
1241
+ """
1242
+ speaker_object_list = ObjectList(
1243
+ [
1244
+ InlinePanel(
1245
+ "speakers",
1246
+ label="Speakers",
1247
+ panels=[
1248
+ FieldPanel("first_name", widget=forms.Textarea),
1249
+ FieldPanel("image"),
1250
+ ],
1251
+ ),
1252
+ ]
1253
+ ).bind_to_model(EventPage)
1254
+ speaker_inline_panel = speaker_object_list.children[0]
1255
+ EventPageForm = speaker_object_list.get_form_class()
1256
+ event_page = EventPage.objects.get(slug="christmas")
1257
+ form = EventPageForm(instance=event_page)
1258
+ panel = speaker_inline_panel.get_bound_panel(
1259
+ instance=event_page, form=form, request=self.request
1260
+ )
1261
+
1262
+ self.assertIn("maxForms: 1000", panel.render_html())
1263
+
1264
+ def test_invalid_inlinepanel_declaration(self):
1265
+ with self.ignore_deprecation_warnings():
1266
+ self.assertRaises(TypeError, lambda: InlinePanel(label="Speakers"))
1267
+ self.assertRaises(
1268
+ TypeError,
1269
+ lambda: InlinePanel(
1270
+ EventPage, "speakers", label="Speakers", bacon="chunky"
1271
+ ),
1272
+ )
1273
+
1274
+
1275
+ class TestInlinePanelGetComparison(TestCase):
1276
+ fixtures = ["test.json"]
1277
+
1278
+ def setUp(self):
1279
+ self.request = RequestFactory().get("/")
1280
+ user = AnonymousUser() # technically, Anonymous users cannot access the admin
1281
+ self.request.user = user
1282
+
1283
+ def test_get_comparison(self):
1284
+ # Test whether the InlinePanel passes it's label in get_comparison
1285
+
1286
+ page = Page.objects.get(id=4).specific
1287
+ comparison = (
1288
+ page.get_edit_handler()
1289
+ .bind_to(instance=page, request=self.request)
1290
+ .get_comparison()
1291
+ )
1292
+
1293
+ comparison = [comp(page, page) for comp in comparison]
1294
+ field_labels = [comp.field_label() for comp in comparison]
1295
+ self.assertIn("Speakers", field_labels)
1296
+
1297
+
1298
+ class TestInlinePanelRelatedModelPanelConfigChecks(TestCase):
1299
+ def setUp(self):
1300
+ self.original_panels = EventPageSpeaker.panels
1301
+ delattr(EventPageSpeaker, "panels")
1302
+
1303
+ def get_checks_result():
1304
+ # run checks only with the 'panels' tag
1305
+ checks_result = checks.run_checks(tags=["panels"])
1306
+ return [
1307
+ warning for warning in checks_result if warning.obj == EventPageSpeaker
1308
+ ]
1309
+
1310
+ self.warning_id = "wagtailadmin.W002"
1311
+ self.get_checks_result = get_checks_result
1312
+
1313
+ def tearDown(self):
1314
+ EventPageSpeaker.panels = self.original_panels
1315
+
1316
+ def test_page_with_inline_model_with_tabbed_panel_only(self):
1317
+ """Test that checks will warn against setting single tabbed panel on InlinePanel model"""
1318
+
1319
+ EventPageSpeaker.settings_panels = [
1320
+ FieldPanel("first_name"),
1321
+ FieldPanel("last_name"),
1322
+ ]
1323
+
1324
+ warning = checks.Warning(
1325
+ "EventPageSpeaker.settings_panels will have no effect on InlinePanel model editing",
1326
+ hint="""Ensure that EventPageSpeaker uses `panels` instead of `settings_panels`.
1327
+ There are no tabs on non-Page model editing within InlinePanels.""",
1328
+ obj=EventPageSpeaker,
1329
+ id=self.warning_id,
1330
+ )
1331
+
1332
+ checks_results = self.get_checks_result()
1333
+
1334
+ self.assertIn(warning, checks_results)
1335
+
1336
+ delattr(EventPageSpeaker, "settings_panels")
1337
+
1338
+ def test_page_with_inline_model_with_two_tabbed_panels(self):
1339
+ """Test that checks will warn against multiple tabbed panels on InlinePanel models"""
1340
+
1341
+ EventPageSpeaker.content_panels = [FieldPanel("first_name")]
1342
+ EventPageSpeaker.promote_panels = [FieldPanel("last_name")]
1343
+
1344
+ warning_1 = checks.Warning(
1345
+ "EventPageSpeaker.content_panels will have no effect on InlinePanel model editing",
1346
+ hint="""Ensure that EventPageSpeaker uses `panels` instead of `content_panels`.
1347
+ There are no tabs on non-Page model editing within InlinePanels.""",
1348
+ obj=EventPageSpeaker,
1349
+ id=self.warning_id,
1350
+ )
1351
+ warning_2 = checks.Warning(
1352
+ "EventPageSpeaker.promote_panels will have no effect on InlinePanel model editing",
1353
+ hint="""Ensure that EventPageSpeaker uses `panels` instead of `promote_panels`.
1354
+ There are no tabs on non-Page model editing within InlinePanels.""",
1355
+ obj=EventPageSpeaker,
1356
+ id=self.warning_id,
1357
+ )
1358
+
1359
+ checks_results = self.get_checks_result()
1360
+
1361
+ self.assertIn(warning_1, checks_results)
1362
+ self.assertIn(warning_2, checks_results)
1363
+
1364
+ delattr(EventPageSpeaker, "content_panels")
1365
+ delattr(EventPageSpeaker, "promote_panels")
1366
+
1367
+ def test_page_with_inline_model_with_edit_handler(self):
1368
+ """Checks should NOT warn if InlinePanel models use tabbed panels AND edit_handler"""
1369
+
1370
+ EventPageSpeaker.content_panels = [FieldPanel("first_name")]
1371
+ EventPageSpeaker.edit_handler = TabbedInterface(
1372
+ [ObjectList([FieldPanel("last_name")], heading="test")]
1373
+ )
1374
+
1375
+ # should not be any errors
1376
+ self.assertEqual(self.get_checks_result(), [])
1377
+
1378
+ # clean up for future checks
1379
+ delattr(EventPageSpeaker, "edit_handler")
1380
+ delattr(EventPageSpeaker, "content_panels")
1381
+
1382
+
1383
+ class TestCommentPanel(TestCase, WagtailTestUtils):
1384
+ fixtures = ["test.json"]
1385
+
1386
+ def setUp(self):
1387
+ self.commenting_user = get_user_model().objects.get(pk=7)
1388
+ self.other_user = get_user_model().objects.get(pk=6)
1389
+ self.request = RequestFactory().get("/")
1390
+ self.request.user = self.commenting_user
1391
+
1392
+ unbound_object_list = ObjectList([CommentPanel()])
1393
+ self.object_list = unbound_object_list.bind_to_model(EventPage)
1394
+ self.tabbed_interface = TabbedInterface([unbound_object_list]).bind_to_model(
1395
+ EventPage
1396
+ )
1397
+
1398
+ self.EventPageForm = self.object_list.get_form_class()
1399
+ self.event_page = EventPage.objects.get(slug="christmas")
1400
+ self.comment = Comment.objects.create(
1401
+ page=self.event_page,
1402
+ text="test",
1403
+ user=self.other_user,
1404
+ contentpath="test_contentpath",
1405
+ )
1406
+ self.reply_1 = CommentReply.objects.create(
1407
+ comment=self.comment, text="reply_1", user=self.other_user
1408
+ )
1409
+ self.reply_2 = CommentReply.objects.create(
1410
+ comment=self.comment, text="reply_2", user=self.commenting_user
1411
+ )
1412
+
1413
+ def test_comments_toggle_enabled(self):
1414
+ """
1415
+ Test that the comments toggle is enabled for a TabbedInterface containing CommentPanel, and disabled otherwise
1416
+ """
1417
+ form_class = self.tabbed_interface.get_form_class()
1418
+ form = form_class()
1419
+ self.assertTrue(form.show_comments_toggle)
1420
+
1421
+ tabbed_interface_without_content_panel = TabbedInterface(
1422
+ [ObjectList(self.event_page.content_panels)]
1423
+ ).bind_to_model(EventPage)
1424
+ form_class = tabbed_interface_without_content_panel.get_form_class()
1425
+ form = form_class()
1426
+ self.assertFalse(form.show_comments_toggle)
1427
+
1428
+ @override_settings(WAGTAILADMIN_COMMENTS_ENABLED=False)
1429
+ def test_comments_disabled_setting(self):
1430
+ """
1431
+ Test that the comment panel is missing if WAGTAILADMIN_COMMENTS_ENABLED=False
1432
+ """
1433
+ self.assertFalse(
1434
+ any(isinstance(panel, CommentPanel) for panel in Page.settings_panels)
1435
+ )
1436
+ form_class = Page.get_edit_handler().get_form_class()
1437
+ form = form_class()
1438
+ self.assertFalse(form.show_comments_toggle)
1439
+
1440
+ def test_comments_enabled_setting(self):
1441
+ """
1442
+ Test that the comment panel is present by default
1443
+ """
1444
+ self.assertTrue(
1445
+ any(isinstance(panel, CommentPanel) for panel in Page.settings_panels)
1446
+ )
1447
+ form_class = Page.get_edit_handler().get_form_class()
1448
+ form = form_class()
1449
+ self.assertTrue(form.show_comments_toggle)
1450
+
1451
+ def test_context(self):
1452
+ """
1453
+ Test that the context contains the data about existing comments necessary to initialize the commenting app
1454
+ """
1455
+ form = self.EventPageForm(instance=self.event_page)
1456
+ panel = self.object_list.get_bound_panel(
1457
+ request=self.request, instance=self.event_page, form=form
1458
+ ).children[0]
1459
+ data = panel.get_context_data()["comments_data"]
1460
+
1461
+ self.assertEqual(data["user"], self.commenting_user.pk)
1462
+
1463
+ self.assertEqual(len(data["comments"]), 1)
1464
+ self.assertEqual(data["comments"][0]["user"], self.comment.user.pk)
1465
+
1466
+ self.assertEqual(len(data["comments"][0]["replies"]), 2)
1467
+ self.assertEqual(
1468
+ data["comments"][0]["replies"][0]["user"], self.reply_1.user.pk
1469
+ )
1470
+ self.assertEqual(
1471
+ data["comments"][0]["replies"][1]["user"], self.reply_2.user.pk
1472
+ )
1473
+
1474
+ self.assertIn(str(self.commenting_user.pk), data["authors"])
1475
+ self.assertIn(str(self.other_user.pk), data["authors"])
1476
+
1477
+ try:
1478
+ json_script(data, "comments-data")
1479
+ except TypeError:
1480
+ self.fail(
1481
+ "Failed to serialize comments data. This is likely due to a custom user model using an unsupported field."
1482
+ )
1483
+
1484
+ def test_form(self):
1485
+ """
1486
+ Check that the form has the comments/replies formsets, and that the
1487
+ user has been set on each CommentForm/CommentReplyForm instance
1488
+ """
1489
+ form = self.EventPageForm(
1490
+ instance=self.event_page, for_user=self.commenting_user
1491
+ )
1492
+
1493
+ self.assertIn("comments", form.formsets)
1494
+
1495
+ comments_formset = form.formsets["comments"]
1496
+ self.assertEqual(len(comments_formset.forms), 1)
1497
+ self.assertEqual(comments_formset.forms[0].for_user, self.commenting_user)
1498
+
1499
+ replies_formset = comments_formset.forms[0].formsets["replies"]
1500
+ self.assertEqual(len(replies_formset.forms), 2)
1501
+ self.assertEqual(replies_formset.forms[0].for_user, self.commenting_user)
1502
+
1503
+ def test_comment_form_validation(self):
1504
+
1505
+ form = self.EventPageForm(
1506
+ {
1507
+ "comments-TOTAL_FORMS": 2,
1508
+ "comments-INITIAL_FORMS": 1,
1509
+ "comments-MIN_NUM_FORMS": 0,
1510
+ "comments-MAX_NUM_FORMS": 1000,
1511
+ "comments-0-id": self.comment.pk,
1512
+ "comments-0-text": "edited text", # Try to edit an existing comment from another user
1513
+ "comments-0-contentpath": self.comment.contentpath,
1514
+ "comments-0-replies-TOTAL_FORMS": 0,
1515
+ "comments-0-replies-INITIAL_FORMS": 0,
1516
+ "comments-0-replies-MIN_NUM_FORMS": 0,
1517
+ "comments-0-replies-MAX_NUM_FORMS": 1000,
1518
+ "comments-1-id": "",
1519
+ "comments-1-text": "new comment", # Add a new comment
1520
+ "comments-1-contentpath": "new.path",
1521
+ "comments-1-replies-TOTAL_FORMS": 0,
1522
+ "comments-1-replies-INITIAL_FORMS": 0,
1523
+ "comments-1-replies-MIN_NUM_FORMS": 0,
1524
+ "comments-1-replies-MAX_NUM_FORMS": 1000,
1525
+ },
1526
+ instance=self.event_page,
1527
+ for_user=self.commenting_user,
1528
+ )
1529
+
1530
+ comment_form = form.formsets["comments"].forms[0]
1531
+ self.assertFalse(comment_form.is_valid())
1532
+ # The existing comment was from another user, so should not be editable
1533
+
1534
+ comment_form = form.formsets["comments"].forms[1]
1535
+ self.assertTrue(comment_form.is_valid())
1536
+ self.assertEqual(comment_form.instance.user, self.commenting_user)
1537
+ # The commenting user should be able to add a new comment, and the new comment's user should be set to request.user
1538
+
1539
+ form = self.EventPageForm(
1540
+ {
1541
+ "comments-TOTAL_FORMS": 1,
1542
+ "comments-INITIAL_FORMS": 1,
1543
+ "comments-MIN_NUM_FORMS": 0,
1544
+ "comments-MAX_NUM_FORMS": 1000,
1545
+ "comments-0-id": self.comment.pk,
1546
+ "comments-0-text": self.comment.text,
1547
+ "comments-0-contentpath": self.comment.contentpath,
1548
+ "comments-0-DELETE": 1, # Try to delete a comment from another user
1549
+ "comments-0-replies-TOTAL_FORMS": 0,
1550
+ "comments-0-replies-INITIAL_FORMS": 0,
1551
+ "comments-0-replies-MIN_NUM_FORMS": 0,
1552
+ "comments-0-replies-MAX_NUM_FORMS": 1000,
1553
+ },
1554
+ instance=self.event_page,
1555
+ for_user=self.commenting_user,
1556
+ )
1557
+
1558
+ comment_form = form.formsets["comments"].forms[0]
1559
+ self.assertFalse(comment_form.is_valid())
1560
+ # Users cannot delete comments from other users
1561
+
1562
+ def test_users_can_edit_comment_positions(self):
1563
+ form = self.EventPageForm(
1564
+ {
1565
+ "comments-TOTAL_FORMS": 1,
1566
+ "comments-INITIAL_FORMS": 1,
1567
+ "comments-MIN_NUM_FORMS": 0,
1568
+ "comments-MAX_NUM_FORMS": 1000,
1569
+ "comments-0-id": self.comment.pk,
1570
+ "comments-0-text": self.comment.text,
1571
+ "comments-0-contentpath": self.comment.contentpath,
1572
+ "comments-0-position": "a_new_position", # Try to change the position of a comment
1573
+ "comments-0-DELETE": 0,
1574
+ "comments-0-replies-TOTAL_FORMS": 0,
1575
+ "comments-0-replies-INITIAL_FORMS": 0,
1576
+ "comments-0-replies-MIN_NUM_FORMS": 0,
1577
+ "comments-0-replies-MAX_NUM_FORMS": 1000,
1578
+ },
1579
+ instance=self.event_page,
1580
+ for_user=self.commenting_user,
1581
+ )
1582
+
1583
+ comment_form = form.formsets["comments"].forms[0]
1584
+ self.assertTrue(comment_form.is_valid())
1585
+ # Users can change the positions of other users' comments within a field
1586
+ # eg by editing a rich text field
1587
+
1588
+ @freeze_time("2017-01-01 12:00:00")
1589
+ def test_comment_resolve(self):
1590
+ form = self.EventPageForm(
1591
+ {
1592
+ "comments-TOTAL_FORMS": 1,
1593
+ "comments-INITIAL_FORMS": 1,
1594
+ "comments-MIN_NUM_FORMS": 0,
1595
+ "comments-MAX_NUM_FORMS": 1000,
1596
+ "comments-0-id": self.comment.pk,
1597
+ "comments-0-text": self.comment.text,
1598
+ "comments-0-contentpath": self.comment.contentpath,
1599
+ "comments-0-resolved": 1,
1600
+ "comments-0-replies-TOTAL_FORMS": 0,
1601
+ "comments-0-replies-INITIAL_FORMS": 0,
1602
+ "comments-0-replies-MIN_NUM_FORMS": 0,
1603
+ "comments-0-replies-MAX_NUM_FORMS": 1000,
1604
+ },
1605
+ instance=self.event_page,
1606
+ for_user=self.commenting_user,
1607
+ )
1608
+ comment_form = form.formsets["comments"].forms[0]
1609
+ self.assertTrue(comment_form.is_valid())
1610
+ comment_form.save()
1611
+ resolved_comment = Comment.objects.get(pk=self.comment.pk)
1612
+ self.assertEqual(resolved_comment.resolved_by, self.commenting_user)
1613
+
1614
+ if settings.USE_TZ:
1615
+ self.assertEqual(
1616
+ resolved_comment.resolved_at, datetime(2017, 1, 1, 12, 0, 0, tzinfo=utc)
1617
+ )
1618
+ else:
1619
+ self.assertEqual(
1620
+ resolved_comment.resolved_at, datetime(2017, 1, 1, 12, 0, 0)
1621
+ )
1622
+
1623
+ def test_comment_reply_form_validation(self):
1624
+
1625
+ form = self.EventPageForm(
1626
+ {
1627
+ "comments-TOTAL_FORMS": 1,
1628
+ "comments-INITIAL_FORMS": 1,
1629
+ "comments-MIN_NUM_FORMS": 0,
1630
+ "comments-MAX_NUM_FORMS": 1000,
1631
+ "comments-0-id": self.comment.pk,
1632
+ "comments-0-text": self.comment.text,
1633
+ "comments-0-contentpath": self.comment.contentpath,
1634
+ "comments-0-replies-TOTAL_FORMS": 3,
1635
+ "comments-0-replies-INITIAL_FORMS": 2,
1636
+ "comments-0-replies-MIN_NUM_FORMS": 0,
1637
+ "comments-0-replies-MAX_NUM_FORMS": 1000,
1638
+ "comments-0-replies-0-id": self.reply_1.pk,
1639
+ "comments-0-replies-0-text": "edited_text", # Try to edit someone else's reply
1640
+ "comments-0-replies-1-id": self.reply_2.pk,
1641
+ "comments-0-replies-1-text": "Edited text 2", # Try to edit own reply
1642
+ "comments-0-replies-2-id": "", # Add new reply
1643
+ "comments-0-replies-2-text": "New reply",
1644
+ },
1645
+ instance=self.event_page,
1646
+ for_user=self.commenting_user,
1647
+ )
1648
+
1649
+ comment_form = form.formsets["comments"].forms[0]
1650
+
1651
+ reply_forms = comment_form.formsets["replies"].forms
1652
+
1653
+ self.assertFalse(reply_forms[0].is_valid())
1654
+ # The existing reply was from another user, so should not be editable
1655
+
1656
+ self.assertTrue(reply_forms[1].is_valid())
1657
+ # The existing reply was from the same user, so should be editable
1658
+
1659
+ self.assertTrue(reply_forms[2].is_valid())
1660
+ self.assertEqual(reply_forms[2].instance.user, self.commenting_user)
1661
+ # Should be able to add new reply, and user should be set correctly
1662
+
1663
+ form = self.EventPageForm(
1664
+ {
1665
+ "comments-TOTAL_FORMS": 1,
1666
+ "comments-INITIAL_FORMS": 1,
1667
+ "comments-MIN_NUM_FORMS": 0,
1668
+ "comments-MAX_NUM_FORMS": 1000,
1669
+ "comments-0-id": self.comment.pk,
1670
+ "comments-0-text": self.comment.text,
1671
+ "comments-0-contentpath": self.comment.contentpath,
1672
+ "comments-0-replies-TOTAL_FORMS": 2,
1673
+ "comments-0-replies-INITIAL_FORMS": 2,
1674
+ "comments-0-replies-MIN_NUM_FORMS": 0,
1675
+ "comments-0-replies-MAX_NUM_FORMS": 1000,
1676
+ "comments-0-replies-0-id": self.reply_1.pk,
1677
+ "comments-0-replies-0-text": self.reply_1.text,
1678
+ "comments-0-replies-0-DELETE": 1, # Try to delete someone else's reply
1679
+ "comments-0-replies-1-id": self.reply_2.pk,
1680
+ "comments-0-replies-1-text": "Edited text 2",
1681
+ "comments-0-replies-1-DELETE": 1, # Try to delete own reply
1682
+ },
1683
+ instance=self.event_page,
1684
+ for_user=self.commenting_user,
1685
+ )
1686
+
1687
+ comment_form = form.formsets["comments"].forms[0]
1688
+
1689
+ reply_forms = comment_form.formsets["replies"].forms
1690
+
1691
+ self.assertFalse(reply_forms[0].is_valid())
1692
+ # The existing reply was from another user, so should not be deletable
1693
+
1694
+ self.assertTrue(reply_forms[1].is_valid())
1695
+ # The existing reply was from the same user, so should be deletable
1696
+
1697
+
1698
+ class TestPublishingPanel(TestCase, WagtailTestUtils):
1699
+ fixtures = ["test.json"]
1700
+
1701
+ def setUp(self):
1702
+ self.user = self.login()
1703
+
1704
+ unbound_object_list = ObjectList([PublishingPanel()])
1705
+ self.object_list = unbound_object_list.bind_to_model(EventPage)
1706
+ self.tabbed_interface = TabbedInterface([unbound_object_list]).bind_to_model(
1707
+ EventPage
1708
+ )
1709
+
1710
+ self.EventPageForm = self.object_list.get_form_class()
1711
+ self.event_page = EventPage.objects.get(slug="christmas")
1712
+
1713
+ def test_schedule_publishing_toggle_toggle_shown(self):
1714
+ """
1715
+ Test that the schedule publishing toggle is shown for a TabbedInterface containing PublishingPanel, and disabled otherwise
1716
+ """
1717
+ form_class = self.tabbed_interface.get_form_class()
1718
+ form = form_class()
1719
+ self.assertTrue(form.show_schedule_publishing_toggle)
1720
+
1721
+ tabbed_interface_without_publishing_panel = TabbedInterface(
1722
+ [ObjectList(self.event_page.content_panels)]
1723
+ ).bind_to_model(EventPage)
1724
+ form_class = tabbed_interface_without_publishing_panel.get_form_class()
1725
+ form = form_class()
1726
+ self.assertFalse(form.show_schedule_publishing_toggle)
1727
+
1728
+ def test_publishing_panel_shown_by_default(self):
1729
+ """
1730
+ Test that the publishing panel is present by default
1731
+ """
1732
+ self.assertTrue(
1733
+ any(isinstance(panel, PublishingPanel) for panel in Page.settings_panels)
1734
+ )
1735
+ form_class = Page.get_edit_handler().get_form_class()
1736
+ form = form_class()
1737
+ self.assertTrue(form.show_schedule_publishing_toggle)
1738
+
1739
+ def test_form(self):
1740
+ """
1741
+ Check that the form has the scheduled publishing fields
1742
+ """
1743
+ form = self.EventPageForm(instance=self.event_page, for_user=self.user)
1744
+
1745
+ self.assertIn("go_live_at", form.base_fields)
1746
+ self.assertIn("expire_at", form.base_fields)
testbed/wagtail__wagtail/wagtail/admin/tests/test_filters.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django import forms
2
+ from django.contrib.auth import get_user_model
3
+ from django.contrib.auth.models import Group
4
+ from django.test import TestCase
5
+
6
+ from wagtail.admin.filters import FilteredModelChoiceField
7
+ from wagtail.test.utils import WagtailTestUtils
8
+
9
+ User = get_user_model()
10
+
11
+
12
+ class TestFilteredModelChoiceField(TestCase, WagtailTestUtils):
13
+ def setUp(self):
14
+ self.musicians = Group.objects.create(name="Musicians")
15
+ self.actors = Group.objects.create(name="Actors")
16
+
17
+ self.david = self.create_user(
18
+ "david",
19
+ "david@example.com",
20
+ "kn1ghtr1der",
21
+ first_name="David",
22
+ last_name="Hasselhoff",
23
+ )
24
+ self.david.groups.set([self.musicians, self.actors])
25
+
26
+ self.kevin = self.create_user(
27
+ "kevin",
28
+ "kevin@example.com",
29
+ "6degrees",
30
+ first_name="Kevin",
31
+ last_name="Bacon",
32
+ )
33
+ self.kevin.groups.set([self.actors])
34
+
35
+ self.morten = self.create_user(
36
+ "morten",
37
+ "morten@example.com",
38
+ "t4ke0nm3",
39
+ first_name="Morten",
40
+ last_name="Harket",
41
+ )
42
+ self.morten.groups.set([self.musicians])
43
+
44
+ def test_with_relation(self):
45
+ class UserForm(forms.Form):
46
+ users = FilteredModelChoiceField(
47
+ queryset=User.objects.order_by(User.USERNAME_FIELD),
48
+ filter_field="id_group",
49
+ filter_accessor="groups",
50
+ )
51
+
52
+ form = UserForm()
53
+ html = str(form["users"])
54
+ expected_html = """
55
+ <select name="users" data-widget="filtered-select" data-filter-field="id_group" required id="id_users">
56
+ <option value="" selected>---------</option>
57
+ <option value="%(david)s" data-filter-value="%(musicians)s,%(actors)s">%(david_username)s</option>
58
+ <option value="%(kevin)s" data-filter-value="%(actors)s">%(kevin_username)s</option>
59
+ <option value="%(morten)s" data-filter-value="%(musicians)s">%(morten_username)s</option>
60
+ </select>
61
+ """ % {
62
+ "david": self.david.pk,
63
+ "kevin": self.kevin.pk,
64
+ "morten": self.morten.pk,
65
+ "musicians": self.musicians.pk,
66
+ "actors": self.actors.pk,
67
+ "david_username": self.david.get_username(),
68
+ "kevin_username": self.kevin.get_username(),
69
+ "morten_username": self.morten.get_username(),
70
+ }
71
+ self.assertHTMLEqual(html, expected_html)
72
+
73
+ def test_with_callable(self):
74
+ class UserForm(forms.Form):
75
+ users = FilteredModelChoiceField(
76
+ queryset=User.objects.order_by(User.USERNAME_FIELD),
77
+ filter_field="id_group",
78
+ filter_accessor=lambda user: user.groups.all(),
79
+ )
80
+
81
+ form = UserForm()
82
+ html = str(form["users"])
83
+ expected_html = """
84
+ <select name="users" data-widget="filtered-select" data-filter-field="id_group" required id="id_users">
85
+ <option value="" selected>---------</option>
86
+ <option value="%(david)s" data-filter-value="%(musicians)s,%(actors)s">%(david_username)s</option>
87
+ <option value="%(kevin)s" data-filter-value="%(actors)s">%(kevin_username)s</option>
88
+ <option value="%(morten)s" data-filter-value="%(musicians)s">%(morten_username)s</option>
89
+ </select>
90
+ """ % {
91
+ "david": self.david.pk,
92
+ "kevin": self.kevin.pk,
93
+ "morten": self.morten.pk,
94
+ "musicians": self.musicians.pk,
95
+ "actors": self.actors.pk,
96
+ "david_username": self.david.get_username(),
97
+ "kevin_username": self.kevin.get_username(),
98
+ "morten_username": self.morten.get_username(),
99
+ }
100
+ self.assertHTMLEqual(html, expected_html)
testbed/wagtail__wagtail/wagtail/admin/tests/test_forms.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.forms.fields import CharField
2
+ from django.test import SimpleTestCase, TestCase
3
+
4
+ from wagtail.admin.forms.auth import LoginForm, PasswordResetForm
5
+
6
+
7
+ class CustomLoginForm(LoginForm):
8
+ captcha = CharField(label="Captcha", help_text="should be in extra_fields()")
9
+
10
+
11
+ class CustomPasswordResetForm(PasswordResetForm):
12
+ captcha = CharField(label="Captcha", help_text="should be in extra_fields()")
13
+
14
+
15
+ class TestLoginForm(TestCase):
16
+ def test_extra_fields(self):
17
+ form = CustomLoginForm()
18
+ self.assertEqual(list(form.extra_fields), [("captcha", form["captcha"])])
19
+
20
+
21
+ class TestPasswordResetForm(SimpleTestCase):
22
+ def test_extra_fields(self):
23
+ form = CustomPasswordResetForm()
24
+ self.assertEqual(list(form.extra_fields), [("captcha", form["captcha"])])
testbed/wagtail__wagtail/wagtail/admin/tests/test_html_ruleset.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.test import TestCase
2
+
3
+ from wagtail.admin.rich_text.converters.html_ruleset import HTMLRuleset
4
+
5
+
6
+ class TestHTMLRuleset(TestCase):
7
+ def test_html_ruleset(self):
8
+ ruleset = HTMLRuleset(
9
+ {
10
+ "p": "paragraph",
11
+ "a[href]": "link",
12
+ "a[linktype=page]": "page-link",
13
+ 'a[linktype="silly page"]': "silly-page-link",
14
+ "a[linktype='sensible page']": "sensible-page-link",
15
+ }
16
+ )
17
+
18
+ self.assertIsNone(ruleset.match("div", {}))
19
+ self.assertEqual(ruleset.match("p", {}), "paragraph")
20
+ self.assertEqual(ruleset.match("p", {"class": "intro"}), "paragraph")
21
+ self.assertIsNone(ruleset.match("a", {"class": "button"}))
22
+ self.assertEqual(
23
+ ruleset.match("a", {"class": "button", "href": "http://wagtail.org"}),
24
+ "link",
25
+ )
26
+ self.assertIsNone(
27
+ ruleset.match("a", {"class": "button", "linktype": "document"})
28
+ )
29
+ self.assertEqual(
30
+ ruleset.match("a", {"class": "button", "linktype": "page"}), "page-link"
31
+ )
32
+ self.assertEqual(
33
+ ruleset.match("a", {"class": "button", "linktype": "silly page"}),
34
+ "silly-page-link",
35
+ )
36
+ self.assertEqual(
37
+ ruleset.match("a", {"class": "button", "linktype": "sensible page"}),
38
+ "sensible-page-link",
39
+ )
40
+
41
+ def test_precedence(self):
42
+ ruleset = HTMLRuleset()
43
+ ruleset.add_rule("p", "normal-paragraph")
44
+ ruleset.add_rule('p[class="intro"]', "intro-paragraph")
45
+ ruleset.add_rule("p", "normal-paragraph-again")
46
+
47
+ self.assertEqual(ruleset.match("p", {"class": "intro"}), "intro-paragraph")
testbed/wagtail__wagtail/wagtail/admin/tests/test_icon_sprite.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ from django.test import TestCase
4
+ from django.urls import reverse
5
+
6
+ from wagtail.admin.urls import get_sprite_hash, sprite_hash
7
+
8
+
9
+ class TestIconSprite(TestCase):
10
+ def test_get_sprite_hash(self):
11
+ result = get_sprite_hash()
12
+ self.assertTrue(bool(re.match(r"^[a-z0-9]{8}$", result)))
13
+
14
+ def test_hash_var(self):
15
+ self.assertIsInstance(sprite_hash, str)
16
+ self.assertEqual(len(sprite_hash), 8)
17
+
18
+ def test_url(self):
19
+ url = reverse("wagtailadmin_sprite")
20
+ self.assertEqual(url[:14], "/admin/sprite-")
21
+
22
+ def test_view(self):
23
+ response = self.client.get(reverse("wagtailadmin_sprite"))
24
+ self.assertIn(
25
+ "Content-Type: text/html; charset=utf-8", str(response.serialize_headers())
26
+ )
testbed/wagtail__wagtail/wagtail/admin/tests/test_jinja2.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.contrib.auth.models import AnonymousUser
2
+ from django.template import engines
3
+ from django.test import TestCase
4
+
5
+ from wagtail.coreutils import get_dummy_request
6
+ from wagtail.models import PAGE_TEMPLATE_VAR, Page, Site
7
+ from wagtail.test.utils import WagtailTestUtils
8
+
9
+
10
+ class TestCoreJinja(TestCase, WagtailTestUtils):
11
+ def setUp(self):
12
+ self.engine = engines["jinja2"]
13
+
14
+ self.user = self.create_superuser(
15
+ username="test", email="test@email.com", password="password"
16
+ )
17
+ self.homepage = Page.objects.get(id=2)
18
+
19
+ def render(self, string, context=None, request_context=True):
20
+ if context is None:
21
+ context = {}
22
+
23
+ template = self.engine.from_string(string)
24
+ return template.render(context)
25
+
26
+ def dummy_request(self, user=None):
27
+ site = Site.objects.get(is_default_site=True)
28
+ request = get_dummy_request(site=site)
29
+ request.user = user or AnonymousUser()
30
+ return request
31
+
32
+ def test_userbar(self):
33
+ content = self.render(
34
+ "{{ wagtailuserbar() }}",
35
+ {
36
+ PAGE_TEMPLATE_VAR: self.homepage,
37
+ "request": self.dummy_request(self.user),
38
+ },
39
+ )
40
+ self.assertIn("<!-- Wagtail user bar embed code -->", content)
41
+
42
+ def test_userbar_anonymous_user(self):
43
+ content = self.render(
44
+ "{{ wagtailuserbar() }}",
45
+ {PAGE_TEMPLATE_VAR: self.homepage, "request": self.dummy_request()},
46
+ )
47
+
48
+ # Make sure nothing was rendered
49
+ self.assertEqual(content, "")
testbed/wagtail__wagtail/wagtail/admin/tests/test_menu.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.test import RequestFactory, TestCase
2
+ from django.urls import reverse
3
+
4
+ from wagtail import hooks
5
+ from wagtail.admin.menu import (
6
+ AdminOnlyMenuItem,
7
+ DismissibleMenuItem,
8
+ DismissibleSubmenuMenuItem,
9
+ Menu,
10
+ MenuItem,
11
+ SubmenuMenuItem,
12
+ )
13
+ from wagtail.admin.ui import sidebar
14
+ from wagtail.test.utils import WagtailTestUtils
15
+ from wagtail.users.models import UserProfile
16
+
17
+
18
+ def menu_item_hook(*args, cls=MenuItem, **kwargs):
19
+ def hook_fn():
20
+ return cls(*args, **kwargs)
21
+
22
+ return hook_fn
23
+
24
+
25
+ class TestMenuRendering(TestCase, WagtailTestUtils):
26
+ def setUp(self):
27
+ self.request = RequestFactory().get("/admin")
28
+ self.request.user = self.create_superuser(username="admin")
29
+ self.profile = UserProfile.get_for_user(self.request.user)
30
+ self.user = self.login()
31
+
32
+ def test_remember_collapsed(self):
33
+ """Sidebar should render with collapsed class applied."""
34
+ # Sidebar should not be collapsed
35
+ self.client.cookies["wagtail_sidebar_collapsed"] = "0"
36
+ response = self.client.get(reverse("wagtailadmin_home"))
37
+ self.assertNotContains(response, "sidebar-collapsed")
38
+
39
+ # Sidebar should be collapsed
40
+ self.client.cookies["wagtail_sidebar_collapsed"] = "1"
41
+ response = self.client.get(reverse("wagtailadmin_home"))
42
+ self.assertContains(response, "sidebar-collapsed")
43
+
44
+ def test_simple_menu(self):
45
+ # Note: initialise the menu before registering hooks as this is what happens in reality.
46
+ # (the real menus are initialised at the module level in admin/menu.py)
47
+ menu = Menu(register_hook_name="register_menu_item")
48
+
49
+ with hooks.register_temporarily(
50
+ [
51
+ ("register_menu_item", menu_item_hook("Pages", "/pages/")),
52
+ ("register_menu_item", menu_item_hook("Images", "/images/")),
53
+ ]
54
+ ):
55
+ rendered = menu.render_component(self.request)
56
+
57
+ self.assertIsInstance(rendered, list)
58
+ self.assertListEqual(
59
+ rendered,
60
+ [
61
+ sidebar.LinkMenuItem("pages", "Pages", "/pages/"),
62
+ sidebar.LinkMenuItem("images", "Images", "/images/"),
63
+ ],
64
+ )
65
+
66
+ def test_menu_with_construct_hook(self):
67
+ menu = Menu(
68
+ register_hook_name="register_menu_item",
69
+ construct_hook_name="construct_menu",
70
+ )
71
+
72
+ def remove_images(request, items):
73
+ items[:] = [item for item in items if not item.name == "images"]
74
+
75
+ with hooks.register_temporarily(
76
+ [
77
+ ("register_menu_item", menu_item_hook("Pages", "/pages/")),
78
+ ("register_menu_item", menu_item_hook("Images", "/images/")),
79
+ ("construct_menu", remove_images),
80
+ ]
81
+ ):
82
+ rendered = menu.render_component(self.request)
83
+
84
+ self.assertEqual(
85
+ rendered,
86
+ [
87
+ sidebar.LinkMenuItem("pages", "Pages", "/pages/"),
88
+ ],
89
+ )
90
+
91
+ def test_submenu(self):
92
+ menu = Menu(register_hook_name="register_menu_item")
93
+ submenu = Menu(register_hook_name="register_submenu_item")
94
+
95
+ with hooks.register_temporarily(
96
+ [
97
+ (
98
+ "register_menu_item",
99
+ menu_item_hook("My lovely submenu", submenu, cls=SubmenuMenuItem),
100
+ ),
101
+ ("register_submenu_item", menu_item_hook("Pages", "/pages/")),
102
+ ]
103
+ ):
104
+ rendered = menu.render_component(self.request)
105
+
106
+ self.assertIsInstance(rendered, list)
107
+ self.assertEqual(len(rendered), 1)
108
+ self.assertIsInstance(rendered[0], sidebar.SubMenuItem)
109
+ self.assertEqual(rendered[0].name, "my-lovely-submenu")
110
+ self.assertEqual(rendered[0].label, "My lovely submenu")
111
+ self.assertListEqual(
112
+ rendered[0].menu_items,
113
+ [
114
+ sidebar.LinkMenuItem("pages", "Pages", "/pages/"),
115
+ ],
116
+ )
117
+
118
+ def test_dismissible_initial(self):
119
+ menu = Menu(register_hook_name="register_menu_item")
120
+ submenu = Menu(register_hook_name="register_submenu_item")
121
+
122
+ with hooks.register_temporarily(
123
+ [
124
+ (
125
+ "register_menu_item",
126
+ menu_item_hook(
127
+ "My dismissible submenu",
128
+ submenu,
129
+ cls=DismissibleSubmenuMenuItem,
130
+ name="dismissible-submenu-menu-item",
131
+ ),
132
+ ),
133
+ (
134
+ "register_submenu_item",
135
+ menu_item_hook(
136
+ "Pages",
137
+ "/pages/",
138
+ cls=DismissibleMenuItem,
139
+ name="dismissible-menu-item",
140
+ ),
141
+ ),
142
+ ]
143
+ ):
144
+ rendered = menu.render_component(self.request)
145
+
146
+ self.assertIsInstance(rendered, list)
147
+ self.assertEqual(len(rendered), 1)
148
+ self.assertIsInstance(rendered[0], sidebar.SubMenuItem)
149
+ self.assertEqual(rendered[0].name, "dismissible-submenu-menu-item")
150
+ self.assertEqual(rendered[0].label, "My dismissible submenu")
151
+ self.assertEqual(
152
+ rendered[0].attrs,
153
+ # Should not be dismissed
154
+ {"data-wagtail-dismissible-id": "dismissible-submenu-menu-item"},
155
+ )
156
+ self.assertListEqual(
157
+ rendered[0].menu_items,
158
+ [
159
+ sidebar.LinkMenuItem(
160
+ "dismissible-menu-item",
161
+ "Pages",
162
+ "/pages/",
163
+ # Should not be dismissed
164
+ attrs={"data-wagtail-dismissible-id": "dismissible-menu-item"},
165
+ ),
166
+ ],
167
+ )
168
+
169
+ def test_dismissible_dismissed(self):
170
+ self.profile.dismissibles = {
171
+ "dismissible-submenu-menu-item": True,
172
+ "dismissible-menu-item": True,
173
+ }
174
+ self.profile.save()
175
+ self.request.user.refresh_from_db()
176
+
177
+ menu = Menu(register_hook_name="register_menu_item")
178
+ submenu = Menu(register_hook_name="register_submenu_item")
179
+
180
+ with hooks.register_temporarily(
181
+ [
182
+ (
183
+ "register_menu_item",
184
+ menu_item_hook(
185
+ "My dismissible submenu",
186
+ submenu,
187
+ cls=DismissibleSubmenuMenuItem,
188
+ name="dismissible-submenu-menu-item",
189
+ ),
190
+ ),
191
+ (
192
+ "register_submenu_item",
193
+ menu_item_hook(
194
+ "Pages",
195
+ "/pages/",
196
+ cls=DismissibleMenuItem,
197
+ name="dismissible-menu-item",
198
+ ),
199
+ ),
200
+ ]
201
+ ):
202
+ rendered = menu.render_component(self.request)
203
+
204
+ self.assertIsInstance(rendered, list)
205
+ self.assertEqual(len(rendered), 1)
206
+ self.assertIsInstance(rendered[0], sidebar.SubMenuItem)
207
+ self.assertEqual(rendered[0].name, "dismissible-submenu-menu-item")
208
+ self.assertEqual(rendered[0].label, "My dismissible submenu")
209
+ self.assertEqual(
210
+ rendered[0].attrs,
211
+ {
212
+ "data-wagtail-dismissible-id": "dismissible-submenu-menu-item",
213
+ # Should be dismissed
214
+ "data-wagtail-dismissed": "",
215
+ },
216
+ )
217
+ self.assertListEqual(
218
+ rendered[0].menu_items,
219
+ [
220
+ sidebar.LinkMenuItem(
221
+ "dismissible-menu-item",
222
+ "Pages",
223
+ "/pages/",
224
+ # Should be dismissed
225
+ attrs={
226
+ "data-wagtail-dismissible-id": "dismissible-menu-item",
227
+ "data-wagtail-dismissed": "",
228
+ },
229
+ ),
230
+ ],
231
+ )
232
+
233
+ def test_dismissible_no_userprofile(self):
234
+ # Without a user profile, dismissible menu items should not be dismissed
235
+ self.profile.delete()
236
+ self.request.user.refresh_from_db()
237
+
238
+ menu = Menu(register_hook_name="register_menu_item")
239
+ submenu = Menu(register_hook_name="register_submenu_item")
240
+
241
+ with hooks.register_temporarily(
242
+ [
243
+ (
244
+ "register_menu_item",
245
+ menu_item_hook(
246
+ "My dismissible submenu",
247
+ submenu,
248
+ cls=DismissibleSubmenuMenuItem,
249
+ name="dismissible-submenu-menu-item",
250
+ ),
251
+ ),
252
+ (
253
+ "register_submenu_item",
254
+ menu_item_hook(
255
+ "Pages",
256
+ "/pages/",
257
+ cls=DismissibleMenuItem,
258
+ name="dismissible-menu-item",
259
+ ),
260
+ ),
261
+ ]
262
+ ):
263
+ rendered = menu.render_component(self.request)
264
+
265
+ self.assertIsInstance(rendered, list)
266
+ self.assertEqual(len(rendered), 1)
267
+ self.assertIsInstance(rendered[0], sidebar.SubMenuItem)
268
+ self.assertEqual(rendered[0].name, "dismissible-submenu-menu-item")
269
+ self.assertEqual(rendered[0].label, "My dismissible submenu")
270
+ self.assertEqual(
271
+ rendered[0].attrs,
272
+ {"data-wagtail-dismissible-id": "dismissible-submenu-menu-item"},
273
+ )
274
+ self.assertListEqual(
275
+ rendered[0].menu_items,
276
+ [
277
+ sidebar.LinkMenuItem(
278
+ "dismissible-menu-item",
279
+ "Pages",
280
+ "/pages/",
281
+ attrs={"data-wagtail-dismissible-id": "dismissible-menu-item"},
282
+ ),
283
+ ],
284
+ )
285
+
286
+ def test_admin_only_menuitem(self):
287
+ menu = Menu(register_hook_name="register_menu_item")
288
+
289
+ with hooks.register_temporarily(
290
+ [
291
+ ("register_menu_item", menu_item_hook("Pages", "/pages/")),
292
+ (
293
+ "register_menu_item",
294
+ menu_item_hook(
295
+ "Secret pages", "/pages/secret/", cls=AdminOnlyMenuItem
296
+ ),
297
+ ),
298
+ ]
299
+ ):
300
+ rendered = menu.render_component(self.request)
301
+ self.request.user = self.create_user(username="non-admin")
302
+ rendered_non_admin = menu.render_component(self.request)
303
+
304
+ self.assertListEqual(
305
+ rendered,
306
+ [
307
+ sidebar.LinkMenuItem("pages", "Pages", "/pages/"),
308
+ sidebar.LinkMenuItem("secret-pages", "Secret pages", "/pages/secret/"),
309
+ ],
310
+ )
311
+
312
+ self.assertListEqual(
313
+ rendered_non_admin,
314
+ [
315
+ sidebar.LinkMenuItem("pages", "Pages", "/pages/"),
316
+ ],
317
+ )
testbed/wagtail__wagtail/wagtail/admin/tests/test_messages.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.test import TestCase
2
+ from django.urls import reverse
3
+
4
+
5
+ class TestPageExplorer(TestCase):
6
+ def test_message_tag_classes(self):
7
+ url = reverse("testapp_message_test")
8
+
9
+ response = self.client.post(
10
+ url, {"level": "success", "message": "A message"}, follow=True
11
+ )
12
+ # Make sure the message appears
13
+ self.assertContains(response, "A message")
14
+ # Make sure the Wagtail-require CSS tag appears
15
+ self.assertContains(response, "success")
16
+
17
+ # https://github.com/wagtail/wagtail/issues/2551 -
18
+ # `my-custom-tag` is set in MESSAGE_TAGS in the project settings, which
19
+ # end-users should be able to do without it leaking into the admin styles.
20
+ self.assertNotContains(response, "my-custom-tag")
21
+
22
+ response = self.client.post(
23
+ url, {"level": "error", "message": "Danger danger!"}, follow=True
24
+ )
25
+ self.assertContains(response, "Danger danger!")
26
+ self.assertContains(response, "error")
27
+ self.assertNotContains(response, "my-custom-tag")
testbed/wagtail__wagtail/wagtail/admin/tests/test_moderation_list.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.contrib.auth.models import Group, Permission
2
+ from django.test import TestCase
3
+ from django.urls import reverse
4
+
5
+ from wagtail.models import GroupPagePermission, Page
6
+ from wagtail.test.testapp.models import SimplePage
7
+ from wagtail.test.utils import WagtailTestUtils
8
+
9
+
10
+ class TestModerationList(TestCase, WagtailTestUtils):
11
+ """Test moderation list rendered by `wagtailadmin_home` view"""
12
+
13
+ def setUp(self):
14
+ # Create a submitter
15
+ submitter = self.create_user(
16
+ username="submitter",
17
+ email="submitter@email.com",
18
+ password="password",
19
+ )
20
+
21
+ # Find root page
22
+ self.root_page = Page.objects.get(id=2)
23
+
24
+ # Create a page
25
+ self.page = SimplePage(
26
+ title="Wagtail, the powerful CMS for modern websites",
27
+ slug="wagtail",
28
+ content="Fast, elegant, open source",
29
+ )
30
+
31
+ self.root_page.add_child(instance=self.page)
32
+
33
+ # Submit it for moderation
34
+ self.page.save_revision(user=submitter, submitted_for_moderation=True)
35
+
36
+ # Create a revision
37
+ self.revision = self.page.get_latest_revision()
38
+
39
+ self.edit_page_url = reverse(
40
+ "wagtailadmin_pages:edit", args=(self.revision.object_id,)
41
+ )
42
+ self.preview_page_url = reverse(
43
+ "wagtailadmin_pages:preview_for_moderation", args=(self.revision.id,)
44
+ )
45
+
46
+ def login_as_moderator_without_edit(self):
47
+ # Create moderators group without edit permissions
48
+ moderators_group = Group.objects.create(name="Moderators without edit")
49
+
50
+ admin_permission = Permission.objects.get(
51
+ content_type__app_label="wagtailadmin", codename="access_admin"
52
+ )
53
+
54
+ moderators_group.permissions.add(admin_permission)
55
+
56
+ # Create group permissions
57
+ GroupPagePermission.objects.create(
58
+ group=moderators_group,
59
+ page=self.root_page,
60
+ permission_type="publish",
61
+ )
62
+
63
+ # Create a moderator without edit permissions
64
+ moderator = self.create_user(
65
+ username="moderator", email="moderator@email.com", password="password"
66
+ )
67
+
68
+ moderator.groups.add(moderators_group)
69
+
70
+ self.login(moderator)
71
+
72
+ def get(self):
73
+ return self.client.get(reverse("wagtailadmin_home"))
74
+
75
+ def test_edit_page(self):
76
+ # Login as moderator
77
+ self.login()
78
+
79
+ response = self.get()
80
+
81
+ self.assertEqual(response.status_code, 200)
82
+ self.assertTemplateUsed(response, "wagtailadmin/home.html")
83
+
84
+ # Check response
85
+ self.assertContains(response, self.edit_page_url, count=2)
86
+
87
+ # page should contain Approve and Reject forms including a valid CSRF token
88
+ self.assertRegex(
89
+ response.content.decode("utf-8"),
90
+ r'<input type="hidden" name="csrfmiddlewaretoken" value="\w+">',
91
+ )
92
+
93
+ def test_preview_for_moderation(self):
94
+ # Login as moderator without edit permissions
95
+ self.login_as_moderator_without_edit()
96
+
97
+ response = self.get()
98
+
99
+ self.assertEqual(response.status_code, 200)
100
+ self.assertTemplateUsed(response, "wagtailadmin/home.html")
101
+
102
+ # Check response
103
+ self.assertContains(response, self.preview_page_url, count=2)
104
+ self.assertNotContains(response, self.edit_page_url)
testbed/wagtail__wagtail/wagtail/admin/tests/test_navigation.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from django.contrib.auth import get_user_model
4
+ from django.test import TestCase
5
+
6
+ from wagtail.admin.navigation import (
7
+ get_explorable_root_page,
8
+ get_pages_with_direct_explore_permission,
9
+ )
10
+ from wagtail.test.utils import WagtailTestUtils
11
+
12
+
13
+ class TestExplorablePages(TestCase, WagtailTestUtils):
14
+ """
15
+ Test the way that the explorer nav menu behaves for users with different permissions.
16
+
17
+ This is isolated in its own test case because it requires a custom page tree and custom set of
18
+ users and groups.
19
+ The fixture sets up this page tree:
20
+ ========================================================
21
+ ID Site Path
22
+ ========================================================
23
+ 1 /
24
+ 2 testserver /home/
25
+ 3 testserver /home/about-us/
26
+ 4 example.com /home/
27
+ 5 example.com /home/content/
28
+ 6 example.com /home/content/page-1/
29
+ 7 example.com /home/content/page-2/
30
+ 9 example.com /home/content/page-2/child-1
31
+ 8 example.com /home/other-content/
32
+ 10 example.com /home-2/
33
+ ========================================================
34
+ Group 1 has explore and choose permissions rooted at testserver's homepage.
35
+ Group 2 has explore and choose permissions rooted at example.com's page-1.
36
+ Group 3 has explore and choose permissions rooted at example.com's other-content.
37
+ User "jane" is in Group 1.
38
+ User "bob" is in Group 2.
39
+ User "sam" is in Groups 1 and 2.
40
+ User "josh" is in Groups 2 and 3.
41
+ User "mary" is is no Groups, but she has the "access wagtail admin" permission.
42
+ User "superman" is an admin.
43
+
44
+ Note that the Explorer Nav does not display leaf nodes.
45
+ """
46
+
47
+ fixtures = ["test_explorable_pages.json"]
48
+
49
+ def test_admins_see_all_pages(self):
50
+ User = get_user_model()
51
+ user = User.objects.get(email="superman@example.com")
52
+ self.assertEqual(get_explorable_root_page(user).id, 1)
53
+
54
+ def test_nav_root_for_nonadmin_is_closest_common_ancestor(self):
55
+ User = get_user_model()
56
+ user = User.objects.get(email="jane@example.com")
57
+ self.assertEqual(get_explorable_root_page(user).id, 2)
58
+
59
+ def test_nonadmin_sees_leaf_page_at_root_level(self):
60
+ User = get_user_model()
61
+ user = User.objects.get(email="bob@example.com")
62
+ self.assertEqual(get_explorable_root_page(user).id, 6)
63
+
64
+ def test_nonadmin_sees_pages_below_closest_common_ancestor(self):
65
+ User = get_user_model()
66
+ user = User.objects.get(email="josh@example.com")
67
+ # Josh has permissions for /example-home/content/page-1 and /example-home/other-content,
68
+ # of which the closest common ancestor is /example-home.
69
+ self.assertEqual(get_explorable_root_page(user).id, 4)
70
+ for page in get_pages_with_direct_explore_permission(user):
71
+ self.assertIn(page.id, [6, 8])
72
+
73
+ def test_nonadmin_sees_only_explorable_pages(self):
74
+ # Sam has permissions for /home and /example-home/content/page-1 , of which the closest
75
+ # common ancestor is root; we don't show root in the menu, so the top level will consist
76
+ # of 'home' and 'example-home' (but not the sibling 'home-2', which Sam doesn't have
77
+ # permission on)
78
+ User = get_user_model()
79
+ user = User.objects.get(email="sam@example.com")
80
+ self.assertEqual(get_explorable_root_page(user).id, 1)
81
+ for page in get_pages_with_direct_explore_permission(user):
82
+ self.assertIn(page.id, [2, 6])
83
+
84
+ def test_nonadmin_with_no_page_perms_cannot_explore(self):
85
+ User = get_user_model()
86
+ user = User.objects.get(email="mary@example.com")
87
+ self.assertIsNone(get_explorable_root_page(user))
testbed/wagtail__wagtail/wagtail/admin/tests/test_page_chooser.py ADDED
@@ -0,0 +1,1204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ from django.contrib.auth import get_user_model
4
+ from django.test import TestCase, override_settings
5
+ from django.urls import reverse
6
+ from django.utils.http import urlencode
7
+
8
+ from wagtail.admin.views.chooser import can_choose_page
9
+ from wagtail.models import Locale, Page, UserPagePermissionsProxy
10
+ from wagtail.test.testapp.models import (
11
+ EventIndex,
12
+ EventPage,
13
+ SimplePage,
14
+ SingleEventPage,
15
+ )
16
+ from wagtail.test.utils import WagtailTestUtils
17
+
18
+
19
+ class TestChooserBrowse(TestCase, WagtailTestUtils):
20
+ def setUp(self):
21
+ self.root_page = Page.objects.get(id=2)
22
+
23
+ # Add child page
24
+ self.child_page = SimplePage(title="foobarbaz", content="hello")
25
+ self.root_page.add_child(instance=self.child_page)
26
+
27
+ self.login()
28
+
29
+ def get(self, params={}):
30
+ return self.client.get(reverse("wagtailadmin_choose_page"), params)
31
+
32
+ def test_simple(self):
33
+ response = self.get()
34
+ self.assertEqual(response.status_code, 200)
35
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/browse.html")
36
+
37
+ def test_construct_queryset_hook(self):
38
+ page = SimplePage(title="Test shown", content="hello")
39
+ Page.get_first_root_node().add_child(instance=page)
40
+
41
+ page_not_shown = SimplePage(title="Test not shown", content="hello")
42
+ Page.get_first_root_node().add_child(instance=page_not_shown)
43
+
44
+ def filter_pages(pages, request):
45
+ return pages.filter(id=page.id)
46
+
47
+ with self.register_hook("construct_page_chooser_queryset", filter_pages):
48
+ response = self.get()
49
+ # 'results' in the template context consists of the parent page followed by the queryset
50
+ self.assertEqual(len(response.context["table"].data), 2)
51
+ self.assertEqual(response.context["table"].data[1].specific, page)
52
+
53
+
54
+ class TestCanChooseRootFlag(TestCase, WagtailTestUtils):
55
+ def setUp(self):
56
+ self.login()
57
+
58
+ def get(self, params={}):
59
+ return self.client.get(reverse("wagtailadmin_choose_page"), params)
60
+
61
+ def test_cannot_choose_root_by_default(self):
62
+ response = self.get()
63
+ self.assertNotContains(response, "/admin/pages/1/edit/")
64
+
65
+ def test_can_choose_root(self):
66
+ response = self.get({"can_choose_root": "true"})
67
+ self.assertContains(response, "/admin/pages/1/edit/")
68
+
69
+
70
+ class TestChooserBrowseChild(TestCase, WagtailTestUtils):
71
+ def setUp(self):
72
+ self.root_page = Page.objects.get(id=2)
73
+
74
+ # Add child page
75
+ self.child_page = SimplePage(title="foobarbaz", content="hello")
76
+ self.root_page.add_child(instance=self.child_page)
77
+
78
+ self.login()
79
+
80
+ def get(self, params={}):
81
+ return self.client.get(
82
+ reverse("wagtailadmin_choose_page_child", args=(self.root_page.id,)), params
83
+ )
84
+
85
+ def get_invalid(self, params={}):
86
+ return self.client.get(
87
+ reverse("wagtailadmin_choose_page_child", args=(9999999,)), params
88
+ )
89
+
90
+ def test_simple(self):
91
+ response = self.get()
92
+ self.assertEqual(response.status_code, 200)
93
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/browse.html")
94
+
95
+ def test_get_invalid(self):
96
+ self.assertEqual(self.get_invalid().status_code, 404)
97
+
98
+ def test_with_page_type(self):
99
+ # Add a page that is not a SimplePage
100
+ event_page = EventPage(
101
+ title="event",
102
+ location="the moon",
103
+ audience="public",
104
+ cost="free",
105
+ date_from="2001-01-01",
106
+ )
107
+ self.root_page.add_child(instance=event_page)
108
+
109
+ # Add a page with a child page
110
+ event_index_page = EventIndex(
111
+ title="events",
112
+ )
113
+ self.root_page.add_child(instance=event_index_page)
114
+ event_index_page.add_child(
115
+ instance=EventPage(
116
+ title="other event",
117
+ location="the moon",
118
+ audience="public",
119
+ cost="free",
120
+ date_from="2001-01-01",
121
+ )
122
+ )
123
+
124
+ # Send request
125
+ response = self.get({"page_type": "tests.simplepage"})
126
+ self.assertEqual(response.status_code, 200)
127
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/browse.html")
128
+ self.assertEqual(response.context["page_type_string"], "tests.simplepage")
129
+
130
+ pages = {page.id: page for page in response.context["table"].data}
131
+
132
+ # Child page is a simple page directly underneath root
133
+ # so should appear in the list
134
+ self.assertIn(self.child_page.id, pages)
135
+ self.assertTrue(pages[self.child_page.id].can_choose)
136
+ self.assertFalse(pages[self.child_page.id].can_descend)
137
+
138
+ # Event page is not a simple page and is not descendable either
139
+ # so should not appear in the list
140
+ self.assertNotIn(event_page.id, pages)
141
+
142
+ # Event index page is not a simple page but has a child and is therefore descendable
143
+ # so should appear in the list
144
+ self.assertIn(event_index_page.id, pages)
145
+ self.assertFalse(pages[event_index_page.id].can_choose)
146
+ self.assertTrue(pages[event_index_page.id].can_descend)
147
+
148
+ def test_with_url_extended_page_type(self):
149
+ # Add a page that overrides the url path
150
+ single_event_page = SingleEventPage(
151
+ title="foo",
152
+ location="the moon",
153
+ audience="public",
154
+ cost="free",
155
+ date_from="2001-01-01",
156
+ )
157
+ self.root_page.add_child(instance=single_event_page)
158
+
159
+ # Send request
160
+ response = self.get()
161
+ self.assertEqual(response.status_code, 200)
162
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/browse.html")
163
+
164
+ page_urls = [page.url for page in response.context["table"].data]
165
+
166
+ self.assertIn("/foo/pointless-suffix/", page_urls)
167
+
168
+ def test_with_blank_page_type(self):
169
+ # a blank page_type parameter should be equivalent to an absent parameter
170
+ # (or an explicit page_type of wagtailcore.page)
171
+ response = self.get({"page_type": ""})
172
+ self.assertEqual(response.status_code, 200)
173
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/browse.html")
174
+
175
+ def test_with_multiple_page_types(self):
176
+ # Add a page that is not a SimplePage
177
+ event_page = EventPage(
178
+ title="event",
179
+ location="the moon",
180
+ audience="public",
181
+ cost="free",
182
+ date_from="2001-01-01",
183
+ )
184
+ self.root_page.add_child(instance=event_page)
185
+
186
+ # Send request
187
+ response = self.get({"page_type": "tests.simplepage,tests.eventpage"})
188
+ self.assertEqual(response.status_code, 200)
189
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/browse.html")
190
+ self.assertEqual(
191
+ response.context["page_type_string"], "tests.simplepage,tests.eventpage"
192
+ )
193
+
194
+ pages = {page.id: page for page in response.context["table"].data}
195
+
196
+ # Simple page in results, as before
197
+ self.assertIn(self.child_page.id, pages)
198
+ self.assertTrue(pages[self.child_page.id].can_choose)
199
+
200
+ # Event page should now also be choosable
201
+ self.assertIn(event_page.id, pages)
202
+ self.assertTrue(pages[self.child_page.id].can_choose)
203
+
204
+ def test_with_unknown_page_type(self):
205
+ response = self.get({"page_type": "foo.bar"})
206
+ self.assertEqual(response.status_code, 404)
207
+
208
+ def test_with_bad_page_type(self):
209
+ response = self.get({"page_type": "wagtailcore.site"})
210
+ self.assertEqual(response.status_code, 404)
211
+
212
+ def test_with_invalid_page_type(self):
213
+ response = self.get({"page_type": "foo"})
214
+ self.assertEqual(response.status_code, 404)
215
+
216
+ def test_with_admin_display_title(self):
217
+ # Check the display of the child page title when it's a child
218
+ response = self.get({"page_type": "wagtailcore.Page"})
219
+ self.assertEqual(response.status_code, 200)
220
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/browse.html")
221
+
222
+ html = response.json().get("html")
223
+ self.assertInHTML("foobarbaz (simple page)", html)
224
+
225
+ # The data-title attribute should not use the custom admin display title,
226
+ # because JS code that uses that attribute (e.g. the rich text editor)
227
+ # should use the real page title.
228
+ self.assertIn('data-title="foobarbaz"', html)
229
+
230
+ def test_parent_with_admin_display_title(self):
231
+ # Add another child under child_page so it renders a chooser list
232
+ leaf_page = SimplePage(title="quux", content="goodbye")
233
+ self.child_page.add_child(instance=leaf_page)
234
+
235
+ # Use the child page as the chooser parent
236
+ response = self.client.get(
237
+ reverse("wagtailadmin_choose_page_child", args=(self.child_page.id,)),
238
+ params={"page_type": "wagtailcore.Page"},
239
+ )
240
+ self.assertEqual(response.status_code, 200)
241
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/browse.html")
242
+
243
+ self.assertInHTML("foobarbaz (simple page)", response.json().get("html"))
244
+ self.assertInHTML("quux (simple page)", response.json().get("html"))
245
+
246
+ def test_admin_display_title_breadcrumb(self):
247
+ # Add another child under child_page so we get breadcrumbs
248
+ leaf_page = SimplePage(title="quux", content="goodbye")
249
+ self.child_page.add_child(instance=leaf_page)
250
+
251
+ # Use the leaf page as the chooser parent, so child is in the breadcrumbs
252
+ response = self.client.get(
253
+ reverse("wagtailadmin_choose_page_child", args=(leaf_page.id,))
254
+ )
255
+ self.assertEqual(response.status_code, 200)
256
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/browse.html")
257
+
258
+ # Look for a link element in the breadcrumbs with the admin title
259
+ expected = """
260
+ <li class="w-h-full w-flex w-items-center w-overflow-hidden w-transition w-duration-300 w-whitespace-nowrap w-flex-shrink-0 w-font-bold " data-breadcrumb-item>
261
+ <a class="w-flex w-items-center w-h-full w-text-primary w-pr-0.5 w-text-14 w-no-underline w-outline-offset-inside hover:w-underline hover:w-text-primary w-h-full" href="/admin/choose-page/{page_id}/?">
262
+ {page_title}
263
+ </a>
264
+ <svg class="icon icon-arrow-right w-w-4 w-h-4 w-ml-3" aria-hidden="true">
265
+ <use href="#icon-arrow-right"></use>
266
+ </svg>
267
+ </li>
268
+ """.format(
269
+ page_id=self.child_page.id,
270
+ page_title="foobarbaz (simple page)",
271
+ )
272
+ self.assertTagInHTML(expected, response.json().get("html"))
273
+
274
+ def setup_pagination_test_data(self):
275
+ # Create lots of pages
276
+ for i in range(100):
277
+ new_page = SimplePage(
278
+ title="foobarbaz",
279
+ slug="foobarbaz-%d" % i,
280
+ content="hello",
281
+ )
282
+ self.root_page.add_child(instance=new_page)
283
+
284
+ def test_pagination_basic(self):
285
+ self.setup_pagination_test_data()
286
+
287
+ response = self.get()
288
+ self.assertEqual(response.context["pagination_page"].paginator.num_pages, 5)
289
+ self.assertEqual(response.context["pagination_page"].number, 1)
290
+
291
+ def test_pagination_another_page(self):
292
+ self.setup_pagination_test_data()
293
+
294
+ response = self.get({"p": 2})
295
+ self.assertEqual(response.context["pagination_page"].number, 2)
296
+
297
+ def test_pagination_invalid_page(self):
298
+ self.setup_pagination_test_data()
299
+
300
+ response = self.get({"p": "foo"})
301
+ self.assertEqual(response.context["pagination_page"].number, 1)
302
+
303
+ def test_pagination_out_of_range_page(self):
304
+ self.setup_pagination_test_data()
305
+
306
+ response = self.get({"p": 100})
307
+ self.assertEqual(response.context["pagination_page"].number, 5)
308
+
309
+
310
+ class TestChooserSearch(TestCase, WagtailTestUtils):
311
+ def setUp(self):
312
+ self.root_page = Page.objects.get(id=2)
313
+
314
+ # Add child page
315
+ self.child_page = SimplePage(title="foobarbaz", content="hello")
316
+ self.root_page.add_child(instance=self.child_page)
317
+
318
+ self.login()
319
+
320
+ def get(self, params=None):
321
+ return self.client.get(reverse("wagtailadmin_choose_page_search"), params or {})
322
+
323
+ def test_simple(self):
324
+ response = self.get({"q": "foobarbaz"})
325
+ self.assertEqual(response.status_code, 200)
326
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/_search_results.html")
327
+ self.assertContains(response, "There is 1 match")
328
+ self.assertContains(response, "foobarbaz")
329
+
330
+ def test_result_uses_custom_admin_display_title(self):
331
+ single_event_page = SingleEventPage(
332
+ title="Lunar event",
333
+ location="the moon",
334
+ audience="public",
335
+ cost="free",
336
+ date_from="2001-01-01",
337
+ )
338
+ self.root_page.add_child(instance=single_event_page)
339
+
340
+ response = self.get({"q": "lunar"})
341
+ self.assertEqual(response.status_code, 200)
342
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/_search_results.html")
343
+ self.assertContains(response, "Lunar event (single event)")
344
+
345
+ def test_search_no_results(self):
346
+ response = self.get({"q": "quux"})
347
+ self.assertEqual(response.status_code, 200)
348
+ self.assertContains(response, "There are 0 matches")
349
+
350
+ def test_with_page_type(self):
351
+ # Add a page that is not a SimplePage
352
+ event_page = EventPage(
353
+ title="foo",
354
+ location="the moon",
355
+ audience="public",
356
+ cost="free",
357
+ date_from="2001-01-01",
358
+ )
359
+ self.root_page.add_child(instance=event_page)
360
+
361
+ # Send request
362
+ response = self.get({"q": "foo", "page_type": "tests.simplepage"})
363
+ self.assertEqual(response.status_code, 200)
364
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/_search_results.html")
365
+ self.assertEqual(response.context["page_type_string"], "tests.simplepage")
366
+
367
+ pages = {page.id: page for page in response.context["pages"]}
368
+
369
+ self.assertIn(self.child_page.id, pages)
370
+
371
+ # Not a simple page
372
+ self.assertNotIn(event_page.id, pages)
373
+
374
+ def test_with_blank_page_type(self):
375
+ # a blank page_type parameter should be equivalent to an absent parameter
376
+ # (or an explicit page_type of wagtailcore.page)
377
+ response = self.get({"q": "foobarbaz", "page_type": ""})
378
+ self.assertEqual(response.status_code, 200)
379
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/_search_results.html")
380
+ self.assertContains(response, "There is 1 match")
381
+ self.assertContains(response, "foobarbaz")
382
+
383
+ def test_with_multiple_page_types(self):
384
+ # Add a page that is not a SimplePage
385
+ event_page = EventPage(
386
+ title="foo",
387
+ location="the moon",
388
+ audience="public",
389
+ cost="free",
390
+ date_from="2001-01-01",
391
+ )
392
+ self.root_page.add_child(instance=event_page)
393
+
394
+ # Send request
395
+ response = self.get(
396
+ {"q": "foo", "page_type": "tests.simplepage,tests.eventpage"}
397
+ )
398
+ self.assertEqual(response.status_code, 200)
399
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/_search_results.html")
400
+ self.assertEqual(
401
+ response.context["page_type_string"], "tests.simplepage,tests.eventpage"
402
+ )
403
+
404
+ pages = {page.id: page for page in response.context["pages"]}
405
+
406
+ # Simple page in results, as before
407
+ self.assertIn(self.child_page.id, pages)
408
+
409
+ # Event page should now also be choosable
410
+ self.assertIn(event_page.id, pages)
411
+
412
+ def test_with_unknown_page_type(self):
413
+ response = self.get({"page_type": "foo.bar"})
414
+ self.assertEqual(response.status_code, 404)
415
+
416
+ def test_with_bad_page_type(self):
417
+ response = self.get({"page_type": "wagtailcore.site"})
418
+ self.assertEqual(response.status_code, 404)
419
+
420
+ def test_with_invalid_page_type(self):
421
+ response = self.get({"page_type": "foo"})
422
+ self.assertEqual(response.status_code, 404)
423
+
424
+ def test_construct_queryset_hook(self):
425
+ page = SimplePage(title="Test shown", content="hello")
426
+ self.root_page.add_child(instance=page)
427
+
428
+ page_not_shown = SimplePage(title="Test not shown", content="hello")
429
+ self.root_page.add_child(instance=page_not_shown)
430
+
431
+ def filter_pages(pages, request):
432
+ return pages.filter(id=page.id)
433
+
434
+ with self.register_hook("construct_page_chooser_queryset", filter_pages):
435
+ response = self.get({"q": "Test"})
436
+ self.assertEqual(len(response.context["pages"]), 1)
437
+ self.assertEqual(response.context["pages"][0].specific, page)
438
+
439
+
440
+ class TestAutomaticRootPageDetection(TestCase, WagtailTestUtils):
441
+ def setUp(self):
442
+ self.tree_root = Page.objects.get(id=1)
443
+ self.home_page = Page.objects.get(id=2)
444
+
445
+ self.about_page = self.home_page.add_child(
446
+ instance=SimplePage(title="About", content="About Foo")
447
+ )
448
+ self.contact_page = self.about_page.add_child(
449
+ instance=SimplePage(title="Contact", content="Content Foo")
450
+ )
451
+ self.people_page = self.about_page.add_child(
452
+ instance=SimplePage(title="People", content="The people of Foo")
453
+ )
454
+
455
+ self.event_index = self.make_event_section("Events")
456
+
457
+ self.login()
458
+
459
+ def make_event_section(self, name):
460
+ event_index = self.home_page.add_child(instance=EventIndex(title=name))
461
+ event_index.add_child(
462
+ instance=EventPage(
463
+ title="First Event",
464
+ location="Bar",
465
+ audience="public",
466
+ cost="free",
467
+ date_from="2001-01-01",
468
+ )
469
+ )
470
+ event_index.add_child(
471
+ instance=EventPage(
472
+ title="Second Event",
473
+ location="Baz",
474
+ audience="public",
475
+ cost="free",
476
+ date_from="2001-01-01",
477
+ )
478
+ )
479
+ return event_index
480
+
481
+ def get_best_root(self, params={}):
482
+ response = self.client.get(reverse("wagtailadmin_choose_page"), params)
483
+ return response.context["parent_page"].specific
484
+
485
+ def test_no_type_filter(self):
486
+ self.assertEqual(self.get_best_root(), self.tree_root)
487
+
488
+ def test_type_page(self):
489
+ self.assertEqual(
490
+ self.get_best_root({"page_type": "wagtailcore.Page"}), self.tree_root
491
+ )
492
+
493
+ def test_type_eventpage(self):
494
+ """
495
+ The chooser should start at the EventIndex that holds all the
496
+ EventPages.
497
+ """
498
+ self.assertEqual(
499
+ self.get_best_root({"page_type": "tests.EventPage"}), self.event_index
500
+ )
501
+
502
+ def test_type_eventpage_two_indexes(self):
503
+ """
504
+ The chooser should start at the home page, as there are two
505
+ EventIndexes with EventPages.
506
+ """
507
+ self.make_event_section("Other events")
508
+ self.assertEqual(
509
+ self.get_best_root({"page_type": "tests.EventPage"}), self.home_page
510
+ )
511
+
512
+ def test_type_simple_page(self):
513
+ """
514
+ The chooser should start at the home page, as all SimplePages are
515
+ directly under it
516
+ """
517
+ self.assertEqual(
518
+ self.get_best_root({"page_type": "tests.BusinessIndex"}), self.tree_root
519
+ )
520
+
521
+ def test_type_missing(self):
522
+ """
523
+ The chooser should start at the root, as there are no BusinessIndexes
524
+ """
525
+ self.assertEqual(
526
+ self.get_best_root({"page_type": "tests.BusinessIndex"}), self.tree_root
527
+ )
528
+
529
+
530
+ class TestChooserExternalLink(TestCase, WagtailTestUtils):
531
+ def setUp(self):
532
+ self.login()
533
+ self.internal_page = SimplePage(title="About", content="About Foo")
534
+ Page.objects.get(pk=2).add_child(instance=self.internal_page)
535
+
536
+ def get(self, params={}):
537
+ return self.client.get(
538
+ reverse("wagtailadmin_choose_page_external_link"), params
539
+ )
540
+
541
+ def post(self, post_data={}, url_params={}):
542
+ url = reverse("wagtailadmin_choose_page_external_link")
543
+ if url_params:
544
+ url += "?" + urlencode(url_params)
545
+ return self.client.post(url, post_data)
546
+
547
+ def test_simple(self):
548
+ response = self.get()
549
+ self.assertEqual(response.status_code, 200)
550
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/external_link.html")
551
+
552
+ def test_prepopulated_form(self):
553
+ response = self.get(
554
+ {"link_text": "Torchbox", "link_url": "https://torchbox.com/"}
555
+ )
556
+ self.assertEqual(response.status_code, 200)
557
+ self.assertContains(response, "Torchbox")
558
+ self.assertContains(response, "https://torchbox.com/")
559
+
560
+ def test_create_link(self):
561
+ response = self.post(
562
+ {
563
+ "external-link-chooser-url": "http://www.example.com/",
564
+ "external-link-chooser-link_text": "example",
565
+ }
566
+ )
567
+ self.assertEqual(response.status_code, 200)
568
+ response_json = json.loads(response.content.decode())
569
+ self.assertEqual(response_json["step"], "external_link_chosen")
570
+ self.assertEqual(response_json["result"]["url"], "http://www.example.com/")
571
+ self.assertEqual(
572
+ response_json["result"]["title"], "example"
573
+ ) # When link text is given, it is used
574
+ self.assertIs(response_json["result"]["prefer_this_title_as_link_text"], True)
575
+
576
+ def test_create_link_without_text(self):
577
+ response = self.post({"external-link-chooser-url": "http://www.example.com/"})
578
+ self.assertEqual(response.status_code, 200)
579
+ response_json = json.loads(response.content.decode())
580
+ self.assertEqual(response_json["step"], "external_link_chosen")
581
+ self.assertEqual(response_json["result"]["url"], "http://www.example.com/")
582
+ self.assertEqual(
583
+ response_json["result"]["title"], "http://www.example.com/"
584
+ ) # When no text is given, it uses the url
585
+ self.assertIs(response_json["result"]["prefer_this_title_as_link_text"], False)
586
+
587
+ def test_notice_changes_to_link_text(self):
588
+ response = self.post(
589
+ {
590
+ "external-link-chooser-url": "http://www.example.com/",
591
+ "external-link-chooser-link_text": "example",
592
+ }, # POST data
593
+ {
594
+ "link_url": "http://old.example.com/",
595
+ "link_text": "example",
596
+ }, # GET params - initial data
597
+ )
598
+ result = json.loads(response.content.decode())["result"]
599
+ self.assertEqual(result["url"], "http://www.example.com/")
600
+ self.assertEqual(result["title"], "example")
601
+ # no change to link text, so prefer the existing link/selection content where available
602
+ self.assertIs(result["prefer_this_title_as_link_text"], False)
603
+
604
+ response = self.post(
605
+ {
606
+ "external-link-chooser-url": "http://www.example.com/",
607
+ "external-link-chooser-link_text": "new example",
608
+ }, # POST data
609
+ {
610
+ "link_url": "http://old.example.com/",
611
+ "link_text": "example",
612
+ }, # GET params - initial data
613
+ )
614
+ result = json.loads(response.content.decode())["result"]
615
+ self.assertEqual(result["url"], "http://www.example.com/")
616
+ self.assertEqual(result["title"], "new example")
617
+ # link text has changed, so tell the caller to use it
618
+ self.assertIs(result["prefer_this_title_as_link_text"], True)
619
+
620
+ def test_invalid_url(self):
621
+ response = self.post(
622
+ {
623
+ "external-link-chooser-url": "ntp://www.example.com",
624
+ "external-link-chooser-link_text": "example",
625
+ }
626
+ )
627
+ self.assertEqual(response.status_code, 200)
628
+ response_json = json.loads(response.content.decode())
629
+ self.assertEqual(
630
+ response_json["step"], "external_link"
631
+ ) # indicates failure / show error message
632
+ self.assertContains(response, "Enter a valid URL.")
633
+
634
+ def test_allow_local_url(self):
635
+ response = self.post(
636
+ {
637
+ "external-link-chooser-url": "/admin/",
638
+ "external-link-chooser-link_text": "admin",
639
+ }
640
+ )
641
+ self.assertEqual(response.status_code, 200)
642
+ response_json = json.loads(response.content.decode())
643
+ self.assertEqual(
644
+ response_json["step"], "external_link_chosen"
645
+ ) # indicates success / post back to calling page
646
+ self.assertEqual(response_json["result"]["url"], "/admin/")
647
+ self.assertEqual(response_json["result"]["title"], "admin")
648
+
649
+ def test_convert_external_to_internal_link(self):
650
+ response = self.post(
651
+ {
652
+ "external-link-chooser-url": "http://localhost/about/",
653
+ "external-link-chooser-link_text": "about",
654
+ }
655
+ )
656
+ self.assertEqual(response.status_code, 200)
657
+ response_json = json.loads(response.content.decode())
658
+ self.assertEqual(response_json["step"], "external_link_chosen")
659
+ self.assertEqual(response_json["result"]["url"], "/about/")
660
+ self.assertEqual(response_json["result"]["id"], self.internal_page.pk)
661
+
662
+ def test_convert_external_link_with_query_parameters_to_internal_link(self):
663
+ response = self.post(
664
+ {
665
+ "external-link-chooser-url": "http://localhost/about?test=1",
666
+ "external-link-chooser-link_text": "about",
667
+ }
668
+ )
669
+ self.assertEqual(response.status_code, 200)
670
+ response_json = json.loads(response.content.decode())
671
+
672
+ # Query parameters will get stripped, so the user should get asked to confirm the conversion
673
+ self.assertEqual(response_json["step"], "confirm_external_to_internal")
674
+
675
+ self.assertEqual(
676
+ response_json["external"]["url"], "http://localhost/about?test=1"
677
+ )
678
+ self.assertEqual(response_json["internal"]["id"], self.internal_page.pk)
679
+
680
+ def test_convert_relative_external_link_to_internal_link(self):
681
+ response = self.post(
682
+ {
683
+ "external-link-chooser-url": "/about/",
684
+ "external-link-chooser-link_text": "about",
685
+ }
686
+ )
687
+ self.assertEqual(response.status_code, 200)
688
+ response_json = json.loads(response.content.decode())
689
+ self.assertEqual(response_json["step"], "external_link_chosen")
690
+ self.assertEqual(response_json["result"]["url"], "/about/")
691
+ self.assertEqual(response_json["result"]["id"], self.internal_page.pk)
692
+
693
+ @override_settings(WAGTAILADMIN_EXTERNAL_LINK_CONVERSION="")
694
+ def test_no_conversion_external_to_internal_link_when_disabled(self):
695
+ url = "http://localhost/about/"
696
+ title = "about"
697
+ response = self.post(
698
+ {"external-link-chooser-url": url, "external-link-chooser-link_text": title}
699
+ )
700
+ self.assertEqual(response.status_code, 200)
701
+ response_json = json.loads(response.content.decode())
702
+ self.assertEqual(response_json["step"], "external_link_chosen")
703
+
704
+ self.assertEqual(response_json["result"]["url"], url)
705
+ self.assertEqual(response_json["result"]["title"], title)
706
+
707
+ @override_settings(WAGTAILADMIN_EXTERNAL_LINK_CONVERSION="exact")
708
+ def test_no_confirm_external_to_internal_link_when_exact(self):
709
+ url = "http://localhost/about?test=1"
710
+ title = "about"
711
+ response = self.post(
712
+ {"external-link-chooser-url": url, "external-link-chooser-link_text": title}
713
+ )
714
+ self.assertEqual(response.status_code, 200)
715
+ response_json = json.loads(response.content.decode())
716
+ # Query parameters will get stripped, so this link should be left as an external url with the 'exact' setting
717
+ self.assertEqual(response_json["step"], "external_link_chosen")
718
+
719
+ self.assertEqual(response_json["result"]["url"], url)
720
+ self.assertEqual(response_json["result"]["title"], title)
721
+
722
+ @override_settings(WAGTAILADMIN_EXTERNAL_LINK_CONVERSION="confirm")
723
+ def test_convert_external_link_to_internal_link_with_confirm_setting(self):
724
+ url = "http://localhost/about/"
725
+ response = self.post(
726
+ {
727
+ "external-link-chooser-url": url,
728
+ "external-link-chooser-link_text": "about",
729
+ }
730
+ )
731
+ self.assertEqual(response.status_code, 200)
732
+ response_json = json.loads(response.content.decode())
733
+
734
+ # The url is identical, but the conversion setting is set to 'confirm'
735
+ # so the user should get asked to confirm the conversion
736
+ self.assertEqual(response_json["step"], "confirm_external_to_internal")
737
+
738
+ self.assertEqual(response_json["external"]["url"], url)
739
+ self.assertEqual(response_json["internal"]["id"], self.internal_page.pk)
740
+
741
+
742
+ class TestChooserAnchorLink(TestCase, WagtailTestUtils):
743
+ def setUp(self):
744
+ self.login()
745
+
746
+ def get(self, params={}):
747
+ return self.client.get(reverse("wagtailadmin_choose_page_anchor_link"), params)
748
+
749
+ def post(self, post_data={}, url_params={}):
750
+ url = reverse("wagtailadmin_choose_page_anchor_link")
751
+ if url_params:
752
+ url += "?" + urlencode(url_params)
753
+ return self.client.post(url, post_data)
754
+
755
+ def test_simple(self):
756
+ response = self.get()
757
+ self.assertEqual(response.status_code, 200)
758
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/anchor_link.html")
759
+
760
+ def test_prepopulated_form(self):
761
+ response = self.get(
762
+ {"link_text": "Example Anchor Text", "link_url": "exampleanchor"}
763
+ )
764
+ self.assertEqual(response.status_code, 200)
765
+ self.assertContains(response, "Example Anchor Text")
766
+ self.assertContains(response, "exampleanchor")
767
+
768
+ def test_create_link(self):
769
+ response = self.post(
770
+ {
771
+ "anchor-link-chooser-url": "exampleanchor",
772
+ "anchor-link-chooser-link_text": "Example Anchor Text",
773
+ }
774
+ )
775
+ result = json.loads(response.content.decode())["result"]
776
+ self.assertEqual(result["url"], "#exampleanchor")
777
+ self.assertEqual(
778
+ result["title"], "Example Anchor Text"
779
+ ) # When link text is given, it is used
780
+ self.assertIs(result["prefer_this_title_as_link_text"], True)
781
+
782
+ def test_create_link_without_text(self):
783
+ response = self.post({"anchor-link-chooser-url": "exampleanchor"})
784
+ result = json.loads(response.content.decode())["result"]
785
+ self.assertEqual(result["url"], "#exampleanchor")
786
+ self.assertEqual(
787
+ result["title"], "exampleanchor"
788
+ ) # When no link text is given, it uses anchor
789
+ self.assertIs(result["prefer_this_title_as_link_text"], False)
790
+
791
+ def test_notice_changes_to_link_text(self):
792
+ response = self.post(
793
+ {
794
+ "anchor-link-chooser-url": "exampleanchor2",
795
+ "email-link-chooser-link_text": "Example Text",
796
+ }, # POST data
797
+ {
798
+ "link_url": "exampleanchor2",
799
+ "link_text": "Example Text",
800
+ }, # GET params - initial data
801
+ )
802
+ result = json.loads(response.content.decode())["result"]
803
+ self.assertEqual(result["url"], "#exampleanchor2")
804
+ self.assertEqual(result["title"], "exampleanchor2")
805
+ # no change to link text, so prefer the existing link/selection content where available
806
+ self.assertIs(result["prefer_this_title_as_link_text"], True)
807
+
808
+ response = self.post(
809
+ {
810
+ "anchor-link-chooser-url": "exampleanchor2",
811
+ "anchor-link-chooser-link_text": "Example Anchor Test 2.1",
812
+ }, # POST data
813
+ {
814
+ "link_url": "exampleanchor",
815
+ "link_text": "Example Anchor Text",
816
+ }, # GET params - initial data
817
+ )
818
+ result = json.loads(response.content.decode())["result"]
819
+ self.assertEqual(result["url"], "#exampleanchor2")
820
+ self.assertEqual(result["title"], "Example Anchor Test 2.1")
821
+ # link text has changed, so tell the caller to use it
822
+ self.assertIs(result["prefer_this_title_as_link_text"], True)
823
+
824
+
825
+ class TestChooserEmailLink(TestCase, WagtailTestUtils):
826
+ def setUp(self):
827
+ self.login()
828
+
829
+ def get(self, params={}):
830
+ return self.client.get(reverse("wagtailadmin_choose_page_email_link"), params)
831
+
832
+ def post(self, post_data={}, url_params={}):
833
+ url = reverse("wagtailadmin_choose_page_email_link")
834
+ if url_params:
835
+ url += "?" + urlencode(url_params)
836
+ return self.client.post(url, post_data)
837
+
838
+ def test_simple(self):
839
+ response = self.get()
840
+ self.assertEqual(response.status_code, 200)
841
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/email_link.html")
842
+
843
+ def test_prepopulated_form(self):
844
+ response = self.get({"link_text": "Example", "link_url": "example@example.com"})
845
+ self.assertEqual(response.status_code, 200)
846
+ self.assertContains(response, "Example")
847
+ self.assertContains(response, "example@example.com")
848
+
849
+ def test_create_link(self):
850
+ response = self.post(
851
+ {
852
+ "email-link-chooser-email_address": "example@example.com",
853
+ "email-link-chooser-link_text": "contact",
854
+ }
855
+ )
856
+ result = json.loads(response.content.decode())["result"]
857
+ self.assertEqual(result["url"], "mailto:example@example.com")
858
+ self.assertEqual(
859
+ result["title"], "contact"
860
+ ) # When link text is given, it is used
861
+ self.assertIs(result["prefer_this_title_as_link_text"], True)
862
+
863
+ def test_create_link_without_text(self):
864
+ response = self.post(
865
+ {"email-link-chooser-email_address": "example@example.com"}
866
+ )
867
+ result = json.loads(response.content.decode())["result"]
868
+ self.assertEqual(result["url"], "mailto:example@example.com")
869
+ self.assertEqual(
870
+ result["title"], "example@example.com"
871
+ ) # When no link text is given, it uses the email
872
+ self.assertIs(result["prefer_this_title_as_link_text"], False)
873
+
874
+ def test_notice_changes_to_link_text(self):
875
+ response = self.post(
876
+ {
877
+ "email-link-chooser-email_address": "example2@example.com",
878
+ "email-link-chooser-link_text": "example",
879
+ }, # POST data
880
+ {
881
+ "link_url": "example@example.com",
882
+ "link_text": "example",
883
+ }, # GET params - initial data
884
+ )
885
+ result = json.loads(response.content.decode())["result"]
886
+ self.assertEqual(result["url"], "mailto:example2@example.com")
887
+ self.assertEqual(result["title"], "example")
888
+ # no change to link text, so prefer the existing link/selection content where available
889
+ self.assertIs(result["prefer_this_title_as_link_text"], False)
890
+
891
+ response = self.post(
892
+ {
893
+ "email-link-chooser-email_address": "example2@example.com",
894
+ "email-link-chooser-link_text": "new example",
895
+ }, # POST data
896
+ {
897
+ "link_url": "example@example.com",
898
+ "link_text": "example",
899
+ }, # GET params - initial data
900
+ )
901
+ result = json.loads(response.content.decode())["result"]
902
+ self.assertEqual(result["url"], "mailto:example2@example.com")
903
+ self.assertEqual(result["title"], "new example")
904
+ # link text has changed, so tell the caller to use it
905
+ self.assertIs(result["prefer_this_title_as_link_text"], True)
906
+
907
+
908
+ class TestChooserPhoneLink(TestCase, WagtailTestUtils):
909
+ def setUp(self):
910
+ self.login()
911
+
912
+ def get(self, params={}):
913
+ return self.client.get(reverse("wagtailadmin_choose_page_phone_link"), params)
914
+
915
+ def post(self, post_data={}, url_params={}):
916
+ url = reverse("wagtailadmin_choose_page_phone_link")
917
+ if url_params:
918
+ url += "?" + urlencode(url_params)
919
+ return self.client.post(url, post_data)
920
+
921
+ def test_simple(self):
922
+ response = self.get()
923
+ self.assertEqual(response.status_code, 200)
924
+ self.assertTemplateUsed(response, "wagtailadmin/chooser/phone_link.html")
925
+
926
+ def test_prepopulated_form(self):
927
+ response = self.get({"link_text": "Example", "link_url": "+123456789"})
928
+ self.assertEqual(response.status_code, 200)
929
+ self.assertContains(response, "Example")
930
+ self.assertContains(response, "+123456789")
931
+
932
+ def test_create_link(self):
933
+ response = self.post(
934
+ {
935
+ "phone-link-chooser-phone_number": "+123456789",
936
+ "phone-link-chooser-link_text": "call",
937
+ }
938
+ )
939
+ result = json.loads(response.content.decode())["result"]
940
+ self.assertEqual(result["url"], "tel:+123456789")
941
+ self.assertEqual(result["title"], "call")
942
+ self.assertIs(result["prefer_this_title_as_link_text"], True)
943
+
944
+ def test_create_link_without_text(self):
945
+ response = self.post({"phone-link-chooser-phone_number": "+123456789"})
946
+ result = json.loads(response.content.decode())["result"]
947
+ self.assertEqual(result["url"], "tel:+123456789")
948
+ self.assertEqual(
949
+ result["title"], "+123456789"
950
+ ) # When no link text is given, it uses the phone number
951
+ self.assertIs(result["prefer_this_title_as_link_text"], False)
952
+
953
+ def test_notice_changes_to_link_text(self):
954
+ response = self.post(
955
+ {
956
+ "phone-link-chooser-phone_number": "+222222222",
957
+ "phone-link-chooser-link_text": "example",
958
+ }, # POST data
959
+ {
960
+ "link_url": "+111111111",
961
+ "link_text": "example",
962
+ }, # GET params - initial data
963
+ )
964
+ result = json.loads(response.content.decode())["result"]
965
+ self.assertEqual(result["url"], "tel:+222222222")
966
+ self.assertEqual(result["title"], "example")
967
+ # no change to link text, so prefer the existing link/selection content where available
968
+ self.assertIs(result["prefer_this_title_as_link_text"], False)
969
+
970
+ response = self.post(
971
+ {
972
+ "phone-link-chooser-phone_number": "+222222222",
973
+ "phone-link-chooser-link_text": "new example",
974
+ }, # POST data
975
+ {
976
+ "link_url": "+111111111",
977
+ "link_text": "example",
978
+ }, # GET params - initial data
979
+ )
980
+ result = json.loads(response.content.decode())["result"]
981
+ self.assertEqual(result["url"], "tel:+222222222")
982
+ self.assertEqual(result["title"], "new example")
983
+ # link text has changed, so tell the caller to use it
984
+ self.assertIs(result["prefer_this_title_as_link_text"], True)
985
+
986
+
987
+ class TestCanChoosePage(TestCase, WagtailTestUtils):
988
+ fixtures = ["test.json"]
989
+
990
+ def setUp(self):
991
+ self.user = self.login()
992
+ self.permission_proxy = UserPagePermissionsProxy(self.user)
993
+ self.desired_classes = (Page,)
994
+
995
+ def test_can_choose_page(self):
996
+ homepage = Page.objects.get(url_path="/home/")
997
+ result = can_choose_page(homepage, self.permission_proxy, self.desired_classes)
998
+ self.assertTrue(result)
999
+
1000
+ def test_with_user_no_permission(self):
1001
+ homepage = Page.objects.get(url_path="/home/")
1002
+ # event editor does not have permissions on homepage
1003
+ event_editor = get_user_model().objects.get(email="eventeditor@example.com")
1004
+ permission_proxy = UserPagePermissionsProxy(event_editor)
1005
+ result = can_choose_page(
1006
+ homepage, permission_proxy, self.desired_classes, user_perm="copy_to"
1007
+ )
1008
+ self.assertFalse(result)
1009
+
1010
+ def test_with_can_choose_root(self):
1011
+ root = Page.objects.get(url_path="/")
1012
+ result = can_choose_page(
1013
+ root, self.permission_proxy, self.desired_classes, can_choose_root=True
1014
+ )
1015
+ self.assertTrue(result)
1016
+
1017
+ def test_with_can_not_choose_root(self):
1018
+ root = Page.objects.get(url_path="/")
1019
+ result = can_choose_page(
1020
+ root, self.permission_proxy, self.desired_classes, can_choose_root=False
1021
+ )
1022
+ self.assertFalse(result)
1023
+
1024
+ def test_move_to_same_page(self):
1025
+ homepage = Page.objects.get(url_path="/home/")
1026
+ result = can_choose_page(
1027
+ homepage,
1028
+ self.permission_proxy,
1029
+ self.desired_classes,
1030
+ user_perm="move_to",
1031
+ target_pages=[homepage],
1032
+ )
1033
+ self.assertFalse(result)
1034
+
1035
+ def test_move_to_root(self):
1036
+ homepage = Page.objects.get(url_path="/home/")
1037
+ root = Page.objects.get(url_path="/")
1038
+ result = can_choose_page(
1039
+ root,
1040
+ self.permission_proxy,
1041
+ self.desired_classes,
1042
+ user_perm="move_to",
1043
+ target_pages=[homepage],
1044
+ )
1045
+ self.assertTrue(result)
1046
+
1047
+ def test_move_to_page_with_wrong_parent_types(self):
1048
+ board_meetings = Page.objects.get(
1049
+ url_path="/home/events/businessy-events/board-meetings/"
1050
+ )
1051
+ homepage = Page.objects.get(url_path="/home/")
1052
+ result = can_choose_page(
1053
+ homepage,
1054
+ self.permission_proxy,
1055
+ self.desired_classes,
1056
+ user_perm="move_to",
1057
+ target_pages=[board_meetings],
1058
+ )
1059
+ self.assertFalse(result)
1060
+
1061
+ def test_move_to_same_page_bulk(self):
1062
+ homepage = Page.objects.get(url_path="/home/")
1063
+ secret_plans = Page.objects.get(url_path="/home/secret-plans/")
1064
+ result = can_choose_page(
1065
+ homepage,
1066
+ self.permission_proxy,
1067
+ self.desired_classes,
1068
+ user_perm="bulk_move_to",
1069
+ target_pages=[homepage, secret_plans],
1070
+ )
1071
+ self.assertFalse(result)
1072
+
1073
+ def test_move_to_root_bulk(self):
1074
+ homepage = Page.objects.get(url_path="/home/")
1075
+ secret_plans = Page.objects.get(url_path="/home/secret-plans/")
1076
+ root = Page.objects.get(url_path="/")
1077
+ result = can_choose_page(
1078
+ root,
1079
+ self.permission_proxy,
1080
+ self.desired_classes,
1081
+ user_perm="bulk_move_to",
1082
+ target_pages=[homepage, secret_plans],
1083
+ )
1084
+ self.assertTrue(result)
1085
+
1086
+ def test_move_to_page_with_wrong_parent_types_bulk(self):
1087
+ board_meetings = Page.objects.get(
1088
+ url_path="/home/events/businessy-events/board-meetings/"
1089
+ )
1090
+ steal_underpants = Page.objects.get(
1091
+ url_path="/home/secret-plans/steal-underpants/"
1092
+ )
1093
+ homepage = Page.objects.get(url_path="/home/")
1094
+ result = can_choose_page(
1095
+ homepage,
1096
+ self.permission_proxy,
1097
+ self.desired_classes,
1098
+ user_perm="bulk_move_to",
1099
+ target_pages=[board_meetings, steal_underpants],
1100
+ )
1101
+ self.assertTrue(result)
1102
+
1103
+
1104
+ @override_settings(WAGTAIL_I18N_ENABLED=True)
1105
+ class TestPageChooserLocaleSelector(TestCase, WagtailTestUtils):
1106
+ fixtures = ["test.json"]
1107
+
1108
+ LOCALE_SELECTOR_HTML = '<a href="javascript:void(0)" aria-label="English" class="c-dropdown__button u-btn-current w-no-underline">'
1109
+ LOCALE_INDICATOR_HTML = '<use href="#icon-site"></use></svg>\n English'
1110
+
1111
+ def setUp(self):
1112
+ self.root_page = Page.objects.get(id=2)
1113
+
1114
+ # Add child page
1115
+ self.child_page = SimplePage(title="foobarbaz", content="hello")
1116
+ self.root_page.add_child(instance=self.child_page)
1117
+
1118
+ self.fr_locale = Locale.objects.create(language_code="fr")
1119
+ self.root_page_fr = self.root_page.copy_for_translation(self.fr_locale)
1120
+ self.root_page_fr.title = "Bienvenue"
1121
+ self.root_page_fr.save()
1122
+ self.child_page_fr = self.child_page.copy_for_translation(self.fr_locale)
1123
+ self.child_page_fr.save()
1124
+
1125
+ switch_to_french_url = self.get_choose_page_url(
1126
+ self.fr_locale, parent_page_id=self.child_page_fr.pk
1127
+ )
1128
+ self.LOCALE_SELECTOR_HTML_FR = f'<a href="{switch_to_french_url}" aria-label="French" class="u-link is-live w-no-underline">'
1129
+
1130
+ self.login()
1131
+
1132
+ def get(self, parent_page_id):
1133
+ return self.client.get(
1134
+ reverse("wagtailadmin_choose_page_child", args=[parent_page_id])
1135
+ )
1136
+
1137
+ def get_choose_page_url(self, locale=None, parent_page_id=None, html=True):
1138
+ if parent_page_id is not None:
1139
+ url = reverse("wagtailadmin_choose_page_child", args=[parent_page_id])
1140
+ else:
1141
+ url = reverse("wagtailadmin_choose_page")
1142
+
1143
+ suffix = ""
1144
+ if parent_page_id is None:
1145
+ # the locale param should only be appended at the root level
1146
+ if locale is None:
1147
+ locale = self.fr_locale
1148
+ separator = "&amp;" if html else "&"
1149
+ suffix = f"{separator}locale={locale.language_code}"
1150
+ return f"{url}?page_type=wagtailcore.page{suffix}"
1151
+
1152
+ def test_locale_selector_present_in_root_view(self):
1153
+ response = self.client.get(reverse("wagtailadmin_choose_page"))
1154
+ html = response.json().get("html")
1155
+
1156
+ self.assertIn(self.LOCALE_SELECTOR_HTML, html)
1157
+
1158
+ switch_to_french_url = self.get_choose_page_url(locale=self.fr_locale)
1159
+ fr_selector = f'<a href="{switch_to_french_url}" aria-label="French" class="u-link is-live w-no-underline">'
1160
+ self.assertIn(fr_selector, html)
1161
+
1162
+ def test_locale_selector(self):
1163
+ response = self.get(self.child_page.pk)
1164
+
1165
+ html = response.json().get("html")
1166
+ self.assertIn(self.LOCALE_SELECTOR_HTML, html)
1167
+ self.assertIn(self.LOCALE_SELECTOR_HTML_FR, html)
1168
+
1169
+ def test_locale_selector_without_translation(self):
1170
+ self.child_page_fr.delete()
1171
+
1172
+ response = self.get(self.child_page.pk)
1173
+ html = response.json().get("html")
1174
+ self.assertNotIn(self.LOCALE_SELECTOR_HTML, html)
1175
+ self.assertNotIn(self.LOCALE_SELECTOR_HTML_FR, html)
1176
+
1177
+ def test_locale_selector_with_active_locale(self):
1178
+ switch_to_french_url = self.get_choose_page_url(
1179
+ locale=self.fr_locale, html=False
1180
+ )
1181
+ response = self.client.get(switch_to_french_url)
1182
+ html = response.json().get("html")
1183
+
1184
+ self.assertNotIn(self.LOCALE_SELECTOR_HTML, html)
1185
+ self.assertNotIn(f'data-title="{self.root_page.title}"', html)
1186
+ self.assertIn(self.root_page_fr.title, html)
1187
+ self.assertIn(
1188
+ '<a href="javascript:void(0)" aria-label="French" class="c-dropdown__button u-btn-current w-no-underline">',
1189
+ html,
1190
+ )
1191
+ switch_to_english_url = self.get_choose_page_url(
1192
+ locale=Locale.objects.get(language_code="en")
1193
+ )
1194
+ self.assertIn(
1195
+ f'<a href="{switch_to_english_url}" aria-label="English" class="u-link is-live w-no-underline">',
1196
+ html,
1197
+ )
1198
+
1199
+ @override_settings(WAGTAIL_I18N_ENABLED=False)
1200
+ def test_locale_selector_not_present_when_i18n_disabled(self):
1201
+ response = self.get(self.child_page.pk)
1202
+ html = response.json().get("html")
1203
+ self.assertNotIn(self.LOCALE_SELECTOR_HTML, html)
1204
+ self.assertNotIn(self.LOCALE_SELECTOR_HTML_FR, html)
testbed/wagtail__wagtail/wagtail/admin/tests/test_password_reset.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from django.conf import settings
4
+ from django.core import mail
5
+ from django.test import TestCase, override_settings
6
+ from django.urls import reverse
7
+
8
+ from wagtail.test.utils import WagtailTestUtils
9
+
10
+
11
+ class TestUserPasswordReset(TestCase, WagtailTestUtils):
12
+ fixtures = ["test.json"]
13
+
14
+ # need to clear urlresolver caches before/after tests, because we override ROOT_URLCONF
15
+ # in some tests here
16
+ def setUp(self):
17
+ from django.urls import clear_url_caches
18
+
19
+ clear_url_caches()
20
+
21
+ def tearDown(self):
22
+ from django.urls import clear_url_caches
23
+
24
+ clear_url_caches()
25
+
26
+ def test_login_has_password_reset_option(self):
27
+ response = self.client.get(reverse("wagtailadmin_login"))
28
+ self.assertEqual(response.status_code, 200)
29
+ self.assertContains(response, "Forgotten password?")
30
+
31
+ @override_settings(WAGTAIL_PASSWORD_RESET_ENABLED=False)
32
+ def test_login_has_no_password_reset_option_when_disabled(self):
33
+ response = self.client.get(reverse("wagtailadmin_login"))
34
+ self.assertEqual(response.status_code, 200)
35
+ self.assertNotContains(response, "Forgotten password?")
36
+
37
+ @override_settings(WAGTAIL_PASSWORD_RESET_ENABLED=False)
38
+ def test_password_reset_view_disabled(self):
39
+ """
40
+ This tests that the password reset view responds with a 404
41
+ when setting WAGTAIL_PASSWORD_RESET_ENABLED is False
42
+ """
43
+ # Get password reset page
44
+ response = self.client.get(reverse("wagtailadmin_password_reset"))
45
+
46
+ # Check that the user received a 404
47
+ self.assertEqual(response.status_code, 404)
48
+
49
+ @override_settings(ROOT_URLCONF="wagtail.admin.urls")
50
+ def test_email_found_default_url(self):
51
+ response = self.client.post(
52
+ reverse("wagtailadmin_password_reset"), {"email": "siteeditor@example.com"}
53
+ )
54
+ self.assertEqual(response.status_code, 302)
55
+ self.assertEqual(len(mail.outbox), 1)
56
+ self.assertIn("testserver", mail.outbox[0].body)
57
+
58
+ @override_settings(
59
+ ROOT_URLCONF="wagtail.admin.urls", WAGTAILADMIN_BASE_URL="http://mysite.com"
60
+ )
61
+ def test_email_found_base_url(self):
62
+ response = self.client.post(
63
+ reverse("wagtailadmin_password_reset"), {"email": "siteeditor@example.com"}
64
+ )
65
+ self.assertEqual(response.status_code, 302)
66
+ self.assertEqual(len(mail.outbox), 1)
67
+ self.assertIn("mysite.com", mail.outbox[0].body)
68
+
69
+ @override_settings(ROOT_URLCONF="wagtail.admin.urls", WAGTAILADMIN_BASE_URL=None)
70
+ def test_email_without_base_url(self):
71
+ response = self.client.post(
72
+ reverse("wagtailadmin_password_reset"), {"email": "siteeditor@example.com"}
73
+ )
74
+ self.assertEqual(response.status_code, 302)
75
+ self.assertEqual(len(mail.outbox), 1)
76
+
77
+ @unittest.skipUnless(
78
+ settings.AUTH_USER_MODEL == "customuser.CustomUser",
79
+ "only applicable to CustomUser",
80
+ )
81
+ def test_password_reset_email_contains_username(self):
82
+ self.client.post(
83
+ reverse("wagtailadmin_password_reset"), {"email": "siteeditor@example.com"}
84
+ )
85
+ self.assertEqual(len(mail.outbox), 1)
86
+ self.assertIn(
87
+ "Your username (in case you've forgotten): siteeditor", mail.outbox[0].body
88
+ )
89
+
90
+ @unittest.skipUnless(
91
+ settings.AUTH_USER_MODEL == "emailuser.EmailUser",
92
+ "only applicable to EmailUser",
93
+ )
94
+ def test_password_reset_no_username_when_email_is_username(self):
95
+ # When the user model is using email as the username, the password reset email
96
+ # should not contain "Your username (in case you've forgotten)..."
97
+ self.client.post(
98
+ reverse("wagtailadmin_password_reset"), {"email": "siteeditor@example.com"}
99
+ )
100
+ self.assertEqual(len(mail.outbox), 1)
101
+ self.assertNotIn(
102
+ "Your username (in case you've forgotten)", mail.outbox[0].body
103
+ )
testbed/wagtail__wagtail/wagtail/admin/tests/test_privacy.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.contrib.auth.models import Group
2
+ from django.test import TestCase
3
+ from django.urls import reverse
4
+
5
+ from wagtail.models import Page, PageViewRestriction
6
+ from wagtail.test.testapp.models import SimplePage
7
+ from wagtail.test.utils import WagtailTestUtils
8
+
9
+
10
+ class TestSetPrivacyView(TestCase, WagtailTestUtils):
11
+ def setUp(self):
12
+ self.login()
13
+
14
+ # Create some pages
15
+ self.homepage = Page.objects.get(id=2)
16
+
17
+ self.public_page = self.homepage.add_child(
18
+ instance=SimplePage(
19
+ title="Public page",
20
+ content="hello",
21
+ live=True,
22
+ )
23
+ )
24
+
25
+ self.private_page = self.homepage.add_child(
26
+ instance=SimplePage(
27
+ title="Private page",
28
+ content="hello",
29
+ live=True,
30
+ )
31
+ )
32
+ PageViewRestriction.objects.create(
33
+ page=self.private_page, restriction_type="password", password="password123"
34
+ )
35
+
36
+ self.private_child_page = self.private_page.add_child(
37
+ instance=SimplePage(
38
+ title="Private child page",
39
+ content="hello",
40
+ live=True,
41
+ )
42
+ )
43
+
44
+ self.private_groups_page = self.homepage.add_child(
45
+ instance=SimplePage(
46
+ title="Private groups page",
47
+ content="hello",
48
+ live=True,
49
+ )
50
+ )
51
+ restriction = PageViewRestriction.objects.create(
52
+ page=self.private_groups_page, restriction_type="groups"
53
+ )
54
+ self.group = Group.objects.create(name="Private page group")
55
+ self.group2 = Group.objects.create(name="Private page group2")
56
+ restriction.groups.add(self.group)
57
+ restriction.groups.add(self.group2)
58
+
59
+ self.private_groups_child_page = self.private_groups_page.add_child(
60
+ instance=SimplePage(
61
+ title="Private groups child page",
62
+ content="hello",
63
+ live=True,
64
+ )
65
+ )
66
+
67
+ def test_get_public(self):
68
+ """
69
+ This tests that a blank form is returned when a user opens the set_privacy view on a public page
70
+ """
71
+ response = self.client.get(
72
+ reverse("wagtailadmin_pages:set_privacy", args=(self.public_page.id,))
73
+ )
74
+
75
+ # Check response
76
+ self.assertEqual(response.status_code, 200)
77
+ self.assertTemplateUsed(response, "wagtailadmin/page_privacy/set_privacy.html")
78
+ self.assertEqual(response.context["page"].specific, self.public_page)
79
+
80
+ # Check form attributes
81
+ self.assertEqual(response.context["form"]["restriction_type"].value(), "none")
82
+
83
+ def test_get_private(self):
84
+ """
85
+ This tests that the restriction type and password fields as set correctly
86
+ when a user opens the set_privacy view on a public page
87
+ """
88
+ response = self.client.get(
89
+ reverse("wagtailadmin_pages:set_privacy", args=(self.private_page.id,))
90
+ )
91
+
92
+ # Check response
93
+ self.assertEqual(response.status_code, 200)
94
+ self.assertTemplateUsed(response, "wagtailadmin/page_privacy/set_privacy.html")
95
+ self.assertEqual(response.context["page"].specific, self.private_page)
96
+
97
+ # Check form attributes
98
+ self.assertEqual(
99
+ response.context["form"]["restriction_type"].value(), "password"
100
+ )
101
+ self.assertEqual(response.context["form"]["password"].value(), "password123")
102
+ self.assertEqual(response.context["form"]["groups"].value(), [])
103
+
104
+ def test_get_private_child(self):
105
+ """
106
+ This tests that the set_privacy view tells the user
107
+ that the password restriction has been applied to an ancestor
108
+ """
109
+ response = self.client.get(
110
+ reverse(
111
+ "wagtailadmin_pages:set_privacy", args=(self.private_child_page.id,)
112
+ )
113
+ )
114
+
115
+ # Check response
116
+ self.assertEqual(response.status_code, 200)
117
+ self.assertTemplateUsed(
118
+ response, "wagtailadmin/page_privacy/ancestor_privacy.html"
119
+ )
120
+ self.assertEqual(
121
+ response.context["page_with_restriction"].specific, self.private_page
122
+ )
123
+
124
+ def test_set_password_restriction(self):
125
+ """
126
+ This tests that setting a password restriction using the set_privacy view works
127
+ """
128
+ post_data = {
129
+ "restriction_type": "password",
130
+ "password": "helloworld",
131
+ "groups": [],
132
+ }
133
+ response = self.client.post(
134
+ reverse("wagtailadmin_pages:set_privacy", args=(self.public_page.id,)),
135
+ post_data,
136
+ )
137
+
138
+ # Check response
139
+ self.assertEqual(response.status_code, 200)
140
+ self.assertContains(response, '"is_public": false')
141
+
142
+ # Check that a page restriction has been created
143
+ self.assertTrue(
144
+ PageViewRestriction.objects.filter(page=self.public_page).exists()
145
+ )
146
+ restriction = PageViewRestriction.objects.get(page=self.public_page)
147
+
148
+ # Check that the password is set correctly
149
+ self.assertEqual(restriction.password, "helloworld")
150
+
151
+ # Check that the restriction_type is set correctly
152
+ self.assertEqual(restriction.restriction_type, "password")
153
+
154
+ # Be sure there are no groups set
155
+ self.assertEqual(restriction.groups.count(), 0)
156
+
157
+ def test_set_password_restriction_password_unset(self):
158
+ """
159
+ This tests that the password field on the form is validated correctly
160
+ """
161
+ post_data = {
162
+ "restriction_type": "password",
163
+ "password": "",
164
+ "groups": [],
165
+ }
166
+ response = self.client.post(
167
+ reverse("wagtailadmin_pages:set_privacy", args=(self.public_page.id,)),
168
+ post_data,
169
+ )
170
+
171
+ # Check response
172
+ self.assertEqual(response.status_code, 200)
173
+
174
+ # Check that a form error was raised
175
+ self.assertFormError(response, "form", "password", "This field is required.")
176
+
177
+ def test_unset_password_restriction(self):
178
+ """
179
+ This tests that removing a password restriction using the set_privacy view works
180
+ """
181
+ post_data = {
182
+ "restriction_type": "none",
183
+ "password": "",
184
+ "groups": [],
185
+ }
186
+ response = self.client.post(
187
+ reverse("wagtailadmin_pages:set_privacy", args=(self.private_page.id,)),
188
+ post_data,
189
+ )
190
+
191
+ # Check response
192
+ self.assertEqual(response.status_code, 200)
193
+ self.assertContains(response, '"is_public": true')
194
+
195
+ # Check that the page restriction has been deleted
196
+ self.assertFalse(
197
+ PageViewRestriction.objects.filter(page=self.private_page).exists()
198
+ )
199
+
200
+ def test_get_private_groups(self):
201
+ """
202
+ This tests that the restriction type and group fields as set correctly when a user opens the set_privacy view on a public page
203
+ """
204
+ response = self.client.get(
205
+ reverse(
206
+ "wagtailadmin_pages:set_privacy", args=(self.private_groups_page.id,)
207
+ )
208
+ )
209
+
210
+ # Check response
211
+ self.assertEqual(response.status_code, 200)
212
+ self.assertTemplateUsed(response, "wagtailadmin/page_privacy/set_privacy.html")
213
+ self.assertEqual(response.context["page"].specific, self.private_groups_page)
214
+
215
+ # Check form attributes
216
+ self.assertEqual(response.context["form"]["restriction_type"].value(), "groups")
217
+ self.assertEqual(response.context["form"]["password"].value(), "")
218
+ self.assertEqual(
219
+ response.context["form"]["groups"].value(), [self.group.id, self.group2.id]
220
+ )
221
+
222
+ def test_set_group_restriction(self):
223
+ """
224
+ This tests that setting a group restriction using the set_privacy view works
225
+ """
226
+ post_data = {
227
+ "restriction_type": "groups",
228
+ "password": "",
229
+ "groups": [self.group.id, self.group2.id],
230
+ }
231
+ response = self.client.post(
232
+ reverse("wagtailadmin_pages:set_privacy", args=(self.public_page.id,)),
233
+ post_data,
234
+ )
235
+
236
+ # Check response
237
+ self.assertEqual(response.status_code, 200)
238
+ self.assertContains(response, '"is_public": false')
239
+
240
+ # Check that a page restriction has been created
241
+ self.assertTrue(
242
+ PageViewRestriction.objects.filter(page=self.public_page).exists()
243
+ )
244
+
245
+ restriction = PageViewRestriction.objects.get(page=self.public_page)
246
+
247
+ # restriction_type should be 'groups'
248
+ self.assertEqual(restriction.restriction_type, "groups")
249
+
250
+ # Be sure there is no password set
251
+ self.assertEqual(restriction.password, "")
252
+
253
+ # Check that the groups are set correctly
254
+ self.assertEqual(
255
+ set(PageViewRestriction.objects.get(page=self.public_page).groups.all()),
256
+ {self.group, self.group2},
257
+ )
258
+
259
+ def test_set_group_restriction_password_unset(self):
260
+ """
261
+ This tests that the group fields on the form are validated correctly
262
+ """
263
+ post_data = {
264
+ "restriction_type": "groups",
265
+ "password": "",
266
+ "groups": [],
267
+ }
268
+ response = self.client.post(
269
+ reverse("wagtailadmin_pages:set_privacy", args=(self.public_page.id,)),
270
+ post_data,
271
+ )
272
+
273
+ # Check response
274
+ self.assertEqual(response.status_code, 200)
275
+
276
+ # Check that a form error was raised
277
+ self.assertFormError(
278
+ response, "form", "groups", "Please select at least one group."
279
+ )
280
+
281
+ def test_unset_group_restriction(self):
282
+ """
283
+ This tests that removing a groups restriction using the set_privacy view works
284
+ """
285
+ post_data = {
286
+ "restriction_type": "none",
287
+ "password": "",
288
+ "groups": [],
289
+ }
290
+ response = self.client.post(
291
+ reverse("wagtailadmin_pages:set_privacy", args=(self.private_page.id,)),
292
+ post_data,
293
+ )
294
+
295
+ # Check response
296
+ self.assertEqual(response.status_code, 200)
297
+ self.assertContains(response, '"is_public": true')
298
+
299
+ # Check that the page restriction has been deleted
300
+ self.assertFalse(
301
+ PageViewRestriction.objects.filter(page=self.private_page).exists()
302
+ )
303
+
304
+
305
+ class TestPrivacyIndicators(TestCase, WagtailTestUtils):
306
+ def setUp(self):
307
+ self.login()
308
+
309
+ # Create some pages
310
+ self.homepage = Page.objects.get(id=2)
311
+
312
+ self.public_page = self.homepage.add_child(
313
+ instance=SimplePage(
314
+ title="Public page",
315
+ content="hello",
316
+ live=True,
317
+ )
318
+ )
319
+
320
+ self.private_page = self.homepage.add_child(
321
+ instance=SimplePage(
322
+ title="Private page",
323
+ content="hello",
324
+ live=True,
325
+ )
326
+ )
327
+ PageViewRestriction.objects.create(
328
+ page=self.private_page, restriction_type="password", password="password123"
329
+ )
330
+
331
+ self.private_child_page = self.private_page.add_child(
332
+ instance=SimplePage(
333
+ title="Private child page",
334
+ content="hello",
335
+ live=True,
336
+ )
337
+ )
338
+
339
+ def test_explorer_public(self):
340
+ """
341
+ This tests that the privacy indicator on the public pages explore view is set to "PUBLIC"
342
+ """
343
+ response = self.client.get(
344
+ reverse("wagtailadmin_explore", args=(self.public_page.id,))
345
+ )
346
+
347
+ # Check the response
348
+ self.assertEqual(response.status_code, 200)
349
+
350
+ # Check the privacy indicator is public
351
+ self.assertContains(
352
+ response, '<div class="w-hidden" data-privacy-sidebar-private>'
353
+ )
354
+ self.assertContains(response, '<div class="" data-privacy-sidebar-public>')
355
+
356
+ def test_explorer_private(self):
357
+ """
358
+ This tests that the privacy indicator on the private pages explore view is set to "PRIVATE"
359
+ """
360
+ response = self.client.get(
361
+ reverse("wagtailadmin_explore", args=(self.private_page.id,))
362
+ )
363
+
364
+ # Check the response
365
+ self.assertEqual(response.status_code, 200)
366
+
367
+ # Check the privacy indicator is private
368
+ self.assertContains(response, '<div class="" data-privacy-sidebar-private>')
369
+ self.assertContains(
370
+ response, '<div class="w-hidden" data-privacy-sidebar-public>'
371
+ )
372
+
373
+ def test_explorer_private_child(self):
374
+ """
375
+ This tests that the privacy indicator on the private child pages explore view is set to "PRIVATE"
376
+ """
377
+ response = self.client.get(
378
+ reverse("wagtailadmin_explore", args=(self.private_child_page.id,))
379
+ )
380
+
381
+ # Check the response
382
+ self.assertEqual(response.status_code, 200)
383
+
384
+ # Check the privacy indicator is private
385
+ self.assertContains(response, '<div class="" data-privacy-sidebar-private>')
386
+ self.assertContains(
387
+ response, '<div class="w-hidden" data-privacy-sidebar-public>'
388
+ )
389
+
390
+ def test_explorer_list_homepage(self):
391
+ """
392
+ This tests that there is a padlock displayed next to the private page in the homepages explorer listing
393
+ """
394
+ response = self.client.get(
395
+ reverse("wagtailadmin_explore", args=(self.homepage.id,))
396
+ )
397
+
398
+ # Check the response
399
+ self.assertEqual(response.status_code, 200)
400
+
401
+ # Must have one privacy icon (next to the private page)
402
+ self.assertContains(
403
+ response,
404
+ 'class="indicator privacy-indicator"',
405
+ count=1,
406
+ )
407
+
408
+ def test_explorer_list_private(self):
409
+ """
410
+ This tests that there is a padlock displayed
411
+ next to the private child page in the private pages explorer listing
412
+ """
413
+ response = self.client.get(
414
+ reverse("wagtailadmin_explore", args=(self.private_page.id,))
415
+ )
416
+
417
+ # Check the response
418
+ self.assertEqual(response.status_code, 200)
419
+
420
+ # Must have one privacy icon (next to the private child page)
421
+ self.assertContains(
422
+ response,
423
+ 'class="indicator privacy-indicator"',
424
+ count=1,
425
+ )
426
+
427
+ def test_edit_public(self):
428
+ """
429
+ This tests that the privacy indicator on the public pages edit view is set to "PUBLIC"
430
+ """
431
+ response = self.client.get(
432
+ reverse("wagtailadmin_pages:edit", args=(self.public_page.id,))
433
+ )
434
+
435
+ # Check the response
436
+ self.assertEqual(response.status_code, 200)
437
+
438
+ # Check the privacy indicator is public
439
+ self.assertContains(
440
+ response, '<div class="w-hidden" data-privacy-sidebar-private>'
441
+ )
442
+ self.assertContains(response, '<div class="" data-privacy-sidebar-public>')
443
+
444
+ def test_edit_private(self):
445
+ """
446
+ This tests that the privacy indicator on the private pages edit view is set to "PRIVATE"
447
+ """
448
+ response = self.client.get(
449
+ reverse("wagtailadmin_pages:edit", args=(self.private_page.id,))
450
+ )
451
+
452
+ # Check the response
453
+ self.assertEqual(response.status_code, 200)
454
+
455
+ # Check the privacy indicator is private
456
+ self.assertContains(response, '<div class="" data-privacy-sidebar-private>')
457
+ self.assertContains(
458
+ response, '<div class="w-hidden" data-privacy-sidebar-public>'
459
+ )
460
+
461
+ def test_edit_private_child(self):
462
+ """
463
+ This tests that the privacy indicator on the private child pages edit view is set to "PRIVATE"
464
+ """
465
+ response = self.client.get(
466
+ reverse("wagtailadmin_pages:edit", args=(self.private_child_page.id,))
467
+ )
468
+
469
+ # Check the response
470
+ self.assertEqual(response.status_code, 200)
471
+
472
+ # Check the privacy indicator is private
473
+ self.assertContains(response, '<div class="" data-privacy-sidebar-private>')
474
+ self.assertContains(
475
+ response, '<div class="w-hidden" data-privacy-sidebar-public>'
476
+ )
testbed/wagtail__wagtail/wagtail/admin/tests/test_reports_views.py ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ from io import BytesIO
3
+
4
+ from django.conf import settings
5
+ from django.conf.locale import LANG_INFO
6
+ from django.contrib.auth.models import Permission
7
+ from django.test import TestCase
8
+ from django.test.utils import override_settings
9
+ from django.urls import reverse
10
+ from django.utils import timezone, translation
11
+ from openpyxl import load_workbook
12
+
13
+ from wagtail.admin.views.mixins import ExcelDateFormatter
14
+ from wagtail.models import Page, PageLogEntry
15
+ from wagtail.test.utils import WagtailTestUtils
16
+
17
+
18
+ class TestLockedPagesView(TestCase, WagtailTestUtils):
19
+ def setUp(self):
20
+ self.user = self.login()
21
+
22
+ def get(self, params={}):
23
+ return self.client.get(reverse("wagtailadmin_reports:locked_pages"), params)
24
+
25
+ def test_simple(self):
26
+ response = self.get()
27
+ self.assertEqual(response.status_code, 200)
28
+ self.assertTemplateUsed(response, "wagtailadmin/reports/locked_pages.html")
29
+
30
+ # Initially there should be no locked pages
31
+ self.assertContains(response, "No locked pages found.")
32
+
33
+ # No user locked anything
34
+ self.assertInHTML(
35
+ """
36
+ <select name="locked_by" id="id_locked_by">
37
+ <option value="" selected>---------</option>
38
+ </select>
39
+ """,
40
+ response.content.decode(),
41
+ )
42
+
43
+ self.page = Page.objects.first()
44
+ self.page.locked = True
45
+ self.page.locked_by = self.user
46
+ self.page.locked_at = timezone.now()
47
+ self.page.save()
48
+
49
+ # Now the listing should contain our locked page
50
+ response = self.get()
51
+ self.assertEqual(response.status_code, 200)
52
+ self.assertTemplateUsed(response, "wagtailadmin/reports/locked_pages.html")
53
+ self.assertNotContains(response, "No locked pages found.")
54
+ self.assertContains(response, self.page.title)
55
+
56
+ self.assertInHTML(
57
+ f"""
58
+ <select name="locked_by" id="id_locked_by">
59
+ <option value="" selected>---------</option>
60
+ <option value="{self.user.pk}">{self.user}</option>
61
+ </select>
62
+ """,
63
+ response.content.decode(),
64
+ )
65
+
66
+ # Locked by current user shown in indicator
67
+ self.assertContains(response, "locked-indicator indicator--is-inverse")
68
+ self.assertContains(
69
+ response, 'title="This page is locked, by you, to further editing"'
70
+ )
71
+
72
+ def test_csv_export(self):
73
+
74
+ self.page = Page.objects.first()
75
+ self.page.locked = True
76
+ self.page.locked_by = self.user
77
+ if settings.USE_TZ:
78
+ # 12:00 UTC
79
+ self.page.locked_at = "2013-02-01T12:00:00.000Z"
80
+ self.page.latest_revision_created_at = "2013-01-01T12:00:00.000Z"
81
+ else:
82
+ # 12:00 in no specific timezone
83
+ self.page.locked_at = "2013-02-01T12:00:00"
84
+ self.page.latest_revision_created_at = "2013-01-01T12:00:00"
85
+ self.page.save()
86
+
87
+ response = self.get(params={"export": "csv"})
88
+
89
+ # Check response
90
+ self.assertEqual(response.status_code, 200)
91
+ data_lines = response.getvalue().decode().split("\n")
92
+ self.assertEqual(
93
+ data_lines[0], "Title,Updated,Status,Type,Locked At,Locked By\r"
94
+ )
95
+ if settings.USE_TZ:
96
+ self.assertEqual(
97
+ data_lines[1],
98
+ "Root,2013-01-01 12:00:00+00:00,live,Page,2013-02-01 12:00:00+00:00,test@email.com\r",
99
+ )
100
+ else:
101
+ self.assertEqual(
102
+ data_lines[1],
103
+ "Root,2013-01-01 12:00:00,live,Page,2013-02-01 12:00:00,test@email.com\r",
104
+ )
105
+
106
+ def test_xlsx_export(self):
107
+
108
+ self.page = Page.objects.first()
109
+ self.page.locked = True
110
+ self.page.locked_by = self.user
111
+ if settings.USE_TZ:
112
+ # 12:00 UTC
113
+ self.page.locked_at = "2013-02-01T12:00:00.000Z"
114
+ self.page.latest_revision_created_at = "2013-01-01T12:00:00.000Z"
115
+ else:
116
+ # 12:00 in no specific timezone
117
+ self.page.locked_at = "2013-02-01T12:00:00"
118
+ self.page.latest_revision_created_at = "2013-01-01T12:00:00"
119
+ self.page.save()
120
+
121
+ response = self.get(params={"export": "xlsx"})
122
+
123
+ # Check response - the locked page info should be in it
124
+ self.assertEqual(response.status_code, 200)
125
+ workbook_data = response.getvalue()
126
+ worksheet = load_workbook(filename=BytesIO(workbook_data))["Sheet1"]
127
+ cell_array = [[cell.value for cell in row] for row in worksheet.rows]
128
+ self.assertEqual(
129
+ cell_array[0],
130
+ ["Title", "Updated", "Status", "Type", "Locked At", "Locked By"],
131
+ )
132
+ self.assertEqual(
133
+ cell_array[1],
134
+ [
135
+ "Root",
136
+ datetime.datetime(2013, 1, 1, 12, 0),
137
+ "live",
138
+ "Page",
139
+ datetime.datetime(2013, 2, 1, 12, 0),
140
+ "test@email.com",
141
+ ],
142
+ )
143
+ self.assertEqual(len(cell_array), 2)
144
+
145
+ self.assertEqual(worksheet["B2"].number_format, ExcelDateFormatter().get())
146
+ self.assertEqual(worksheet["E2"].number_format, ExcelDateFormatter().get())
147
+
148
+
149
+ class TestFilteredLockedPagesView(TestCase, WagtailTestUtils):
150
+ fixtures = ["test.json"]
151
+
152
+ def setUp(self):
153
+ self.user = self.login()
154
+ self.unpublished_page = Page.objects.get(
155
+ url_path="/home/events/tentative-unpublished-event/"
156
+ )
157
+ self.unpublished_page.locked = True
158
+ self.unpublished_page.locked_by = self.user
159
+ self.unpublished_page.locked_at = timezone.now()
160
+ self.unpublished_page.save()
161
+
162
+ def get(self, params={}):
163
+ return self.client.get(reverse("wagtailadmin_reports:locked_pages"), params)
164
+
165
+ def test_filter_by_live(self):
166
+ response = self.get(params={"live": "true"})
167
+ self.assertEqual(response.status_code, 200)
168
+ self.assertNotContains(response, "Tentative Unpublished Event")
169
+ self.assertContains(response, "My locked page")
170
+
171
+ response = self.get(params={"live": "false"})
172
+ self.assertEqual(response.status_code, 200)
173
+ self.assertContains(response, "Tentative Unpublished Event")
174
+ self.assertNotContains(response, "My locked page")
175
+
176
+ def test_filter_by_user(self):
177
+ response = self.get(params={"locked_by": self.user.pk})
178
+ self.assertEqual(response.status_code, 200)
179
+ self.assertContains(response, "Tentative Unpublished Event")
180
+ self.assertNotContains(response, "My locked page")
181
+
182
+
183
+ class TestFilteredLogEntriesView(TestCase, WagtailTestUtils):
184
+ fixtures = ["test.json"]
185
+
186
+ def setUp(self):
187
+ self.user = self.login()
188
+ self.home_page = Page.objects.get(url_path="/home/")
189
+
190
+ self.create_log = PageLogEntry.objects.log_action(
191
+ self.home_page, "wagtail.create"
192
+ )
193
+ self.edit_log_1 = PageLogEntry.objects.log_action(
194
+ self.home_page, "wagtail.edit"
195
+ )
196
+ self.edit_log_2 = PageLogEntry.objects.log_action(
197
+ self.home_page, "wagtail.edit"
198
+ )
199
+ self.edit_log_3 = PageLogEntry.objects.log_action(
200
+ self.home_page, "wagtail.edit"
201
+ )
202
+
203
+ self.create_comment_log = PageLogEntry.objects.log_action(
204
+ self.home_page,
205
+ "wagtail.comments.create",
206
+ data={
207
+ "comment": {
208
+ "contentpath": "title",
209
+ "text": "Foo",
210
+ }
211
+ },
212
+ )
213
+ self.edit_comment_log = PageLogEntry.objects.log_action(
214
+ self.home_page,
215
+ "wagtail.comments.edit",
216
+ data={
217
+ "comment": {
218
+ "contentpath": "title",
219
+ "text": "Edited",
220
+ }
221
+ },
222
+ )
223
+ self.create_reply_log = PageLogEntry.objects.log_action(
224
+ self.home_page,
225
+ "wagtail.comments.create_reply",
226
+ data={
227
+ "comment": {
228
+ "contentpath": "title",
229
+ "text": "Foo",
230
+ }
231
+ },
232
+ )
233
+
234
+ def get(self, params={}):
235
+ return self.client.get(reverse("wagtailadmin_reports:site_history"), params)
236
+
237
+ def assert_log_entries(self, response, expected):
238
+ actual = set(response.context["object_list"])
239
+ self.assertSetEqual(actual, set(expected))
240
+
241
+ def test_unfiltered(self):
242
+ response = self.get()
243
+ self.assertEqual(response.status_code, 200)
244
+ self.assert_log_entries(
245
+ response,
246
+ [
247
+ self.create_log,
248
+ self.edit_log_1,
249
+ self.edit_log_2,
250
+ self.edit_log_3,
251
+ self.create_comment_log,
252
+ self.edit_comment_log,
253
+ self.create_reply_log,
254
+ ],
255
+ )
256
+
257
+ def test_filter_by_action(self):
258
+ response = self.get(params={"action": "wagtail.edit"})
259
+ self.assertEqual(response.status_code, 200)
260
+ self.assert_log_entries(
261
+ response,
262
+ [
263
+ self.edit_log_1,
264
+ self.edit_log_2,
265
+ self.edit_log_3,
266
+ ],
267
+ )
268
+
269
+ def test_hide_commenting_actions(self):
270
+ response = self.get(params={"hide_commenting_actions": "on"})
271
+ self.assertEqual(response.status_code, 200)
272
+ self.assert_log_entries(
273
+ response,
274
+ [
275
+ self.create_log,
276
+ self.edit_log_1,
277
+ self.edit_log_2,
278
+ self.edit_log_3,
279
+ ],
280
+ )
281
+
282
+
283
+ @override_settings(
284
+ USE_L10N=True,
285
+ )
286
+ class TestExcelDateFormatter(TestCase):
287
+ def test_all_locales(self):
288
+ formatter = ExcelDateFormatter()
289
+
290
+ for lang in LANG_INFO.keys():
291
+ with self.subTest(lang), translation.override(lang):
292
+ self.assertNotEqual(formatter.get(), "")
293
+
294
+ def test_format(self):
295
+ formatter = ExcelDateFormatter()
296
+
297
+ with self.subTest(format="r"):
298
+ # Format code for RFC 5322 formatted date, e.g. 'Thu, 21 Dec 2000 16:01:07'
299
+ self.assertEqual(formatter.format("r"), "ddd, d mmm yyyy hh:mm:ss")
300
+
301
+ with self.subTest(format="m/d/Y g:i A"):
302
+ # Format code for e.g. '12/21/2000 4:01 PM'
303
+ self.assertEqual(formatter.format("m/d/Y g:i A"), "mm/dd/yyyy h:mm AM/PM")
304
+
305
+
306
+ class TestAgingPagesView(TestCase, WagtailTestUtils):
307
+ def setUp(self):
308
+ self.user = self.login()
309
+ self.root = Page.objects.first()
310
+ self.home = Page.objects.get(slug="home")
311
+
312
+ def get(self, params={}):
313
+ return self.client.get(reverse("wagtailadmin_reports:aging_pages"), params)
314
+
315
+ def publish_home_page(self):
316
+ self.home.save_revision().publish(user=self.user)
317
+
318
+ def test_simple(self):
319
+ response = self.get()
320
+ self.assertEqual(response.status_code, 200)
321
+ self.assertTemplateUsed(response, "wagtailadmin/reports/aging_pages.html")
322
+
323
+ def test_displays_only_published_pages(self):
324
+ response = self.get()
325
+ self.assertContains(response, "No pages found.")
326
+
327
+ self.publish_home_page()
328
+ response = self.get()
329
+
330
+ # Home Page should be listed
331
+ self.assertContains(response, self.home.title)
332
+ # Last published by user is set
333
+ self.assertContains(response, self.user.get_username())
334
+
335
+ self.assertNotContains(response, self.root.title)
336
+ self.assertNotContains(response, "No pages found.")
337
+
338
+ def test_permissions(self):
339
+ # Publish home page
340
+ self.publish_home_page()
341
+
342
+ # Remove privileges from user
343
+ self.user.is_superuser = False
344
+ self.user.user_permissions.add(
345
+ Permission.objects.get(
346
+ content_type__app_label="wagtailadmin", codename="access_admin"
347
+ )
348
+ )
349
+ self.user.save()
350
+
351
+ response = self.get()
352
+ self.assertContains(response, "No pages found.")
353
+ self.assertNotContains(response, self.home.title)
354
+
355
+ def test_csv_export(self):
356
+ self.publish_home_page()
357
+ if settings.USE_TZ:
358
+ self.home.last_published_at = "2013-01-01T12:00:00.000Z"
359
+ else:
360
+ self.home.last_published_at = "2013-01-01T12:00:00"
361
+ self.home.save()
362
+
363
+ response = self.get(params={"export": "csv"})
364
+ self.assertEqual(response.status_code, 200)
365
+
366
+ data_lines = response.getvalue().decode().split("\n")
367
+ self.assertEqual(
368
+ data_lines[0], "Title,Status,Last published at,Last published by,Type\r"
369
+ )
370
+ if settings.USE_TZ:
371
+ self.assertEqual(
372
+ data_lines[1],
373
+ "Welcome to your new Wagtail site!,live + draft,2013-01-01 12:00:00+00:00,test@email.com,Page\r",
374
+ )
375
+ else:
376
+ self.assertEqual(
377
+ data_lines[1],
378
+ "Welcome to your new Wagtail site!,live + draft,2013-01-01 12:00:00,test@email.com,Page\r",
379
+ )
380
+
381
+ def test_xlsx_export(self):
382
+ self.publish_home_page()
383
+
384
+ if settings.USE_TZ:
385
+ self.home.last_published_at = "2013-01-01T12:00:00.000Z"
386
+ else:
387
+ self.home.last_published_at = "2013-01-01T12:00:00"
388
+ self.home.save()
389
+
390
+ response = self.get(params={"export": "xlsx"})
391
+ self.assertEqual(response.status_code, 200)
392
+
393
+ workbook_data = response.getvalue()
394
+ worksheet = load_workbook(filename=BytesIO(workbook_data))["Sheet1"]
395
+ cell_array = [[cell.value for cell in row] for row in worksheet.rows]
396
+
397
+ self.assertEqual(
398
+ cell_array[0],
399
+ ["Title", "Status", "Last published at", "Last published by", "Type"],
400
+ )
401
+ self.assertEqual(
402
+ cell_array[1],
403
+ [
404
+ "Welcome to your new Wagtail site!",
405
+ "live + draft",
406
+ datetime.datetime(2013, 1, 1, 12, 0),
407
+ "test@email.com",
408
+ "Page",
409
+ ],
410
+ )
411
+ self.assertEqual(len(cell_array), 2)
412
+
413
+ self.assertEqual(worksheet["C2"].number_format, ExcelDateFormatter().get())
414
+
415
+ def test_report_renders_when_page_publisher_deleted(self):
416
+ temp_user = self.create_superuser(
417
+ "temp", email="temp@user.com", password="tempuser"
418
+ )
419
+ expected_deleted_string = f"user {temp_user.pk} (deleted)"
420
+
421
+ self.home.save_revision().publish(user=temp_user)
422
+ temp_user.delete()
423
+
424
+ response = self.get()
425
+ self.assertContains(response, expected_deleted_string)
426
+
427
+
428
+ class TestFilteredAgingPagesView(TestCase, WagtailTestUtils):
429
+ fixtures = ["test.json"]
430
+
431
+ def setUp(self):
432
+ self.user = self.login()
433
+ self.home_page = Page.objects.get(slug="home")
434
+ self.aboutus_page = Page.objects.get(slug="about-us")
435
+
436
+ def get(self, params={}):
437
+ return self.client.get(reverse("wagtailadmin_reports:aging_pages"), params)
438
+
439
+ def test_filter_by_live(self):
440
+ response = self.get(params={"live": "true"})
441
+
442
+ self.assertEqual(response.status_code, 200)
443
+ self.assertContains(response, self.home_page.title)
444
+ self.assertContains(response, self.aboutus_page.title)
445
+
446
+ response = self.get(params={"live": "false"})
447
+ self.assertEqual(response.status_code, 200)
448
+ self.assertNotContains(response, self.home_page.title)
449
+ self.assertNotContains(response, self.aboutus_page.title)
450
+
451
+ def test_filter_by_content_type(self):
452
+ response = self.get(
453
+ params={"content_type": self.home_page.specific.content_type.pk}
454
+ )
455
+
456
+ self.assertEqual(response.status_code, 200)
457
+ self.assertContains(response, self.home_page.title)
458
+ self.assertNotContains(response, self.aboutus_page.title)
459
+
460
+ def test_filter_by_last_published_at(self):
461
+ self.home_page.last_published_at = timezone.now()
462
+ self.home_page.save()
463
+
464
+ response = self.get(params={"last_published_at": "2015-01-01"})
465
+ self.assertEqual(response.status_code, 200)
466
+ self.assertContains(response, self.aboutus_page.title)
467
+ self.assertNotContains(response, self.home_page.title)
testbed/wagtail__wagtail/wagtail/admin/tests/test_rich_text.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from bs4 import BeautifulSoup
4
+ from django.conf import settings
5
+ from django.test import SimpleTestCase, TestCase
6
+ from django.test.utils import override_settings
7
+ from django.urls import reverse
8
+
9
+ from wagtail.admin.rich_text import DraftailRichTextArea, get_rich_text_editor_widget
10
+ from wagtail.admin.rich_text.converters.editor_html import PageLinkHandler
11
+ from wagtail.admin.rich_text.editors.draftail.features import Feature
12
+ from wagtail.blocks import RichTextBlock
13
+ from wagtail.models import Page, get_page_models
14
+ from wagtail.rich_text import RichText
15
+ from wagtail.test.testapp.models import SingleEventPage
16
+ from wagtail.test.testapp.rich_text import CustomRichTextArea, LegacyRichTextArea
17
+ from wagtail.test.utils import WagtailTestUtils
18
+
19
+
20
+ class BaseRichTextEditHandlerTestCase(TestCase):
21
+ def _clear_edit_handler_cache(self):
22
+ """
23
+ These tests generate new panel definitions with different settings. The
24
+ cached edit handlers should be cleared before and after each test run
25
+ to ensure that no changes leak through to other tests.
26
+ """
27
+ from wagtail.test.testapp.models import DefaultRichBlockFieldPage
28
+
29
+ rich_text_block = (
30
+ DefaultRichBlockFieldPage.get_edit_handler()
31
+ .get_form_class()
32
+ .base_fields["body"]
33
+ .block.child_blocks["rich_text"]
34
+ )
35
+ if hasattr(rich_text_block, "field"):
36
+ del rich_text_block.field
37
+
38
+ for page_class in get_page_models():
39
+ page_class.get_edit_handler.cache_clear()
40
+
41
+ def setUp(self):
42
+ super().setUp()
43
+ self._clear_edit_handler_cache()
44
+
45
+ def tearDown(self):
46
+ self._clear_edit_handler_cache()
47
+ super().tearDown()
48
+
49
+
50
+ class TestGetRichTextEditorWidget(TestCase):
51
+ @override_settings() # create temporary copy of settings so we can remove WAGTAILADMIN_RICH_TEXT_EDITORS
52
+ def test_default(self):
53
+ # Simulate the absence of a setting
54
+ if hasattr(settings, "WAGTAILADMIN_RICH_TEXT_EDITORS"):
55
+ del settings.WAGTAILADMIN_RICH_TEXT_EDITORS
56
+
57
+ self.assertIsInstance(get_rich_text_editor_widget(), DraftailRichTextArea)
58
+
59
+ @override_settings(
60
+ WAGTAILADMIN_RICH_TEXT_EDITORS={
61
+ "default": {"WIDGET": "wagtail.test.testapp.rich_text.CustomRichTextArea"},
62
+ }
63
+ )
64
+ def test_overridden_default_editor(self):
65
+ self.assertIsInstance(get_rich_text_editor_widget(), CustomRichTextArea)
66
+
67
+ @override_settings(
68
+ WAGTAILADMIN_RICH_TEXT_EDITORS={
69
+ "custom": {"WIDGET": "wagtail.test.testapp.rich_text.CustomRichTextArea"},
70
+ }
71
+ )
72
+ def test_custom_editor_without_default(self):
73
+ self.assertIsInstance(get_rich_text_editor_widget(), DraftailRichTextArea)
74
+ self.assertIsInstance(get_rich_text_editor_widget("custom"), CustomRichTextArea)
75
+
76
+ @override_settings(
77
+ WAGTAILADMIN_RICH_TEXT_EDITORS={
78
+ "default": {"WIDGET": "wagtail.test.testapp.rich_text.LegacyRichTextArea"},
79
+ "custom": {"WIDGET": "wagtail.test.testapp.rich_text.CustomRichTextArea"},
80
+ }
81
+ )
82
+ def test_custom_editor_with_default(self):
83
+ self.assertIsInstance(get_rich_text_editor_widget(), LegacyRichTextArea)
84
+ self.assertIsInstance(get_rich_text_editor_widget("custom"), CustomRichTextArea)
85
+
86
+
87
+ class TestDefaultRichText(BaseRichTextEditHandlerTestCase, WagtailTestUtils):
88
+ def setUp(self):
89
+ super().setUp()
90
+ # Find root page
91
+ self.root_page = Page.objects.get(id=2)
92
+
93
+ self.login()
94
+
95
+ @override_settings() # create temporary copy of settings so we can remove WAGTAILADMIN_RICH_TEXT_EDITORS
96
+ def test_default_editor_in_rich_text_field(self):
97
+ # Simulate the absence of a setting
98
+ if hasattr(settings, "WAGTAILADMIN_RICH_TEXT_EDITORS"):
99
+ del settings.WAGTAILADMIN_RICH_TEXT_EDITORS
100
+
101
+ response = self.client.get(
102
+ reverse(
103
+ "wagtailadmin_pages:add",
104
+ args=("tests", "defaultrichtextfieldpage", self.root_page.id),
105
+ )
106
+ )
107
+
108
+ # Check status code
109
+ self.assertEqual(response.status_code, 200)
110
+
111
+ # Check that draftail (default editor) initialisation is applied
112
+ self.assertContains(response, "window.draftail.initEditor('#id_body',")
113
+
114
+ # check that media for draftail is being imported
115
+ self.assertContains(response, "wagtailadmin/js/draftail.js")
116
+
117
+ # check that media for non-active features is not being imported
118
+ self.assertNotContains(response, "testapp/js/draftail-blockquote.js")
119
+ self.assertNotContains(response, "testapp/css/draftail-blockquote.css")
120
+
121
+ @unittest.expectedFailure # TODO(telepath)
122
+ @override_settings() # create temporary copy of settings so we can remove WAGTAILADMIN_RICH_TEXT_EDITORS
123
+ def test_default_editor_in_rich_text_block(self):
124
+ # Simulate the absence of a setting
125
+ if hasattr(settings, "WAGTAILADMIN_RICH_TEXT_EDITORS"):
126
+ del settings.WAGTAILADMIN_RICH_TEXT_EDITORS
127
+
128
+ response = self.client.get(
129
+ reverse(
130
+ "wagtailadmin_pages:add",
131
+ args=("tests", "defaultrichblockfieldpage", self.root_page.id),
132
+ )
133
+ )
134
+
135
+ # Check status code
136
+ self.assertEqual(response.status_code, 200)
137
+
138
+ # Check that draftail (default editor) initialisation is applied
139
+ self.assertContains(
140
+ response, "window.draftail.initEditor('#__PREFIX__\\u002Dvalue',"
141
+ )
142
+
143
+ # check that media for draftail is being imported
144
+ self.assertContains(response, "wagtailadmin/js/draftail.js")
145
+
146
+ # check that media for non-active features is not being imported
147
+ self.assertNotContains(response, "testapp/js/draftail-blockquote.js")
148
+ self.assertNotContains(response, "testapp/css/draftail-blockquote.css")
149
+
150
+
151
+ @override_settings(
152
+ WAGTAILADMIN_RICH_TEXT_EDITORS={
153
+ "default": {
154
+ "WIDGET": "wagtail.admin.rich_text.DraftailRichTextArea",
155
+ "OPTIONS": {"features": ["h2", "quotation"]},
156
+ },
157
+ }
158
+ )
159
+ class TestDraftailFeatureMedia(BaseRichTextEditHandlerTestCase, WagtailTestUtils):
160
+ """
161
+ Features that define additional js/css imports (blockquote, in this case) should
162
+ have those loaded on the page
163
+ """
164
+
165
+ def setUp(self):
166
+ super().setUp()
167
+ # Find root page
168
+ self.root_page = Page.objects.get(id=2)
169
+
170
+ self.login()
171
+
172
+ def test_feature_media_on_rich_text_field(self):
173
+ response = self.client.get(
174
+ reverse(
175
+ "wagtailadmin_pages:add",
176
+ args=("tests", "defaultrichtextfieldpage", self.root_page.id),
177
+ )
178
+ )
179
+
180
+ self.assertContains(response, "wagtailadmin/js/draftail.js")
181
+ self.assertContains(response, "testapp/js/draftail-quotation.js")
182
+ self.assertContains(response, "testapp/css/draftail-quotation.css")
183
+
184
+ def test_feature_media_on_rich_text_block(self):
185
+ response = self.client.get(
186
+ reverse(
187
+ "wagtailadmin_pages:add",
188
+ args=("tests", "defaultrichblockfieldpage", self.root_page.id),
189
+ )
190
+ )
191
+
192
+ self.assertContains(response, "wagtailadmin/js/draftail.js")
193
+ self.assertContains(response, "testapp/js/draftail-quotation.js")
194
+ self.assertContains(response, "testapp/css/draftail-quotation.css")
195
+
196
+
197
+ @override_settings(
198
+ WAGTAILADMIN_RICH_TEXT_EDITORS={
199
+ "default": {"WIDGET": "wagtail.test.testapp.rich_text.LegacyRichTextArea"},
200
+ }
201
+ )
202
+ class TestOverriddenDefaultRichText(BaseRichTextEditHandlerTestCase, WagtailTestUtils):
203
+ def setUp(self):
204
+ super().setUp()
205
+
206
+ # Find root page
207
+ self.root_page = Page.objects.get(id=2)
208
+
209
+ self.login()
210
+
211
+ def test_overridden_default_editor_in_rich_text_field(self):
212
+ response = self.client.get(
213
+ reverse(
214
+ "wagtailadmin_pages:add",
215
+ args=("tests", "defaultrichtextfieldpage", self.root_page.id),
216
+ )
217
+ )
218
+
219
+ # Check status code
220
+ self.assertEqual(response.status_code, 200)
221
+
222
+ # Check that custom editor (default editor by now) was replaced with fake editor
223
+ self.assertNotContains(response, 'customEditorInitScript("id_body");')
224
+ self.assertContains(response, 'legacyEditorInitScript("id_body");')
225
+
226
+ @unittest.expectedFailure # TODO(telepath)
227
+ def test_overridden_default_editor_in_rich_text_block(self):
228
+ response = self.client.get(
229
+ reverse(
230
+ "wagtailadmin_pages:add",
231
+ args=("tests", "defaultrichblockfieldpage", self.root_page.id),
232
+ )
233
+ )
234
+
235
+ # Check status code
236
+ self.assertEqual(response.status_code, 200)
237
+
238
+ # Check that custom editor (default editor by now) was replaced with fake editor
239
+ self.assertNotContains(response, 'customEditorInitScript("__PREFIX__-value");')
240
+ self.assertContains(response, 'legacyEditorInitScript("__PREFIX__-value");')
241
+
242
+
243
+ @override_settings(
244
+ WAGTAILADMIN_RICH_TEXT_EDITORS={
245
+ "default": {
246
+ "WIDGET": "wagtail.admin.tests.test_rich_text.TestCustomDefaultRichText"
247
+ },
248
+ "custom": {"WIDGET": "wagtail.test.testapp.rich_text.CustomRichTextArea"},
249
+ }
250
+ )
251
+ class TestCustomDefaultRichText(BaseRichTextEditHandlerTestCase, WagtailTestUtils):
252
+ def setUp(self):
253
+ super().setUp()
254
+
255
+ # Find root page
256
+ self.root_page = Page.objects.get(id=2)
257
+
258
+ self.login()
259
+
260
+ def test_custom_editor_in_rich_text_field(self):
261
+ response = self.client.get(
262
+ reverse(
263
+ "wagtailadmin_pages:add",
264
+ args=("tests", "customrichtextfieldpage", self.root_page.id),
265
+ )
266
+ )
267
+
268
+ # Check status code
269
+ self.assertEqual(response.status_code, 200)
270
+
271
+ # Check that custom editor (default editor by now) was replaced with fake editor
272
+ self.assertNotContains(response, 'legacyEditorInitScript("id_body");')
273
+ self.assertContains(response, 'customEditorInitScript("id_body");')
274
+
275
+ @unittest.expectedFailure # TODO(telepath)
276
+ def test_custom_editor_in_rich_text_block(self):
277
+ response = self.client.get(
278
+ reverse(
279
+ "wagtailadmin_pages:add",
280
+ args=("tests", "customrichblockfieldpage", self.root_page.id),
281
+ )
282
+ )
283
+
284
+ # Check status code
285
+ self.assertEqual(response.status_code, 200)
286
+
287
+ self.assertContains(response, 'customEditorInitScript("__PREFIX__-value");')
288
+
289
+
290
+ class TestRichTextValue(TestCase):
291
+ def setUp(self):
292
+ self.root_page = Page.objects.get(id=2)
293
+
294
+ self.single_event_page = SingleEventPage(
295
+ title="foo",
296
+ location="the moon",
297
+ audience="public",
298
+ cost="free",
299
+ date_from="2001-01-01",
300
+ )
301
+ self.root_page.add_child(instance=self.single_event_page)
302
+
303
+ def test_render(self):
304
+ text = '<p>To the <a linktype="page" id="{}">moon</a>!</p>'.format(
305
+ self.single_event_page.id
306
+ )
307
+ value = RichText(text)
308
+ result = str(value)
309
+ expected = '<p>To the <a href="/foo/pointless-suffix/">moon</a>!</p>'
310
+ self.assertEqual(result, expected)
311
+
312
+
313
+ @override_settings(
314
+ WAGTAILADMIN_RICH_TEXT_EDITORS={
315
+ "default": {
316
+ "WIDGET": "wagtail.admin.rich_text.DraftailRichTextArea",
317
+ "OPTIONS": {"features": ["h2", "image"]},
318
+ },
319
+ }
320
+ )
321
+ class TestDraftailWithFeatureOptions(BaseRichTextEditHandlerTestCase, WagtailTestUtils):
322
+ def setUp(self):
323
+ super().setUp()
324
+
325
+ # Find root page
326
+ self.root_page = Page.objects.get(id=2)
327
+
328
+ self.login()
329
+
330
+ def test_settings_features_option_on_rich_text_field(self):
331
+ response = self.client.get(
332
+ reverse(
333
+ "wagtailadmin_pages:add",
334
+ args=("tests", "defaultrichtextfieldpage", self.root_page.id),
335
+ )
336
+ )
337
+ self.assertEqual(response.status_code, 200)
338
+ self.assertContains(response, '"type": "header-two"')
339
+ self.assertContains(response, '"type": "IMAGE"')
340
+ self.assertNotContains(response, '"type": "ordered-list-item"')
341
+
342
+ @unittest.expectedFailure # TODO(telepath)
343
+ def test_features_option_on_rich_text_block(self):
344
+ # a 'features' list passed on the RichTextBlock
345
+ # should override the list in OPTIONS
346
+ block = RichTextBlock(features=["h2", "embed"])
347
+
348
+ form_html = block.render_form(block.to_python("<p>hello</p>"), "body")
349
+
350
+ self.assertIn('"type": "header-two"', form_html)
351
+ self.assertIn('"type": "EMBED"', form_html)
352
+ self.assertNotIn('"type": "IMAGE""', form_html)
353
+ self.assertNotIn('"type": "ordered-list-item""', form_html)
354
+
355
+
356
+ class TestDraftailWithAdditionalFeatures(
357
+ BaseRichTextEditHandlerTestCase, WagtailTestUtils
358
+ ):
359
+ def setUp(self):
360
+ super().setUp()
361
+
362
+ # Find root page
363
+ self.root_page = Page.objects.get(id=2)
364
+
365
+ self.login()
366
+
367
+ @override_settings(
368
+ WAGTAILADMIN_RICH_TEXT_EDITORS={
369
+ "default": {
370
+ "WIDGET": "wagtail.admin.rich_text.DraftailRichTextArea",
371
+ },
372
+ }
373
+ )
374
+ def test_additional_features_should_not_be_included_by_default(self):
375
+ response = self.client.get(
376
+ reverse(
377
+ "wagtailadmin_pages:add",
378
+ args=("tests", "defaultrichtextfieldpage", self.root_page.id),
379
+ )
380
+ )
381
+
382
+ self.assertEqual(response.status_code, 200)
383
+ # default ones are there
384
+ self.assertContains(response, '"type": "header-two"')
385
+ self.assertContains(response, '"type": "LINK"')
386
+ self.assertContains(response, '"type": "ITALIC"')
387
+
388
+ # not the additional ones.
389
+ self.assertNotContains(response, '"type": "CODE"')
390
+ self.assertNotContains(response, '"type": "blockquote"')
391
+ self.assertNotContains(response, '"type": "SUPERSCRIPT"')
392
+ self.assertNotContains(response, '"type": "SUBSCRIPT"')
393
+ self.assertNotContains(response, '"type": "STRIKETHROUGH"')
394
+
395
+ @override_settings(
396
+ WAGTAILADMIN_RICH_TEXT_EDITORS={
397
+ "default": {
398
+ "WIDGET": "wagtail.admin.rich_text.DraftailRichTextArea",
399
+ "OPTIONS": {
400
+ "features": [
401
+ "h2",
402
+ "code",
403
+ "blockquote",
404
+ "strikethrough",
405
+ "subscript",
406
+ "superscript",
407
+ ]
408
+ },
409
+ },
410
+ }
411
+ )
412
+ def test_additional_features_included(self):
413
+ response = self.client.get(
414
+ reverse(
415
+ "wagtailadmin_pages:add",
416
+ args=("tests", "defaultrichtextfieldpage", self.root_page.id),
417
+ )
418
+ )
419
+
420
+ self.assertEqual(response.status_code, 200)
421
+ # Added features are there
422
+ self.assertContains(response, '"type": "header-two"')
423
+ self.assertContains(response, '"type": "CODE"')
424
+ self.assertContains(response, '"type": "blockquote"')
425
+ self.assertContains(response, '"type": "SUPERSCRIPT"')
426
+ self.assertContains(response, '"type": "SUBSCRIPT"')
427
+ self.assertContains(response, '"type": "STRIKETHROUGH"')
428
+
429
+ # But not the unprovided default ones.
430
+ self.assertNotContains(response, '"type": "LINK"')
431
+ self.assertNotContains(response, '"type": "ITALIC"')
432
+
433
+
434
+ class TestPageLinkHandler(TestCase):
435
+ fixtures = ["test.json"]
436
+
437
+ def test_get_db_attributes(self):
438
+ soup = BeautifulSoup('<a data-id="test-id">foo</a>', "html5lib")
439
+ tag = soup.a
440
+ result = PageLinkHandler.get_db_attributes(tag)
441
+ self.assertEqual(result, {"id": "test-id"})
442
+
443
+ def test_expand_db_attributes_for_editor(self):
444
+ result = PageLinkHandler.expand_db_attributes({"id": 1})
445
+ self.assertEqual(result, '<a data-linktype="page" data-id="1" href="None">')
446
+
447
+ events_page_id = Page.objects.get(url_path="/home/events/").pk
448
+ result = PageLinkHandler.expand_db_attributes({"id": events_page_id})
449
+ self.assertEqual(
450
+ result,
451
+ '<a data-linktype="page" data-id="%d" data-parent-id="2" href="/events/">'
452
+ % events_page_id,
453
+ )
454
+
455
+
456
+ class TestWidgetNotHidden(SimpleTestCase):
457
+ def test_draftail(self):
458
+ self.assertIs(
459
+ DraftailRichTextArea().is_hidden,
460
+ False,
461
+ )
462
+
463
+
464
+ class TestDraftailFeature(SimpleTestCase):
465
+ def test_versioned_static_media(self):
466
+ feature = Feature(
467
+ js=["wagtailadmin/js/example/feature.js"],
468
+ css={
469
+ "all": ["wagtailadmin/css/example/feature.css"],
470
+ },
471
+ )
472
+ media_html = str(feature.media)
473
+ self.assertRegex(media_html, r"feature.js\?v=(\w+)")
474
+ self.assertRegex(media_html, r"feature.css\?v=(\w+)")
testbed/wagtail__wagtail/wagtail/admin/tests/test_site_summary.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.contrib.auth.models import Group
2
+ from django.test import TestCase
3
+ from django.urls import reverse
4
+
5
+ from wagtail.admin.site_summary import PagesSummaryItem
6
+ from wagtail.models import GroupPagePermission, Page, Site
7
+ from wagtail.test.testapp.models import SimplePage
8
+ from wagtail.test.utils import WagtailTestUtils
9
+
10
+
11
+ class TestPagesSummary(TestCase, WagtailTestUtils):
12
+ @classmethod
13
+ def setUpClass(cls):
14
+ super().setUpClass()
15
+
16
+ cls.test_page = SimplePage(title="test", slug="test", content="test")
17
+ cls.wagtail_root = Page.get_first_root_node()
18
+ cls.wagtail_root.add_child(instance=cls.test_page)
19
+
20
+ cls.test_page_group = Group.objects.create(name="Test page")
21
+ GroupPagePermission.objects.create(
22
+ group=cls.test_page_group, page=cls.test_page, permission_type="edit"
23
+ )
24
+
25
+ @classmethod
26
+ def tearDownClass(cls):
27
+ cls.test_page.delete()
28
+ cls.test_page_group.delete()
29
+
30
+ super().tearDownClass()
31
+
32
+ def setUp(self):
33
+ self.user = self.login()
34
+ self.request = self.client.get("/").wsgi_request
35
+
36
+ def assertSummaryContains(self, content):
37
+ summary = PagesSummaryItem(self.request).render_html()
38
+ self.assertIn(content, summary)
39
+
40
+ def assertSummaryContainsLinkToPage(self, page_pk):
41
+ self.assertSummaryContains(reverse("wagtailadmin_explore", args=[page_pk]))
42
+
43
+ def test_user_with_page_permissions_is_shown_panel(self):
44
+ self.assertTrue(PagesSummaryItem(self.request).is_shown())
45
+
46
+ def test_single_site_summary_links_to_site_root(self):
47
+ self.assertEqual(Site.objects.count(), 1)
48
+ site = Site.objects.first()
49
+ self.assertSummaryContainsLinkToPage(site.root_page.pk)
50
+
51
+ def test_multiple_sites_summary_links_to_wagtail_root(self):
52
+ Site.objects.create(hostname="foo.com", root_page=self.wagtail_root)
53
+ self.assertSummaryContainsLinkToPage(self.wagtail_root.pk)
54
+
55
+ def test_no_sites_summary_links_to_wagtail_root(self):
56
+ Site.objects.all().delete()
57
+ self.assertSummaryContainsLinkToPage(self.wagtail_root.pk)
58
+
59
+ def test_summary_includes_page_count_without_wagtail_root(self):
60
+ self.assertSummaryContains(
61
+ "<span>{}</span> Pages".format(Page.objects.count() - 1)
62
+ )
63
+
64
+ def test_summary_shows_zero_pages_if_none_exist_except_wagtail_root(self):
65
+ Page.objects.exclude(pk=self.wagtail_root.pk).delete()
66
+ self.assertSummaryContains("<span>0</span> Pages")
67
+
68
+ def test_user_with_no_page_permissions_is_not_shown_panel(self):
69
+ self.user.is_superuser = False
70
+ self.user.save()
71
+ self.assertFalse(PagesSummaryItem(self.request).is_shown())
72
+
73
+ def test_user_with_limited_page_permissions_summary_links_to_their_root(self):
74
+ self.user.is_superuser = False
75
+ self.user.save()
76
+ self.user.groups.add(self.test_page_group)
77
+ self.assertSummaryContainsLinkToPage(self.test_page.pk)
78
+
79
+ def test_user_with_limited_page_permissions_sees_proper_page_count(self):
80
+ self.user.is_superuser = False
81
+ self.user.save()
82
+ self.user.groups.add(self.test_page_group)
83
+ self.assertSummaryContains("<span>1</span> Page")
testbed/wagtail__wagtail/wagtail/admin/tests/test_templatetags.py ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from datetime import timedelta
3
+ from unittest import mock
4
+
5
+ from django.conf import settings
6
+ from django.template import Context, Template, TemplateSyntaxError
7
+ from django.test import TestCase
8
+ from django.test.utils import override_settings
9
+ from django.utils import timezone
10
+ from django.utils.html import format_html
11
+ from freezegun import freeze_time
12
+
13
+ from wagtail.admin.staticfiles import versioned_static
14
+ from wagtail.admin.templatetags.wagtailadmin_tags import (
15
+ avatar_url,
16
+ i18n_enabled,
17
+ locale_label_from_id,
18
+ )
19
+ from wagtail.admin.templatetags.wagtailadmin_tags import locales as locales_tag
20
+ from wagtail.admin.templatetags.wagtailadmin_tags import (
21
+ notification_static,
22
+ timesince_last_update,
23
+ timesince_simple,
24
+ )
25
+ from wagtail.admin.ui.components import Component
26
+ from wagtail.images.tests.utils import get_test_image_file
27
+ from wagtail.models import Locale
28
+ from wagtail.test.utils import WagtailTestUtils
29
+ from wagtail.users.models import UserProfile
30
+
31
+
32
+ class TestAvatarTemplateTag(TestCase, WagtailTestUtils):
33
+ def setUp(self):
34
+ # Create a user
35
+ self.test_user = self.create_user(
36
+ username="testuser",
37
+ email="testuser@email.com",
38
+ password="password",
39
+ )
40
+
41
+ def test_use_gravatar_by_default(self):
42
+ url = avatar_url(self.test_user)
43
+ self.assertIn("www.gravatar.com", url)
44
+
45
+ def test_skip_gravatar_if_no_email(self):
46
+ self.test_user.email = ""
47
+ url = avatar_url(self.test_user)
48
+ self.assertIn("default-user-avatar", url)
49
+
50
+ @override_settings(WAGTAIL_GRAVATAR_PROVIDER_URL="https://robohash.org")
51
+ def test_custom_gravatar_provider(self):
52
+ url = avatar_url(self.test_user)
53
+ self.assertIn("robohash.org", url)
54
+
55
+ @override_settings(WAGTAIL_GRAVATAR_PROVIDER_URL=None)
56
+ def test_disable_gravatar(self):
57
+ url = avatar_url(self.test_user)
58
+ self.assertIn("default-user-avatar", url)
59
+
60
+ def test_uploaded_avatar(self):
61
+ user_profile = UserProfile.get_for_user(self.test_user)
62
+ user_profile.avatar = get_test_image_file(filename="custom-avatar.png")
63
+ user_profile.save()
64
+
65
+ url = avatar_url(self.test_user)
66
+ self.assertIn("custom-avatar", url)
67
+
68
+
69
+ class TestNotificationStaticTemplateTag(TestCase):
70
+ @override_settings(STATIC_URL="/static/")
71
+ def test_local_notification_static(self):
72
+ url = notification_static("wagtailadmin/images/email-header.jpg")
73
+ self.assertEqual(
74
+ "{}/static/wagtailadmin/images/email-header.jpg".format(
75
+ settings.WAGTAILADMIN_BASE_URL
76
+ ),
77
+ url,
78
+ )
79
+
80
+ @override_settings(
81
+ STATIC_URL="/static/", WAGTAILADMIN_BASE_URL="http://localhost:8000"
82
+ )
83
+ def test_local_notification_static_baseurl(self):
84
+ url = notification_static("wagtailadmin/images/email-header.jpg")
85
+ self.assertEqual(
86
+ "http://localhost:8000/static/wagtailadmin/images/email-header.jpg", url
87
+ )
88
+
89
+ @override_settings(
90
+ STATIC_URL="https://s3.amazonaws.com/somebucket/static/",
91
+ WAGTAILADMIN_BASE_URL="http://localhost:8000",
92
+ )
93
+ def test_remote_notification_static(self):
94
+ url = notification_static("wagtailadmin/images/email-header.jpg")
95
+ self.assertEqual(
96
+ "https://s3.amazonaws.com/somebucket/static/wagtailadmin/images/email-header.jpg",
97
+ url,
98
+ )
99
+
100
+
101
+ class TestVersionedStatic(TestCase):
102
+ def test_versioned_static(self):
103
+ result = versioned_static("wagtailadmin/js/core.js")
104
+ self.assertRegex(result, r"^/static/wagtailadmin/js/core.js\?v=(\w+)$")
105
+
106
+ @mock.patch("wagtail.admin.staticfiles.static")
107
+ def test_versioned_static_version_string(self, mock_static):
108
+ mock_static.return_value = "/static/wagtailadmin/js/core.js?v=123"
109
+ result = versioned_static("wagtailadmin/js/core.js")
110
+ self.assertEqual(result, "/static/wagtailadmin/js/core.js?v=123")
111
+ mock_static.assert_called_once_with("wagtailadmin/js/core.js")
112
+
113
+ def test_versioned_static_absolute_path(self):
114
+ result = versioned_static("/static/wagtailadmin/js/core.js")
115
+ self.assertEqual(result, "/static/wagtailadmin/js/core.js")
116
+
117
+ def test_versioned_static_url(self):
118
+ result = versioned_static("http://example.org/static/wagtailadmin/js/core.js")
119
+ self.assertEqual(result, "http://example.org/static/wagtailadmin/js/core.js")
120
+
121
+
122
+ @freeze_time("2020-07-01 12:00:00")
123
+ class TestTimesinceTags(TestCase):
124
+ def test_timesince_simple(self):
125
+ now = timezone.now()
126
+ ts = timesince_simple(now)
127
+ self.assertEqual(ts, "just now")
128
+
129
+ ts = timesince_simple(now - timedelta(hours=1, minutes=10))
130
+ self.assertEqual(ts, "1\xa0hour ago")
131
+
132
+ ts = timesince_simple(now - timedelta(weeks=2, hours=1, minutes=10))
133
+ self.assertEqual(ts, "2\xa0weeks ago")
134
+
135
+ def test_timesince_last_update_today_shows_time(self):
136
+ dt = timezone.now() - timedelta(hours=1)
137
+ formatted_time = dt.astimezone(timezone.get_current_timezone()).strftime(
138
+ "%H:%M"
139
+ )
140
+
141
+ timesince = timesince_last_update(dt)
142
+ self.assertEqual(timesince, formatted_time)
143
+
144
+ # Check prefix output
145
+ timesince = timesince_last_update(dt, show_time_prefix=True)
146
+ self.assertEqual(timesince, "at {}".format(formatted_time))
147
+
148
+ # Check user output
149
+ timesince = timesince_last_update(dt, user_display_name="Gary")
150
+ self.assertEqual(timesince, "{} by Gary".format(formatted_time))
151
+
152
+ # Check user and prefix output
153
+ timesince = timesince_last_update(
154
+ dt, show_time_prefix=True, user_display_name="Gary"
155
+ )
156
+ self.assertEqual(timesince, "at {} by Gary".format(formatted_time))
157
+
158
+ def test_timesince_last_update_before_today_shows_timeago(self):
159
+ dt = timezone.now() - timedelta(weeks=1, days=2)
160
+
161
+ # 1) use_shorthand=False
162
+
163
+ timesince = timesince_last_update(dt, use_shorthand=False)
164
+ self.assertEqual(timesince, "1\xa0week, 2\xa0days ago")
165
+ # The prefix is not used, if the date is older than the current day.
166
+ self.assertEqual(
167
+ timesince_last_update(dt, use_shorthand=False, show_time_prefix=True),
168
+ timesince,
169
+ )
170
+
171
+ # Check user output
172
+ timesince = timesince_last_update(
173
+ dt, use_shorthand=False, user_display_name="Gary"
174
+ )
175
+ self.assertEqual(timesince, "1\xa0week, 2\xa0days ago by Gary")
176
+ self.assertEqual(
177
+ timesince_last_update(
178
+ dt, use_shorthand=False, user_display_name="Gary", show_time_prefix=True
179
+ ),
180
+ timesince,
181
+ )
182
+
183
+ # 2) use_shorthand=True
184
+
185
+ timesince = timesince_last_update(dt)
186
+ self.assertEqual(timesince, "1\xa0week ago")
187
+ self.assertEqual(timesince_last_update(dt, show_time_prefix=True), timesince)
188
+
189
+ timesince = timesince_last_update(dt, user_display_name="Gary")
190
+ self.assertEqual(timesince, "1\xa0week ago by Gary")
191
+ self.assertEqual(
192
+ timesince_last_update(dt, user_display_name="Gary", show_time_prefix=True),
193
+ timesince,
194
+ )
195
+
196
+ def test_human_readable_date(self):
197
+ now = timezone.now()
198
+ template = """
199
+ {% load wagtailadmin_tags %}
200
+ {% human_readable_date date %}
201
+ """
202
+
203
+ html = Template(template).render(Context({"date": now}))
204
+ self.assertIn("Just now", html)
205
+
206
+ html = Template(template).render(
207
+ Context({"date": now - timedelta(hours=1, minutes=10)})
208
+ )
209
+ self.assertIn("1\xa0hour ago", html)
210
+
211
+
212
+ class TestComponentTag(TestCase):
213
+ def test_passing_context_to_component(self):
214
+ class MyComponent(Component):
215
+ def render_html(self, parent_context):
216
+ return format_html(
217
+ "<h1>{} was here</h1>", parent_context.get("first_name")
218
+ )
219
+
220
+ template = Template(
221
+ "{% load wagtailadmin_tags %}{% with first_name='Kilroy' %}{% component my_component %}{% endwith %}"
222
+ )
223
+ html = template.render(Context({"my_component": MyComponent()}))
224
+ self.assertEqual(html, "<h1>Kilroy was here</h1>")
225
+
226
+ def test_component_escapes_unsafe_strings(self):
227
+ class MyComponent(Component):
228
+ def render_html(self, parent_context):
229
+ return "Look, I'm running with scissors! 8< 8< 8<"
230
+
231
+ template = Template(
232
+ "{% load wagtailadmin_tags %}<h1>{% component my_component %}</h1>"
233
+ )
234
+ html = template.render(Context({"my_component": MyComponent()}))
235
+ self.assertEqual(
236
+ html, "<h1>Look, I&#x27;m running with scissors! 8&lt; 8&lt; 8&lt;</h1>"
237
+ )
238
+
239
+ def test_error_on_rendering_non_component(self):
240
+ template = Template(
241
+ "{% load wagtailadmin_tags %}<h1>{% component my_component %}</h1>"
242
+ )
243
+
244
+ with self.assertRaises(ValueError) as cm:
245
+ template.render(Context({"my_component": "hello"}))
246
+ self.assertEqual(str(cm.exception), "Cannot render 'hello' as a component")
247
+
248
+
249
+ @override_settings(
250
+ WAGTAIL_CONTENT_LANGUAGES=[
251
+ ("en", "English"),
252
+ ("fr", "French"),
253
+ ("ro", "Romanian"),
254
+ ("ru", "Russian"),
255
+ ]
256
+ )
257
+ class TestInternationalisationTags(TestCase):
258
+ def setUp(self):
259
+ self.locale_ids = []
260
+ for language_code in ["en", "fr", "ro", "ru"]:
261
+ locale, _ = Locale.objects.get_or_create(language_code=language_code)
262
+ self.locale_ids.append(locale.pk)
263
+
264
+ def test_i18n_enabled(self):
265
+ with override_settings(WAGTAIL_I18N_ENABLED=False):
266
+ self.assertFalse(i18n_enabled())
267
+
268
+ with override_settings(WAGTAIL_I18N_ENABLED=True):
269
+ self.assertTrue(i18n_enabled())
270
+
271
+ def test_locales(self):
272
+ locales_output = locales_tag()
273
+ self.assertIsInstance(locales_output, str)
274
+ self.assertEqual(
275
+ json.loads(locales_output),
276
+ [
277
+ {"code": "en", "display_name": "English"},
278
+ {"code": "fr", "display_name": "French"},
279
+ {"code": "ro", "display_name": "Romanian"},
280
+ {"code": "ru", "display_name": "Russian"},
281
+ ],
282
+ )
283
+
284
+ def test_locale_label_from_id(self):
285
+ with self.assertNumQueries(1):
286
+ self.assertEqual(locale_label_from_id(self.locale_ids[0]), "English")
287
+
288
+ with self.assertNumQueries(0):
289
+ self.assertEqual(locale_label_from_id(self.locale_ids[1]), "French")
290
+
291
+ # check with an invalid id
292
+ with self.assertNumQueries(0):
293
+ self.assertIsNone(locale_label_from_id(self.locale_ids[-1] + 100), None)
294
+
295
+
296
+ class ComponentTest(TestCase):
297
+ def test_render_block_component(self):
298
+ template = """
299
+ {% load wagtailadmin_tags %}
300
+ {% help_block status="info" %}Proceed with caution{% endhelp_block %}
301
+ """
302
+
303
+ expected = """
304
+ <div class="help-block help-info">
305
+ <svg aria-hidden="true" class="icon icon icon-help"><use href="#icon-help"></svg>
306
+ Proceed with caution
307
+ </div>
308
+ """
309
+
310
+ self.assertHTMLEqual(expected, Template(template).render(Context()))
311
+
312
+ def test_render_nested(self):
313
+ template = """
314
+ {% load wagtailadmin_tags %}
315
+ {% help_block status="warning" %}
316
+ {% help_block status="info" %}Proceed with caution{% endhelp_block %}
317
+ {% endhelp_block %}
318
+ """
319
+
320
+ expected = """
321
+ <div class="help-block help-warning">
322
+ <svg aria-hidden="true" class="icon icon icon-warning"><use href="#icon-warning"></svg>
323
+ <div class="help-block help-info">
324
+ <svg aria-hidden="true" class="icon icon icon-help"><use href="#icon-help"></svg>
325
+ Proceed with caution
326
+ </div>
327
+ </div>
328
+ """
329
+
330
+ self.assertHTMLEqual(expected, Template(template).render(Context()))
331
+
332
+ def test_kwargs_with_filters(self):
333
+ template = """
334
+ {% load wagtailadmin_tags %}
335
+ {% help_block status="warning"|upper %}Proceed with caution{% endhelp_block %}
336
+ """
337
+
338
+ expected = """
339
+ <div class="help-block help-WARNING">
340
+ <svg aria-hidden="true" class="icon icon icon-warning"><use href="#icon-warning"></svg>
341
+ Proceed with caution
342
+ </div>
343
+ """
344
+
345
+ self.assertHTMLEqual(expected, Template(template).render(Context()))
346
+
347
+ def test_render_as_variable(self):
348
+ template = """
349
+ {% load wagtailadmin_tags %}
350
+ {% help_block status="info" as help %}Proceed with caution{% endhelp_block %}
351
+ <template>{{ help }}</template>
352
+ """
353
+
354
+ expected = """
355
+ <template>
356
+ <div class="help-block help-info">
357
+ <svg aria-hidden="true" class="icon icon icon-help"><use href="#icon-help"></svg>
358
+ Proceed with caution
359
+ </div>
360
+ </template>
361
+ """
362
+
363
+ self.assertHTMLEqual(expected, Template(template).render(Context()))
364
+
365
+
366
+ class FragmentTagTest(TestCase):
367
+ def test_basic(self):
368
+ context = Context({})
369
+
370
+ template = """
371
+ {% load wagtailadmin_tags %}
372
+ {% fragment as my_fragment %}
373
+ <p>Hello, World</p>
374
+ {% endfragment %}
375
+ Text coming after:
376
+ {{ my_fragment }}
377
+ """
378
+
379
+ expected = """
380
+ Text coming after:
381
+ <p>Hello, World</p>
382
+ """
383
+
384
+ self.assertHTMLEqual(expected, Template(template).render(context))
385
+
386
+ @override_settings(DEBUG=True)
387
+ def test_syntax_error(self):
388
+ template = """
389
+ {% load wagtailadmin_tags %}
390
+ {% fragment %}
391
+ <p>Hello, World</p>
392
+ {% endfragment %}
393
+ """
394
+
395
+ with self.assertRaises(TemplateSyntaxError):
396
+ Template(template).render(Context())
397
+
398
+ def test_with_variables(self):
399
+ context = Context({"name": "jonathan wells"})
400
+
401
+ template = """
402
+ {% load wagtailadmin_tags %}
403
+ {% fragment as my_fragment %}
404
+ <p>Hello, {{ name|title }}</p>
405
+ {% endfragment %}
406
+ Text coming after:
407
+ {{ my_fragment }}
408
+ """
409
+
410
+ expected = """
411
+ Text coming after:
412
+ <p>Hello, Jonathan Wells</p>
413
+ """
414
+
415
+ self.assertHTMLEqual(expected, Template(template).render(context))
416
+
417
+
418
+ class ClassnamesTagTest(TestCase):
419
+ def test_with_single_arg(self):
420
+ template = """
421
+ {% load wagtailadmin_tags %}
422
+ <p class="{% classnames "w-header" classname %}">Hello!</p>
423
+ """
424
+
425
+ expected = """
426
+ <p class="w-header">Hello!</p>
427
+ """
428
+
429
+ actual = Template(template).render(Context())
430
+
431
+ self.assertHTMLEqual(expected, actual)
432
+
433
+ def test_with_multiple_args(self):
434
+ template = """
435
+ {% load wagtailadmin_tags %}
436
+ <p class="{% classnames "w-header" classname "w-header--merged" "w-header--hasform" %}">
437
+ Hello!
438
+ </p>
439
+ """
440
+
441
+ expected = """
442
+ <p class="w-header w-header--merged w-header--hasform">
443
+ Hello!
444
+ </p>
445
+ """
446
+
447
+ actual = Template(template).render(Context())
448
+
449
+ self.assertHTMLEqual(expected, actual)
450
+
451
+ def test_with_falsy_args(self):
452
+ template = """
453
+ {% load wagtailadmin_tags %}
454
+ <p class="{% classnames "w-header" classname "" %}">Hello!</p>
455
+ """
456
+
457
+ expected = """
458
+ <p class="w-header">Hello!</p>
459
+ """
460
+
461
+ actual = Template(template).render(Context())
462
+
463
+ self.assertEqual(expected.strip(), actual.strip())
464
+
465
+ def test_with_args_with_extra_whitespace(self):
466
+ context = Context(
467
+ {
468
+ "merged": "w-header--merged ",
469
+ "search_form": " w-header--hasform",
470
+ "name": " wagtail ",
471
+ }
472
+ )
473
+
474
+ template = """
475
+ {% load wagtailadmin_tags %}
476
+ <p class="{% classnames "w-header" classname merged search_form name %}">Hello!</p>
477
+ """
478
+
479
+ expected = """
480
+ <p class="w-header w-header--merged w-header--hasform wagtail">Hello!</p>
481
+ """
482
+
483
+ actual = Template(template).render(context)
484
+
485
+ self.assertEqual(expected.strip(), actual.strip())
testbed/wagtail__wagtail/wagtail/admin/tests/test_upgrade_notification.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.test import RequestFactory, TestCase, override_settings
2
+
3
+ from wagtail.admin.views.home import UpgradeNotificationPanel
4
+ from wagtail.test.utils import WagtailTestUtils
5
+
6
+
7
+ class TestUpgradeNotificationPanel(TestCase, WagtailTestUtils):
8
+ DATA_ATTRIBUTE_UPGRADE_CHECK = "data-w-upgrade"
9
+ DATA_ATTRIBUTE_UPGRADE_CHECK_LTS = "data-w-upgrade-lts-only"
10
+
11
+ @classmethod
12
+ def setUpTestData(cls):
13
+ cls.panel = UpgradeNotificationPanel()
14
+ cls.request_factory = RequestFactory()
15
+ cls.user = cls.create_user(username="tester")
16
+ cls.superuser = cls.create_superuser(username="supertester")
17
+ cls.request = cls.request_factory.get("/")
18
+
19
+ def test_get_upgrade_check_setting_default(self):
20
+ self.assertTrue(self.panel.get_upgrade_check_setting())
21
+
22
+ @override_settings(WAGTAIL_ENABLE_UPDATE_CHECK=False)
23
+ def test_get_upgrade_check_setting_false(self):
24
+ self.assertFalse(self.panel.get_upgrade_check_setting())
25
+
26
+ @override_settings(WAGTAIL_ENABLE_UPDATE_CHECK="LTS")
27
+ def test_get_upgrade_check_setting_LTS(self):
28
+ self.assertEqual(self.panel.get_upgrade_check_setting(), "LTS")
29
+
30
+ @override_settings(WAGTAIL_ENABLE_UPDATE_CHECK="lts")
31
+ def test_get_upgrade_check_setting_lts(self):
32
+ self.assertEqual(self.panel.get_upgrade_check_setting(), "lts")
33
+
34
+ def test_upgrade_check_lts_only_default(self):
35
+ self.assertFalse(self.panel.upgrade_check_lts_only())
36
+
37
+ @override_settings(WAGTAIL_ENABLE_UPDATE_CHECK=False)
38
+ def test_upgrade_check_lts_only_setting_true(self):
39
+ self.assertFalse(self.panel.upgrade_check_lts_only())
40
+
41
+ @override_settings(WAGTAIL_ENABLE_UPDATE_CHECK="LTS")
42
+ def test_upgrade_check_lts_only_setting_LTS(self):
43
+ self.assertTrue(self.panel.upgrade_check_lts_only())
44
+
45
+ @override_settings(WAGTAIL_ENABLE_UPDATE_CHECK="lts")
46
+ def test_upgrade_check_lts_only_setting_lts(self):
47
+ self.assertTrue(self.panel.upgrade_check_lts_only())
48
+
49
+ def test_render_html_normal_user(self):
50
+ self.request.user = self.user
51
+ parent_context = {"request": self.request}
52
+
53
+ result = self.panel.render_html(parent_context)
54
+
55
+ self.assertEqual(result, "")
56
+
57
+ def test_render_html_superuser(self):
58
+ self.request.user = self.superuser
59
+ parent_context = {"request": self.request}
60
+
61
+ result = self.panel.render_html(parent_context)
62
+
63
+ self.assertIn(self.DATA_ATTRIBUTE_UPGRADE_CHECK, result)
64
+ self.assertNotIn(self.DATA_ATTRIBUTE_UPGRADE_CHECK_LTS, result)
65
+
66
+ @override_settings(WAGTAIL_ENABLE_UPDATE_CHECK=False)
67
+ def test_render_html_setting_false(self):
68
+ self.request.user = self.superuser
69
+ parent_context = {"request": self.request}
70
+
71
+ result = self.panel.render_html(parent_context)
72
+
73
+ self.assertEqual(result, "")
74
+
75
+ @override_settings(WAGTAIL_ENABLE_UPDATE_CHECK="LTS")
76
+ def test_render_html_setting_LTS(self):
77
+ self.request.user = self.superuser
78
+ parent_context = {"request": self.request}
79
+
80
+ result = self.panel.render_html(parent_context)
81
+
82
+ self.assertIn(self.DATA_ATTRIBUTE_UPGRADE_CHECK, result)
83
+ self.assertIn(self.DATA_ATTRIBUTE_UPGRADE_CHECK_LTS, result)
84
+
85
+ @override_settings(WAGTAIL_ENABLE_UPDATE_CHECK="lts")
86
+ def test_render_html_setting_lts(self):
87
+ self.request.user = self.superuser
88
+ parent_context = {"request": self.request}
89
+
90
+ result = self.panel.render_html(parent_context)
91
+
92
+ self.assertIn(self.DATA_ATTRIBUTE_UPGRADE_CHECK, result)
93
+ self.assertIn(self.DATA_ATTRIBUTE_UPGRADE_CHECK_LTS, result)
testbed/wagtail__wagtail/wagtail/admin/tests/test_userbar.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.contrib.auth.models import AnonymousUser
2
+ from django.template import Context, Template
3
+ from django.test import TestCase
4
+ from django.test.client import RequestFactory
5
+ from django.urls import reverse
6
+
7
+ from wagtail.models import PAGE_TEMPLATE_VAR, Page
8
+ from wagtail.test.testapp.models import BusinessChild, BusinessIndex
9
+ from wagtail.test.utils import WagtailTestUtils
10
+
11
+
12
+ class TestUserbarTag(TestCase, WagtailTestUtils):
13
+ def setUp(self):
14
+ self.user = self.create_superuser(
15
+ username="test", email="test@email.com", password="password"
16
+ )
17
+ self.homepage = Page.objects.get(id=2)
18
+
19
+ def dummy_request(
20
+ self, user=None, *, is_preview=False, in_preview_panel=False, revision_id=None
21
+ ):
22
+ request = RequestFactory().get("/")
23
+ request.user = user or AnonymousUser()
24
+ request.is_preview = is_preview
25
+ request.in_preview_panel = in_preview_panel
26
+ if revision_id:
27
+ request.revision_id = revision_id
28
+ return request
29
+
30
+ def test_userbar_tag(self):
31
+ template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
32
+ context = Context(
33
+ {
34
+ PAGE_TEMPLATE_VAR: self.homepage,
35
+ "request": self.dummy_request(self.user),
36
+ }
37
+ )
38
+ with self.assertNumQueries(5):
39
+ content = template.render(context)
40
+
41
+ self.assertIn("<!-- Wagtail user bar embed code -->", content)
42
+
43
+ def test_userbar_tag_revision(self):
44
+ self.homepage.save_revision(user=self.user, submitted_for_moderation=True)
45
+ revision = self.homepage.get_latest_revision()
46
+ template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
47
+ context = Context(
48
+ {
49
+ PAGE_TEMPLATE_VAR: self.homepage,
50
+ "request": self.dummy_request(self.user, revision_id=revision.id),
51
+ }
52
+ )
53
+ with self.assertNumQueries(7):
54
+ content = template.render(context)
55
+
56
+ self.assertIn("<!-- Wagtail user bar embed code -->", content)
57
+ self.assertIn("Approve", content)
58
+
59
+ def test_userbar_does_not_break_without_request(self):
60
+ template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}boom")
61
+ content = template.render(Context({}))
62
+
63
+ self.assertEqual("boom", content)
64
+
65
+ def test_userbar_tag_self(self):
66
+ """
67
+ Ensure the userbar renders with `self` instead of `PAGE_TEMPLATE_VAR`
68
+ """
69
+ template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
70
+ content = template.render(
71
+ Context(
72
+ {
73
+ "self": self.homepage,
74
+ "request": self.dummy_request(self.user),
75
+ }
76
+ )
77
+ )
78
+
79
+ self.assertIn("<!-- Wagtail user bar embed code -->", content)
80
+
81
+ def test_userbar_tag_anonymous_user(self):
82
+ template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
83
+ content = template.render(
84
+ Context(
85
+ {
86
+ PAGE_TEMPLATE_VAR: self.homepage,
87
+ "request": self.dummy_request(),
88
+ }
89
+ )
90
+ )
91
+
92
+ # Make sure nothing was rendered
93
+ self.assertEqual(content, "")
94
+
95
+ def test_userbar_tag_no_page(self):
96
+ template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
97
+ content = template.render(
98
+ Context(
99
+ {
100
+ "request": self.dummy_request(self.user),
101
+ }
102
+ )
103
+ )
104
+
105
+ self.assertIn("<!-- Wagtail user bar embed code -->", content)
106
+
107
+ def test_edit_link(self):
108
+ template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
109
+ content = template.render(
110
+ Context(
111
+ {
112
+ PAGE_TEMPLATE_VAR: self.homepage,
113
+ "request": self.dummy_request(self.user, is_preview=False),
114
+ }
115
+ )
116
+ )
117
+ self.assertIn("<!-- Wagtail user bar embed code -->", content)
118
+ self.assertIn("Edit this page", content)
119
+
120
+ def test_userbar_edit_menu_not_in_preview(self):
121
+ template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
122
+ content = template.render(
123
+ Context(
124
+ {
125
+ PAGE_TEMPLATE_VAR: self.homepage,
126
+ "request": self.dummy_request(self.user, is_preview=True),
127
+ }
128
+ )
129
+ )
130
+ self.assertIn("<!-- Wagtail user bar embed code -->", content)
131
+ self.assertNotIn("Edit this page", content)
132
+
133
+ def test_userbar_not_in_preview_panel(self):
134
+ template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
135
+ content = template.render(
136
+ Context(
137
+ {
138
+ PAGE_TEMPLATE_VAR: self.homepage,
139
+ "request": self.dummy_request(
140
+ self.user, is_preview=True, in_preview_panel=True
141
+ ),
142
+ }
143
+ )
144
+ )
145
+
146
+ # Make sure nothing was rendered
147
+ self.assertEqual(content, "")
148
+
149
+
150
+ class TestUserbarFrontend(TestCase, WagtailTestUtils):
151
+ def setUp(self):
152
+ self.login()
153
+ self.homepage = Page.objects.get(id=2)
154
+
155
+ def test_userbar_frontend(self):
156
+ response = self.client.get(
157
+ reverse("wagtailadmin_userbar_frontend", args=(self.homepage.id,))
158
+ )
159
+
160
+ self.assertEqual(response.status_code, 200)
161
+ self.assertTemplateUsed(response, "wagtailadmin/userbar/base.html")
162
+
163
+ def test_userbar_frontend_anonymous_user_cannot_see(self):
164
+ # Logout
165
+ self.client.logout()
166
+
167
+ response = self.client.get(
168
+ reverse("wagtailadmin_userbar_frontend", args=(self.homepage.id,))
169
+ )
170
+
171
+ # Check that the user received a forbidden message
172
+ self.assertEqual(response.status_code, 403)
173
+
174
+
175
+ class TestUserbarAddLink(TestCase, WagtailTestUtils):
176
+ fixtures = ["test.json"]
177
+
178
+ def setUp(self):
179
+ self.login()
180
+ self.homepage = Page.objects.get(url_path="/home/")
181
+ self.event_index = Page.objects.get(url_path="/home/events/")
182
+
183
+ self.business_index = BusinessIndex(title="Business", live=True)
184
+ self.homepage.add_child(instance=self.business_index)
185
+
186
+ self.business_child = BusinessChild(title="Business Child", live=True)
187
+ self.business_index.add_child(instance=self.business_child)
188
+
189
+ def test_page_allowing_subpages(self):
190
+ response = self.client.get(
191
+ reverse("wagtailadmin_userbar_frontend", args=(self.event_index.id,))
192
+ )
193
+
194
+ # page allows subpages, so the 'add page' button should show
195
+ expected_url = reverse(
196
+ "wagtailadmin_pages:add_subpage", args=(self.event_index.id,)
197
+ )
198
+ needle = f"""
199
+ <a href="{expected_url}" target="_parent" role="menuitem">
200
+ <svg class="icon icon-plus w-action-icon" aria-hidden="true">
201
+ <use href="#icon-plus"></use>
202
+ </svg>
203
+ Add a child page
204
+ </a>
205
+ """
206
+ self.assertTagInHTML(needle, str(response.content))
207
+
208
+ def test_page_disallowing_subpages(self):
209
+ response = self.client.get(
210
+ reverse("wagtailadmin_userbar_frontend", args=(self.business_child.id,))
211
+ )
212
+
213
+ # page disallows subpages, so the 'add page' button shouldn't show
214
+ expected_url = reverse(
215
+ "wagtailadmin_pages:add_subpage", args=(self.business_index.id,)
216
+ )
217
+ expected_link = (
218
+ '<a href="%s" target="_parent">Add a child page</a>' % expected_url
219
+ )
220
+ self.assertNotContains(response, expected_link)
221
+
222
+
223
+ class TestUserbarModeration(TestCase, WagtailTestUtils):
224
+ def setUp(self):
225
+ self.login()
226
+ self.homepage = Page.objects.get(id=2)
227
+ self.homepage.save_revision(submitted_for_moderation=True)
228
+ self.revision = self.homepage.get_latest_revision()
229
+
230
+ def test_userbar_moderation(self):
231
+ response = self.client.get(
232
+ reverse("wagtailadmin_userbar_moderation", args=(self.revision.id,))
233
+ )
234
+
235
+ self.assertEqual(response.status_code, 200)
236
+ self.assertTemplateUsed(response, "wagtailadmin/userbar/base.html")
237
+
238
+ expected_approve_html = """
239
+ <form action="/admin/pages/moderation/{}/approve/" target="_parent" method="post">
240
+ <input type="hidden" name="csrfmiddlewaretoken">
241
+ <div class="w-action">
242
+ <input type="submit" value="Approve" class="button" />
243
+ </div>
244
+ </form>
245
+ """.format(
246
+ self.revision.id
247
+ )
248
+ self.assertTagInHTML(expected_approve_html, str(response.content))
249
+
250
+ expected_reject_html = """
251
+ <form action="/admin/pages/moderation/{}/reject/" target="_parent" method="post">
252
+ <input type="hidden" name="csrfmiddlewaretoken">
253
+ <div class="w-action">
254
+ <input type="submit" value="Reject" class="button" />
255
+ </div>
256
+ </form>
257
+ """.format(
258
+ self.revision.id
259
+ )
260
+ self.assertTagInHTML(expected_reject_html, str(response.content))
261
+
262
+ def test_userbar_moderation_anonymous_user_cannot_see(self):
263
+ # Logout
264
+ self.client.logout()
265
+
266
+ response = self.client.get(
267
+ reverse("wagtailadmin_userbar_moderation", args=(self.revision.id,))
268
+ )
269
+
270
+ # Check that the user received a forbidden message
271
+ self.assertEqual(response.status_code, 403)
testbed/wagtail__wagtail/wagtail/admin/tests/test_views.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.test import TestCase, override_settings
2
+ from django.urls import reverse
3
+
4
+ from wagtail.admin.forms.auth import PasswordResetForm
5
+ from wagtail.admin.tests.test_forms import CustomPasswordResetForm
6
+ from wagtail.models import Page
7
+ from wagtail.test.utils import WagtailTestUtils
8
+
9
+
10
+ class TestLoginView(TestCase, WagtailTestUtils):
11
+ fixtures = ["test.json"]
12
+
13
+ def setUp(self):
14
+ self.user = self.create_test_user()
15
+ self.homepage = Page.objects.get(url_path="/home/")
16
+
17
+ def test_success_redirect(self):
18
+ response = self.client.post(
19
+ reverse("wagtailadmin_login"),
20
+ {
21
+ "username": "test@email.com",
22
+ "password": "password",
23
+ },
24
+ )
25
+ self.assertRedirects(response, reverse("wagtailadmin_home"))
26
+
27
+ def test_success_redirect_honour_redirect_get_parameter(self):
28
+ homepage_admin_url = reverse("wagtailadmin_pages:edit", args=[self.homepage.pk])
29
+ login_url = reverse("wagtailadmin_login") + "?next={}".format(
30
+ homepage_admin_url
31
+ )
32
+ response = self.client.post(
33
+ login_url,
34
+ {
35
+ "username": "test@email.com",
36
+ "password": "password",
37
+ },
38
+ )
39
+ self.assertRedirects(response, homepage_admin_url)
40
+
41
+ def test_success_redirect_honour_redirect_post_parameter(self):
42
+ homepage_admin_url = reverse("wagtailadmin_pages:edit", args=[self.homepage.pk])
43
+ response = self.client.post(
44
+ reverse("wagtailadmin_login"),
45
+ {
46
+ "username": "test@email.com",
47
+ "password": "password",
48
+ "next": homepage_admin_url,
49
+ },
50
+ )
51
+ self.assertRedirects(response, homepage_admin_url)
52
+
53
+ def test_already_authenticated_redirect(self):
54
+ self.login(username="test@email.com", password="password")
55
+
56
+ response = self.client.get(reverse("wagtailadmin_login"))
57
+ self.assertRedirects(response, reverse("wagtailadmin_home"))
58
+
59
+ def test_already_authenticated_redirect_honour_redirect_get_parameter(self):
60
+ self.login(username="test@email.com", password="password")
61
+
62
+ homepage_admin_url = reverse("wagtailadmin_pages:edit", args=[self.homepage.pk])
63
+ login_url = reverse("wagtailadmin_login") + "?next={}".format(
64
+ homepage_admin_url
65
+ )
66
+ response = self.client.get(login_url)
67
+ self.assertRedirects(response, homepage_admin_url)
68
+
69
+ @override_settings(LANGUAGE_CODE="de")
70
+ def test_language_code(self):
71
+ response = self.client.get(reverse("wagtailadmin_login"))
72
+ self.assertContains(response, '<html lang="de" dir="ltr">')
73
+
74
+ @override_settings(LANGUAGE_CODE="he")
75
+ def test_bidi_language_changes_dir_attribute(self):
76
+ response = self.client.get(reverse("wagtailadmin_login"))
77
+ self.assertContains(response, '<html lang="he" dir="rtl">')
78
+
79
+ @override_settings(
80
+ WAGTAILADMIN_USER_LOGIN_FORM="wagtail.admin.tests.test_forms.CustomLoginForm"
81
+ )
82
+ def test_login_page_renders_extra_fields(self):
83
+ response = self.client.get(reverse("wagtailadmin_login"))
84
+ self.assertContains(
85
+ response, '<input type="text" name="captcha" required id="id_captcha">'
86
+ )
87
+
88
+ def test_session_expire_on_browser_close(self):
89
+ self.client.post(
90
+ reverse("wagtailadmin_login"),
91
+ {
92
+ "username": "test@email.com",
93
+ "password": "password",
94
+ },
95
+ )
96
+ self.assertTrue(self.client.session.get_expire_at_browser_close())
97
+
98
+ @override_settings(SESSION_COOKIE_AGE=7)
99
+ def test_session_expiry_remember(self):
100
+ self.client.post(
101
+ reverse("wagtailadmin_login"),
102
+ {"username": "test@email.com", "password": "password", "remember": True},
103
+ )
104
+ self.assertFalse(self.client.session.get_expire_at_browser_close())
105
+ self.assertEqual(self.client.session.get_expiry_age(), 7)
106
+
107
+
108
+ class TestPasswordResetView(TestCase):
109
+ def test_password_reset_view_uses_correct_form(self):
110
+ response = self.client.get(reverse("wagtailadmin_password_reset"))
111
+ self.assertIsInstance(response.context.get("form"), PasswordResetForm)
112
+
113
+ with override_settings(
114
+ WAGTAILADMIN_USER_PASSWORD_RESET_FORM="wagtail.admin.tests.test_forms.CustomPasswordResetForm"
115
+ ):
116
+ response = self.client.get(reverse("wagtailadmin_password_reset"))
117
+ self.assertIsInstance(response.context.get("form"), CustomPasswordResetForm)
118
+
119
+ @override_settings(
120
+ WAGTAILADMIN_USER_PASSWORD_RESET_FORM="wagtail.admin.tests.test_forms.CustomPasswordResetForm"
121
+ )
122
+ def test_password_reset_page_renders_extra_fields(self):
123
+ response = self.client.get(reverse("wagtailadmin_password_reset"))
124
+ self.assertContains(
125
+ response, '<input type="text" name="captcha" required id="id_captcha">'
126
+ )
testbed/wagtail__wagtail/wagtail/admin/tests/test_views_generic.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.contrib.admin.utils import quote
2
+ from django.test import TestCase
3
+ from django.urls import reverse
4
+
5
+ from wagtail.test.utils import WagtailTestUtils
6
+
7
+
8
+ class TestGenericIndexView(TestCase, WagtailTestUtils):
9
+
10
+ fixtures = ["test.json"]
11
+
12
+ def get(self, params={}):
13
+ return self.client.get(reverse("testapp_generic_index"), params)
14
+
15
+ def test_non_integer_primary_key(self):
16
+ response = self.get()
17
+ self.assertEqual(response.status_code, 200)
18
+ response_object_count = response.context_data["object_list"].count()
19
+ self.assertEqual(response_object_count, 3)
20
+ self.assertContains(response, "first modelwithstringtypeprimarykey model")
21
+ self.assertContains(response, "second modelwithstringtypeprimarykey model")
22
+
23
+
24
+ class TestGenericEditView(TestCase, WagtailTestUtils):
25
+
26
+ fixtures = ["test.json"]
27
+
28
+ def get(self, object_pk, params={}):
29
+ return self.client.get(
30
+ reverse("testapp_generic_edit", args=(object_pk,)), params
31
+ )
32
+
33
+ def test_non_integer_primary_key(self):
34
+ response = self.get("string-pk-2")
35
+ self.assertEqual(response.status_code, 200)
36
+ self.assertContains(response, "second modelwithstringtypeprimarykey model")
37
+
38
+ def test_non_url_safe_primary_key(self):
39
+ object_pk = 'string-pk-:#?;@&=+$,"[]<>%'
40
+ response = self.get(quote(object_pk))
41
+ self.assertEqual(response.status_code, 200)
42
+ self.assertContains(
43
+ response, "non-url-safe pk modelwithstringtypeprimarykey model"
44
+ )
45
+
46
+ def test_using_quote_in_edit_url(self):
47
+ object_pk = 'string-pk-:#?;@&=+$,"[]<>%'
48
+ response = self.get(quote(object_pk))
49
+ edit_url = response.context_data["action_url"]
50
+ edit_url_pk = edit_url.split("/")[-2]
51
+ self.assertEqual(edit_url_pk, quote(object_pk))
52
+
53
+ def test_using_quote_in_delete_url(self):
54
+ object_pk = 'string-pk-:#?;@&=+$,"[]<>%'
55
+ response = self.get(quote(object_pk))
56
+ delete_url = response.context_data["delete_url"]
57
+ delete_url_pk = delete_url.split("/")[-2]
58
+ self.assertEqual(delete_url_pk, quote(object_pk))
59
+
60
+
61
+ class TestGenericDeleteView(TestCase, WagtailTestUtils):
62
+
63
+ fixtures = ["test.json"]
64
+
65
+ def get(self, object_pk, params={}):
66
+ return self.client.get(
67
+ reverse("testapp_generic_edit", args=(object_pk,)), params
68
+ )
69
+
70
+ def test_with_non_integer_primary_key(self):
71
+ response = self.get("string-pk-2")
72
+ self.assertEqual(response.status_code, 200)
73
+
74
+ def test_with_non_url_safe_primary_key(self):
75
+ object_pk = 'string-pk-:#?;@&=+$,"[]<>%'
76
+ response = self.get(quote(object_pk))
77
+ self.assertEqual(response.status_code, 200)
testbed/wagtail__wagtail/wagtail/admin/tests/test_whats_new.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.test import RequestFactory, TestCase, override_settings
2
+ from django.urls import reverse
3
+
4
+ from wagtail.admin.views.home import WhatsNewInWagtailVersionPanel
5
+ from wagtail.test.utils import WagtailTestUtils
6
+ from wagtail.users.models import UserProfile
7
+
8
+
9
+ class TestWhatsNewInWagtailVersionPanel(TestCase, WagtailTestUtils):
10
+ @classmethod
11
+ def setUpTestData(cls):
12
+ cls.panel = WhatsNewInWagtailVersionPanel()
13
+ cls.dismissible_id = cls.panel.get_dismissible_id()
14
+ cls.request_factory = RequestFactory()
15
+ cls.user = cls.create_user(username="tester")
16
+ cls.profile = UserProfile.get_for_user(cls.user)
17
+
18
+ def get_parent_context(self):
19
+ request = self.request_factory.get("/")
20
+ request.user = self.user
21
+ return {"request": request}
22
+
23
+ def test_get_whats_new_banner_setting_default(self):
24
+ self.assertTrue(self.panel.get_whats_new_banner_setting())
25
+
26
+ @override_settings(WAGTAIL_ENABLE_WHATS_NEW_BANNER=False)
27
+ def test_get_whats_new_banner_setting_false(self):
28
+ self.assertFalse(self.panel.get_whats_new_banner_setting())
29
+
30
+ def test_render_html_user_initial(self):
31
+ result = self.panel.render_html(self.get_parent_context())
32
+ self.assertIn(
33
+ f'<section class="w-whats-new w-dismissible" aria-labelledby="whats-new-heading" data-wagtail-dismissible-id="{self.dismissible_id}">',
34
+ result,
35
+ )
36
+ self.assertIn("Things in Wagtail 4 have changed!", result)
37
+
38
+ @override_settings(WAGTAIL_ENABLE_WHATS_NEW_BANNER=False)
39
+ def test_render_html_setting_false(self):
40
+ result = self.panel.render_html(self.get_parent_context())
41
+ self.assertEqual(result, "")
42
+
43
+ def test_render_html_user_no_profile(self):
44
+ self.profile.delete()
45
+ self.user.refresh_from_db()
46
+ result = self.panel.render_html(self.get_parent_context())
47
+ self.assertIn(
48
+ f'<section class="w-whats-new w-dismissible" aria-labelledby="whats-new-heading" data-wagtail-dismissible-id="{self.dismissible_id}">',
49
+ result,
50
+ )
51
+ self.assertIn("Things in Wagtail 4 have changed!", result)
52
+
53
+ def test_render_html_user_dismissed(self):
54
+ self.profile.dismissibles[self.dismissible_id] = True
55
+ self.profile.save(update_fields=["dismissibles"])
56
+ result = self.panel.render_html(self.get_parent_context())
57
+ self.assertEqual(result, "")
58
+
59
+
60
+ class TestWhatsNewOnDashboard(TestCase, WagtailTestUtils):
61
+ """Test 'What's New In Wagtail' banner rendered by `wagtailadmin_home` view"""
62
+
63
+ def setUp(self):
64
+ self.user = self.login()
65
+ self.profile = UserProfile.get_for_user(self.user)
66
+ self.dismissible_id = WhatsNewInWagtailVersionPanel().get_dismissible_id()
67
+
68
+ def get(self):
69
+ return self.client.get(reverse("wagtailadmin_home"))
70
+
71
+ def test_get_enabled_initial(self):
72
+ response = self.get()
73
+ self.assertContains(
74
+ response,
75
+ f'<section class="w-whats-new w-dismissible" aria-labelledby="whats-new-heading" data-wagtail-dismissible-id="{self.dismissible_id}">',
76
+ )
77
+ self.assertContains(response, "Things in Wagtail 4 have changed!")
78
+
79
+ @override_settings(WAGTAIL_ENABLE_WHATS_NEW_BANNER=False)
80
+ def test_get_disabled_initial(self):
81
+ response = self.get()
82
+ self.assertNotContains(
83
+ response,
84
+ f'<section class="w-whats-new w-dismissible" aria-labelledby="whats-new-heading" data-wagtail-dismissible-id="{self.dismissible_id}">',
85
+ )
86
+ self.assertNotContains(response, "Things in Wagtail 4 have changed!")
87
+
88
+ def test_render_html_user_no_profile(self):
89
+ self.profile.delete()
90
+ self.user.refresh_from_db()
91
+ response = self.get()
92
+ self.assertContains(
93
+ response,
94
+ f'<section class="w-whats-new w-dismissible" aria-labelledby="whats-new-heading" data-wagtail-dismissible-id="{self.dismissible_id}">',
95
+ )
96
+ self.assertContains(response, "Things in Wagtail 4 have changed!")
97
+
98
+ def test_get_enabled_dismissed(self):
99
+ self.profile.dismissibles[self.dismissible_id] = True
100
+ self.profile.save(update_fields=["dismissibles"])
101
+
102
+ response = self.get()
103
+ self.assertNotContains(
104
+ response,
105
+ f'<section class="w-whats-new w-dismissible" aria-labelledby="whats-new-heading" data-wagtail-dismissible-id="{self.dismissible_id}">',
106
+ )
107
+ self.assertNotContains(response, "Things in Wagtail 4 have changed!")
testbed/wagtail__wagtail/wagtail/admin/tests/test_widgets.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ from django import forms
4
+ from django.test import TestCase
5
+ from django.test.utils import override_settings
6
+
7
+ from wagtail.admin import widgets
8
+ from wagtail.admin.forms.tags import TagField
9
+ from wagtail.models import Page
10
+ from wagtail.test.testapp.forms import AdminStarDateInput
11
+ from wagtail.test.testapp.models import EventPage, RestaurantTag, SimplePage
12
+
13
+
14
+ class TestAdminPageChooserWidget(TestCase):
15
+ def setUp(self):
16
+ self.root_page = Page.objects.get(id=2)
17
+
18
+ # Add child page
19
+ self.child_page = SimplePage(
20
+ title="foobarbaz",
21
+ content="hello",
22
+ )
23
+ self.root_page.add_child(instance=self.child_page)
24
+
25
+ def test_not_hidden(self):
26
+ widget = widgets.AdminPageChooser()
27
+ self.assertFalse(widget.is_hidden)
28
+
29
+ def test_adapt(self):
30
+ widget = widgets.AdminPageChooser()
31
+
32
+ js_args = widgets.PageChooserAdapter().js_args(widget)
33
+ self.assertInHTML(
34
+ """<input id="__ID__" name="__NAME__" type="hidden" />""", js_args[0]
35
+ )
36
+ self.assertIn(">Choose a page<", js_args[0])
37
+ self.assertEqual(js_args[1], "__ID__")
38
+ self.assertEqual(
39
+ js_args[2],
40
+ {
41
+ "can_choose_root": False,
42
+ "model_names": ["wagtailcore.page"],
43
+ "user_perms": None,
44
+ },
45
+ )
46
+
47
+ def test_adapt_with_target_model(self):
48
+ widget = widgets.AdminPageChooser(target_models=[SimplePage, EventPage])
49
+
50
+ js_args = widgets.PageChooserAdapter().js_args(widget)
51
+ self.assertEqual(
52
+ js_args[2]["model_names"], ["tests.simplepage", "tests.eventpage"]
53
+ )
54
+
55
+ def test_adapt_with_can_choose_root(self):
56
+ widget = widgets.AdminPageChooser(can_choose_root=True)
57
+
58
+ js_args = widgets.PageChooserAdapter().js_args(widget)
59
+ self.assertTrue(js_args[2]["can_choose_root"])
60
+
61
+ def test_render_html(self):
62
+ # render_html is mostly an internal API, but we do want to support calling it with None as
63
+ # a value, to render a blank field without the JS initialiser (so that we can call that
64
+ # separately in our own context and hold on to the return value)
65
+ widget = widgets.AdminPageChooser()
66
+
67
+ html = widget.render_html("test", None, {})
68
+ self.assertInHTML("""<input name="test" type="hidden" />""", html)
69
+ self.assertIn(">Choose a page<", html)
70
+
71
+ def test_render_js_init(self):
72
+ widget = widgets.AdminPageChooser()
73
+
74
+ html = widget.render("test", None, {"id": "test-id"})
75
+ self.assertIn(
76
+ 'new PageChooser("test-id", null, {"model_names": ["wagtailcore.page"], "can_choose_root": false, "user_perms": null});',
77
+ html,
78
+ )
79
+
80
+ def test_render_js_init_with_user_perm(self):
81
+ widget = widgets.AdminPageChooser(user_perms="copy_to")
82
+
83
+ html = widget.render("test", None, {"id": "test-id"})
84
+ self.assertIn(
85
+ 'new PageChooser("test-id", null, {"model_names": ["wagtailcore.page"], "can_choose_root": false, "user_perms": "copy_to"});',
86
+ html,
87
+ )
88
+
89
+ def test_render_with_value(self):
90
+ widget = widgets.AdminPageChooser()
91
+
92
+ html = widget.render("test", self.child_page, {"id": "test-id"})
93
+ self.assertInHTML(
94
+ """<input id="test-id" name="test" type="hidden" value="%d" />"""
95
+ % self.child_page.id,
96
+ html,
97
+ )
98
+ # SimplePage has a custom get_admin_display_title method which should be reflected here
99
+ self.assertInHTML("foobarbaz (simple page)", html)
100
+
101
+ self.assertIn(
102
+ 'new PageChooser("test-id", %d, {"model_names": ["wagtailcore.page"], "can_choose_root": false, "user_perms": null});'
103
+ % self.root_page.id,
104
+ html,
105
+ )
106
+
107
+ def test_render_with_target_model(self):
108
+ widget = widgets.AdminPageChooser(target_models=[SimplePage])
109
+
110
+ html = widget.render("test", None, {"id": "test-id"})
111
+ self.assertIn(
112
+ 'new PageChooser("test-id", null, {"model_names": ["tests.simplepage"], "can_choose_root": false, "user_perms": null});',
113
+ html,
114
+ )
115
+
116
+ html = widget.render("test", self.child_page, {"id": "test-id"})
117
+ self.assertIn(">Choose a page (Simple Page)<", html)
118
+
119
+ def test_render_with_target_model_as_single_instance(self):
120
+ widget = widgets.AdminPageChooser(target_models=SimplePage)
121
+
122
+ html = widget.render("test", None, {"id": "test-id"})
123
+ self.assertIn(
124
+ 'new PageChooser("test-id", null, {"model_names": ["tests.simplepage"], "can_choose_root": false, "user_perms": null});',
125
+ html,
126
+ )
127
+
128
+ html = widget.render("test", self.child_page, {"id": "test-id"})
129
+ self.assertIn(">Choose a page (Simple Page)<", html)
130
+
131
+ def test_render_with_target_model_as_single_string(self):
132
+ widget = widgets.AdminPageChooser(target_models="tests.SimplePage")
133
+
134
+ html = widget.render("test", None, {"id": "test-id"})
135
+ self.assertIn(
136
+ 'new PageChooser("test-id", null, {"model_names": ["tests.simplepage"], "can_choose_root": false, "user_perms": null});',
137
+ html,
138
+ )
139
+
140
+ html = widget.render("test", self.child_page, {"id": "test-id"})
141
+ self.assertIn(">Choose a page (Simple Page)<", html)
142
+
143
+ def test_render_with_multiple_target_models(self):
144
+ target_models = [SimplePage, "tests.eventpage"]
145
+ widget = widgets.AdminPageChooser(target_models=target_models)
146
+
147
+ html = widget.render("test", None, {"id": "test-id"})
148
+ self.assertIn(
149
+ 'new PageChooser("test-id", null, {"model_names": ["tests.simplepage", "tests.eventpage"], "can_choose_root": false, "user_perms": null});',
150
+ html,
151
+ )
152
+
153
+ html = widget.render("test", self.child_page, {"id": "test-id"})
154
+ self.assertIn(">Choose a page<", html)
155
+
156
+ def test_render_js_init_with_can_choose_root(self):
157
+ widget = widgets.AdminPageChooser(can_choose_root=True)
158
+
159
+ html = widget.render("test", self.child_page, {"id": "test-id"})
160
+ self.assertIn(
161
+ 'new PageChooser("test-id", %d, {"model_names": ["wagtailcore.page"], "can_choose_root": true, "user_perms": null});'
162
+ % self.root_page.id,
163
+ html,
164
+ )
165
+
166
+
167
+ class TestAdminDateInput(TestCase):
168
+ def test_adapt(self):
169
+ widget = widgets.AdminDateInput()
170
+
171
+ js_args = widgets.AdminDateInputAdapter().js_args(widget)
172
+
173
+ self.assertEqual(js_args[0], {"dayOfWeekStart": 0, "format": "Y-m-d"})
174
+
175
+ def test_adapt_with_custom_format(self):
176
+ widget = widgets.AdminDateInput(format="%d.%m.%Y")
177
+
178
+ js_args = widgets.AdminDateInputAdapter().js_args(widget)
179
+
180
+ self.assertEqual(js_args[0], {"dayOfWeekStart": 0, "format": "d.m.Y"})
181
+
182
+ def test_render_js_init(self):
183
+ widget = widgets.AdminDateInput()
184
+
185
+ html = widget.render("test", None, attrs={"id": "test-id"})
186
+
187
+ self.assertInHTML(
188
+ '<input type="text" name="test" autocomplete="off" id="test-id" />', html
189
+ )
190
+
191
+ # we should see the JS initialiser code:
192
+ # initDateChooser("test-id", {"dayOfWeekStart": 0, "format": "Y-m-d"});
193
+ # except that we can't predict the order of the config options
194
+ self.assertIn('initDateChooser("test\\u002Did", {', html)
195
+ self.assertIn('"dayOfWeekStart": 0', html)
196
+ self.assertIn('"format": "Y-m-d"', html)
197
+
198
+ def test_render_js_init_with_format(self):
199
+ widget = widgets.AdminDateInput(format="%d.%m.%Y.")
200
+
201
+ html = widget.render("test", None, attrs={"id": "test-id"})
202
+ self.assertIn(
203
+ '"format": "d.m.Y."',
204
+ html,
205
+ )
206
+
207
+ @override_settings(WAGTAIL_DATE_FORMAT="%d.%m.%Y.")
208
+ def test_render_js_init_with_format_from_settings(self):
209
+ widget = widgets.AdminDateInput()
210
+
211
+ html = widget.render("test", None, attrs={"id": "test-id"})
212
+ self.assertIn(
213
+ '"format": "d.m.Y."',
214
+ html,
215
+ )
216
+
217
+ def test_media_inheritance(self):
218
+ """
219
+ Widgets inheriting from AdminDateInput should have their media definitions merged
220
+ with AdminDateInput's
221
+ """
222
+ widget = AdminStarDateInput()
223
+ media_html = str(widget.media)
224
+ self.assertIn("wagtailadmin/js/date-time-chooser.js", media_html)
225
+ self.assertIn("vendor/star_date.js", media_html)
226
+
227
+
228
+ class TestAdminTimeInput(TestCase):
229
+ def test_adapt(self):
230
+ widget = widgets.AdminTimeInput()
231
+
232
+ js_args = widgets.AdminTimeInputAdapter().js_args(widget)
233
+
234
+ self.assertEqual(js_args[0], {"format": "H:i", "formatTime": "H:i"})
235
+
236
+ def test_adapt_with_custom_format(self):
237
+ widget = widgets.AdminTimeInput(format="%H:%M:%S")
238
+
239
+ js_args = widgets.AdminTimeInputAdapter().js_args(widget)
240
+
241
+ self.assertEqual(js_args[0], {"format": "H:i:s", "formatTime": "H:i:s"})
242
+
243
+ def test_render_js_init(self):
244
+ widget = widgets.AdminTimeInput()
245
+
246
+ html = widget.render("test", None, attrs={"id": "test-id"})
247
+
248
+ self.assertInHTML(
249
+ '<input type="text" name="test" autocomplete="off" id="test-id" />', html
250
+ )
251
+
252
+ # we should see the JS initialiser code:
253
+ # initDateChooser("test-id", {"dayOfWeekStart": 0, "format": "Y-m-d"});
254
+ # except that we can't predict the order of the config options
255
+ self.assertIn('initTimeChooser("test\\u002Did", {', html)
256
+ self.assertIn('"format": "H:i"', html)
257
+
258
+ def test_render_js_init_with_format(self):
259
+ widget = widgets.AdminTimeInput(format="%H:%M:%S")
260
+
261
+ html = widget.render("test", None, attrs={"id": "test-id"})
262
+ self.assertIn(
263
+ '"format": "H:i:s"',
264
+ html,
265
+ )
266
+
267
+ @override_settings(WAGTAIL_TIME_FORMAT="%H:%M:%S")
268
+ def test_render_js_init_with_format_from_settings(self):
269
+ widget = widgets.AdminTimeInput()
270
+
271
+ html = widget.render("test", None, attrs={"id": "test-id"})
272
+ self.assertIn(
273
+ '"format": "H:i:s"',
274
+ html,
275
+ )
276
+
277
+
278
+ class TestAdminDateTimeInput(TestCase):
279
+ def test_adapt(self):
280
+ widget = widgets.AdminDateTimeInput()
281
+
282
+ js_args = widgets.AdminDateTimeInputAdapter().js_args(widget)
283
+
284
+ self.assertEqual(
285
+ js_args[0],
286
+ {
287
+ "dayOfWeekStart": 0,
288
+ "format": "Y-m-d H:i",
289
+ "formatTime": "H:i",
290
+ "parentID": "body",
291
+ },
292
+ )
293
+
294
+ def test_adapt_with_custom_format(self):
295
+ widget = widgets.AdminDateTimeInput(
296
+ format="%d.%m.%Y. %H:%M", time_format="%H:%M %p"
297
+ )
298
+
299
+ js_args = widgets.AdminDateTimeInputAdapter().js_args(widget)
300
+
301
+ self.assertEqual(
302
+ js_args[0],
303
+ {
304
+ "dayOfWeekStart": 0,
305
+ "format": "d.m.Y. H:i",
306
+ "formatTime": "H:i A",
307
+ "parentID": "body",
308
+ },
309
+ )
310
+
311
+ def test_adapt_with_custom_parent_selector(self):
312
+ widget = widgets.AdminDateTimeInput(
313
+ js_overlay_parent_selector="#test-parent-id"
314
+ )
315
+
316
+ js_args = widgets.AdminDateTimeInputAdapter().js_args(widget)
317
+
318
+ self.assertEqual(
319
+ js_args[0],
320
+ {
321
+ "dayOfWeekStart": 0,
322
+ "format": "Y-m-d H:i",
323
+ "formatTime": "H:i",
324
+ "parentID": "#test-parent-id",
325
+ },
326
+ )
327
+
328
+ def test_render_js_init(self):
329
+ widget = widgets.AdminDateTimeInput()
330
+
331
+ html = widget.render("test", None, attrs={"id": "test-id"})
332
+
333
+ self.assertInHTML(
334
+ '<input type="text" name="test" autocomplete="off" id="test-id" />', html
335
+ )
336
+
337
+ # we should see the JS initialiser code:
338
+ # initDateTimeChooser("test-id", {"dayOfWeekStart": 0, "format": "Y-m-d H:i"});
339
+ # except that we can't predict the order of the config options
340
+ self.assertIn('initDateTimeChooser("test\\u002Did", {', html)
341
+ self.assertIn('"dayOfWeekStart": 0', html)
342
+ self.assertIn('"format": "Y-m-d H:i"', html)
343
+ self.assertIn('"formatTime": "H:i"', html)
344
+ self.assertIn('"parentID": "body"', html)
345
+
346
+ def test_render_js_init_with_format(self):
347
+ widget = widgets.AdminDateTimeInput(
348
+ format="%d.%m.%Y. %H:%M", time_format="%H:%M %p"
349
+ )
350
+
351
+ html = widget.render("test", None, attrs={"id": "test-id"})
352
+ self.assertIn(
353
+ '"format": "d.m.Y. H:i"',
354
+ html,
355
+ )
356
+ self.assertIn(
357
+ '"formatTime": "H:i A"',
358
+ html,
359
+ )
360
+
361
+ @override_settings(
362
+ WAGTAIL_DATETIME_FORMAT="%d.%m.%Y. %H:%M", WAGTAIL_TIME_FORMAT="%H:%M %p"
363
+ )
364
+ def test_render_js_init_with_format_from_settings(self):
365
+ widget = widgets.AdminDateTimeInput()
366
+
367
+ html = widget.render("test", None, attrs={"id": "test-id"})
368
+ self.assertIn(
369
+ '"format": "d.m.Y. H:i"',
370
+ html,
371
+ )
372
+ self.assertIn(
373
+ '"formatTime": "H:i A"',
374
+ html,
375
+ )
376
+
377
+
378
+ class TestAdminTagWidget(TestCase):
379
+ def get_js_init_params(self, html):
380
+ """Returns a list of the params passed in to initTagField from the supplied HTML"""
381
+ # example - ["test_id", "/admin/tag-autocomplete/", {'allowSpaces': True}]
382
+ start = "initTagField("
383
+ end = ");"
384
+ items_after_init = html.split(start)[1]
385
+ if items_after_init:
386
+ params_raw = items_after_init.split(end)[0]
387
+ if params_raw:
388
+ # stuff parameter string into an array so that we can unpack it as JSON
389
+ return json.loads("[%s]" % params_raw)
390
+ return []
391
+
392
+ def get_help_text_html_element(self, html):
393
+ """Return a help text html element with content as string"""
394
+ start = """<input type="text" name="tags">"""
395
+ end = "<script>"
396
+ items_after_input_tag = html.split(start)[1]
397
+ if items_after_input_tag:
398
+ help_text_element = items_after_input_tag.split(end)[0].strip()
399
+ return help_text_element
400
+ return []
401
+
402
+ def test_render_js_init_basic(self):
403
+ """Checks that the 'initTagField' is correctly added to the inline script for tag widgets"""
404
+ widget = widgets.AdminTagWidget()
405
+
406
+ html = widget.render("tags", None, attrs={"id": "alpha"})
407
+ params = self.get_js_init_params(html)
408
+
409
+ self.assertEqual(
410
+ params,
411
+ [
412
+ "alpha",
413
+ "/admin/tag-autocomplete/",
414
+ {"allowSpaces": True, "tagLimit": None, "autocompleteOnly": False},
415
+ ],
416
+ )
417
+
418
+ @override_settings(TAG_SPACES_ALLOWED=False)
419
+ def test_render_js_init_no_spaces_allowed(self):
420
+ """Checks that the 'initTagField' includes the correct value based on TAG_SPACES_ALLOWED in settings"""
421
+ widget = widgets.AdminTagWidget()
422
+
423
+ html = widget.render("tags", None, attrs={"id": "alpha"})
424
+ params = self.get_js_init_params(html)
425
+
426
+ self.assertEqual(
427
+ params,
428
+ [
429
+ "alpha",
430
+ "/admin/tag-autocomplete/",
431
+ {"allowSpaces": False, "tagLimit": None, "autocompleteOnly": False},
432
+ ],
433
+ )
434
+
435
+ @override_settings(TAG_LIMIT=5)
436
+ def test_render_js_init_with_tag_limit(self):
437
+ """Checks that the 'initTagField' includes the correct value based on TAG_LIMIT in settings"""
438
+ widget = widgets.AdminTagWidget()
439
+
440
+ html = widget.render("tags", None, attrs={"id": "alpha"})
441
+ params = self.get_js_init_params(html)
442
+
443
+ self.assertEqual(
444
+ params,
445
+ [
446
+ "alpha",
447
+ "/admin/tag-autocomplete/",
448
+ {"allowSpaces": True, "tagLimit": 5, "autocompleteOnly": False},
449
+ ],
450
+ )
451
+
452
+ def test_render_js_init_with_tag_model(self):
453
+ """
454
+ Checks that 'initTagField' is passed the correct autocomplete URL for the custom model,
455
+ and sets autocompleteOnly according to that model's free_tagging attribute
456
+ """
457
+ widget = widgets.AdminTagWidget(tag_model=RestaurantTag)
458
+
459
+ html = widget.render("tags", None, attrs={"id": "alpha"})
460
+ params = self.get_js_init_params(html)
461
+
462
+ self.assertEqual(
463
+ params,
464
+ [
465
+ "alpha",
466
+ "/admin/tag-autocomplete/tests/restauranttag/",
467
+ {"allowSpaces": True, "tagLimit": None, "autocompleteOnly": True},
468
+ ],
469
+ )
470
+
471
+ def test_render_with_free_tagging_false(self):
472
+ """Checks that free_tagging=False is passed to the inline script"""
473
+ widget = widgets.AdminTagWidget(free_tagging=False)
474
+
475
+ html = widget.render("tags", None, attrs={"id": "alpha"})
476
+ params = self.get_js_init_params(html)
477
+
478
+ self.assertEqual(
479
+ params,
480
+ [
481
+ "alpha",
482
+ "/admin/tag-autocomplete/",
483
+ {"allowSpaces": True, "tagLimit": None, "autocompleteOnly": True},
484
+ ],
485
+ )
486
+
487
+ def test_render_with_free_tagging_true(self):
488
+ """free_tagging=True on the widget can also override the tag model setting free_tagging=False"""
489
+ widget = widgets.AdminTagWidget(tag_model=RestaurantTag, free_tagging=True)
490
+
491
+ html = widget.render("tags", None, attrs={"id": "alpha"})
492
+ params = self.get_js_init_params(html)
493
+
494
+ self.assertEqual(
495
+ params,
496
+ [
497
+ "alpha",
498
+ "/admin/tag-autocomplete/tests/restauranttag/",
499
+ {"allowSpaces": True, "tagLimit": None, "autocompleteOnly": False},
500
+ ],
501
+ )
502
+
503
+ @override_settings(TAG_SPACES_ALLOWED=True)
504
+ def test_tags_help_text_spaces_allowed(self):
505
+ """Checks that the tags help text html element content is correct when TAG_SPACES_ALLOWED is True"""
506
+ widget = widgets.AdminTagWidget()
507
+ help_text = widget.get_context(None, None, {})["widget"]["help_text"]
508
+
509
+ html = widget.render("tags", None, {})
510
+ help_text_html_element = self.get_help_text_html_element(html)
511
+
512
+ self.assertEqual(
513
+ help_text,
514
+ 'Multi-word tags with spaces will automatically be enclosed in double quotes (").',
515
+ )
516
+
517
+ self.assertHTMLEqual(
518
+ help_text_html_element,
519
+ """<p class="help">%s</p>""" % help_text,
520
+ )
521
+
522
+ @override_settings(TAG_SPACES_ALLOWED=False)
523
+ def test_tags_help_text_no_spaces_allowed(self):
524
+ """Checks that the tags help text html element content is correct when TAG_SPACES_ALLOWED is False"""
525
+ widget = widgets.AdminTagWidget()
526
+ help_text = widget.get_context(None, None, {})["widget"]["help_text"]
527
+
528
+ html = widget.render("tags", None, {})
529
+ help_text_html_element = self.get_help_text_html_element(html)
530
+
531
+ self.assertEqual(
532
+ help_text, "Tags can only consist of a single word, no spaces allowed."
533
+ )
534
+
535
+ self.assertHTMLEqual(
536
+ help_text_html_element,
537
+ """<p class="help">%s</p>""" % help_text,
538
+ )
539
+
540
+
541
+ class TestTagField(TestCase):
542
+ def setUp(self):
543
+ RestaurantTag.objects.create(name="Italian", slug="italian")
544
+ RestaurantTag.objects.create(name="Indian", slug="indian")
545
+
546
+ def test_tag_whitelisting(self):
547
+ class RestaurantTagForm(forms.Form):
548
+ # RestaurantTag sets free_tagging=False at the model level
549
+ tags = TagField(tag_model=RestaurantTag)
550
+
551
+ form = RestaurantTagForm({"tags": "Italian, delicious"})
552
+ self.assertTrue(form.is_valid())
553
+ self.assertEqual(form.cleaned_data["tags"], ["Italian"])
554
+
555
+ def test_override_free_tagging(self):
556
+ class RestaurantTagForm(forms.Form):
557
+ tags = TagField(tag_model=RestaurantTag, free_tagging=True)
558
+
559
+ form = RestaurantTagForm({"tags": "Italian, delicious"})
560
+ self.assertTrue(form.is_valid())
561
+ self.assertEqual(set(form.cleaned_data["tags"]), {"Italian", "delicious"})
562
+
563
+ def test_tag_over_one_hundred_characters(self):
564
+ class RestaurantTagForm(forms.Form):
565
+ tags = TagField(tag_model=RestaurantTag)
566
+
567
+ tag_name = ""
568
+ for _ in range(101):
569
+ tag_name += "a"
570
+ form = RestaurantTagForm({"tags": tag_name})
571
+ self.assertFalse(form.is_valid())
572
+
573
+
574
+ class TestFilteredSelect(TestCase):
575
+ def test_render(self):
576
+ widget = widgets.FilteredSelect(
577
+ choices=[
578
+ (None, "----"),
579
+ ("FR", "France", ["EU"]),
580
+ ("JP", "Japan", ["AS"]),
581
+ ("RU", "Russia", ["AS", "EU"]),
582
+ ],
583
+ filter_field="id_continent",
584
+ )
585
+
586
+ html = widget.render("country", "JP")
587
+ self.assertHTMLEqual(
588
+ html,
589
+ """
590
+ <select name="country" data-widget="filtered-select" data-filter-field="id_continent">
591
+ <option value="">----</option>
592
+ <option value="FR" data-filter-value="EU">France</option>
593
+ <option value="JP" selected data-filter-value="AS">Japan</option>
594
+ <option value="RU" data-filter-value="AS,EU">Russia</option>
595
+ </select>
596
+ """,
597
+ )
598
+
599
+ def test_optgroups(self):
600
+ widget = widgets.FilteredSelect(
601
+ choices=[
602
+ (None, "----"),
603
+ (
604
+ "Big countries",
605
+ [
606
+ ("FR", "France", ["EU"]),
607
+ ("JP", "Japan", ["AS"]),
608
+ ("RU", "Russia", ["AS", "EU"]),
609
+ ("MOON", "The moon"),
610
+ ],
611
+ ),
612
+ (
613
+ "Small countries",
614
+ [
615
+ ("AZ", "Azerbaijan", ["AS"]),
616
+ ("LI", "Liechtenstein", ["EU"]),
617
+ ],
618
+ ),
619
+ ("SK", "Slovakia", ["EU"]),
620
+ ],
621
+ filter_field="id_continent",
622
+ )
623
+
624
+ html = widget.render("country", "JP")
625
+ self.assertHTMLEqual(
626
+ html,
627
+ """
628
+ <select name="country" data-widget="filtered-select" data-filter-field="id_continent">
629
+ <option value="">----</option>
630
+ <optgroup label="Big countries">
631
+ <option value="FR" data-filter-value="EU">France</option>
632
+ <option value="JP" selected data-filter-value="AS">Japan</option>
633
+ <option value="RU" data-filter-value="AS,EU">Russia</option>
634
+ <option value="MOON">The moon</option>
635
+ </optgroup>
636
+ <optgroup label="Small countries">
637
+ <option value="AZ" data-filter-value="AS">Azerbaijan</option>
638
+ <option value="LI" data-filter-value="EU">Liechtenstein</option>
639
+ </optgroup>
640
+ <option value="SK" data-filter-value="EU">Slovakia</option>
641
+ </select>
642
+ """,
643
+ )