import base64 import collections import copy import json import unittest import unittest.mock from decimal import Decimal # non-standard import name for gettext_lazy, to prevent strings from being picked up for translation from django import forms from django.core.exceptions import ValidationError from django.core.serializers.json import DjangoJSONEncoder from django.forms.utils import ErrorList from django.template.loader import render_to_string from django.test import SimpleTestCase, TestCase from django.utils.safestring import SafeData, mark_safe from django.utils.translation import gettext_lazy as _ from wagtail import blocks from wagtail.blocks.base import get_error_json_data from wagtail.blocks.definition_lookup import BlockDefinitionLookup from wagtail.blocks.field_block import FieldBlockAdapter from wagtail.blocks.list_block import ListBlockAdapter, ListBlockValidationError from wagtail.blocks.static_block import StaticBlockAdapter from wagtail.blocks.stream_block import StreamBlockAdapter, StreamBlockValidationError from wagtail.blocks.struct_block import StructBlockAdapter, StructBlockValidationError from wagtail.models import Page from wagtail.rich_text import RichText from wagtail.test.testapp.blocks import LinkBlock as CustomLinkBlock from wagtail.test.testapp.blocks import SectionBlock from wagtail.test.testapp.models import EventPage, SimplePage from wagtail.test.utils import WagtailTestUtils class FooStreamBlock(blocks.StreamBlock): text = blocks.CharBlock() error = 'At least one block must say "foo"' def clean(self, value): value = super().clean(value) if not any(block.value == "foo" for block in value): raise blocks.StreamBlockValidationError( non_block_errors=ErrorList([self.error]) ) return value class ContextCharBlock(blocks.CharBlock): def get_context(self, value, parent_context=None): value = str(value).upper() return super(blocks.CharBlock, self).get_context(value, parent_context) class TestBlock(SimpleTestCase): def test_normalize(self): """The base normalize implementation should return its argument unchanged""" obj = object() self.assertIs(blocks.Block().normalize(obj), obj) def test_block_definition_registry(self): """Instantiating a Block should register it in the definition registry""" block = blocks.Block() self.assertIs(blocks.Block.definition_registry[block.definition_prefix], block) def test_block_is_previewable(self): class CustomContextBlock(blocks.Block): def get_preview_context(self, value, parent_context=None): return {"value": value, "foo": "bar"} class CustomTemplateBlock(blocks.Block): def get_preview_template(self, value=None, context=None): return "foo.html" class CustomValueBlock(blocks.Block): def get_preview_value(self): return "foo" variants = { "no_config": [ blocks.Block(), ], "specific_template": [ blocks.Block(preview_template="foo.html"), CustomTemplateBlock(), ], "custom_value": [ blocks.Block(preview_value="foo"), blocks.Block(default="bar"), CustomContextBlock(), CustomValueBlock(), ], "specific_template_and_custom_value": [ blocks.Block(preview_template="foo.html", preview_value="bar"), ], "unset_default_not_none": [ blocks.ListBlock(blocks.Block()), blocks.StreamBlock(), blocks.StructBlock(), ], } # Test without a global template override cases = [ # Unconfigured block should not be previewable ("no_config", False), # Providing a specific preview template should make the block # previewable even without a custom preview value, as the content # may be hardcoded in the template ("specific_template", True), # Providing a preview value without a custom template should not # make the block previewable, as it may be missing the static assets ("custom_value", False), # Providing both a preview template and value also makes the block # previewable, this is the same as providing a custom template only ("specific_template_and_custom_value", True), # These blocks define their own unset default value that is not # `None`, and that value should not make it previewable ("unset_default_not_none", False), ] for variant, is_previewable in cases: with self.subTest(variant=variant, custom_global_template=False): for block in variants[variant]: self.assertIs(block.is_previewable, is_previewable) # Test with a global template override with unittest.mock.patch( "wagtail.blocks.base.template_is_overridden", return_value=True, ): cases = [ # Global template override + no preview value = not previewable, # since it's unlikely the global template alone will provide a # useful preview ("no_config", False), # Unchanged – specific template always makes the block previewable ("specific_template", True), # Global template override + custom preview value = previewable. # We assume the global template will provide the static assets, # and the custom value (and the block's real template via # {% include_block %}) will provide the content. ("custom_value", True), # Unchanged – providing both also makes the block previewable ("specific_template_and_custom_value", True), # Unchanged – even after providing a global template override, # these blocks should not be previewable ("unset_default_not_none", False), ] for variant, is_previewable in cases: with self.subTest(variant=variant, custom_global_template=True): for block in variants[variant]: del block.is_previewable # Clear cached_property self.assertIs(block.is_previewable, is_previewable) class TestFieldBlock(WagtailTestUtils, SimpleTestCase): def test_charfield_render(self): block = blocks.CharBlock() html = block.render("Hello world!") self.assertEqual(html, "Hello world!") def test_block_definition_registry(self): block = blocks.CharBlock(label="Test block") registered_block = blocks.Block.definition_registry[block.definition_prefix] self.assertIsInstance(registered_block, blocks.CharBlock) self.assertEqual(registered_block.meta.label, "Test block") self.assertIs(registered_block, block) def test_charfield_render_with_template(self): block = blocks.CharBlock(template="tests/blocks/heading_block.html") html = block.render("Hello world!") self.assertEqual(html, "
Now is the time...") def test_render_with_validator(self): def validate_is_proper_story(value): if not value.startswith("Once upon a time"): raise ValidationError("Value must be a proper story") block = blocks.BlockQuoteBlock(validators=[validate_is_proper_story]) with self.assertRaises(ValidationError): block.clean("A long, long time ago") class TestFloatBlock(TestCase): def test_type(self): block = blocks.FloatBlock() block_val = block.value_from_form(float(1.63)) self.assertEqual(type(block_val), float) def test_render(self): block = blocks.FloatBlock() test_val = float(1.63) block_val = block.value_from_form(test_val) self.assertEqual(block_val, test_val) def test_raises_required_error(self): block = blocks.FloatBlock() with self.assertRaises(ValidationError): block.clean("") def test_raises_max_value_validation_error(self): block = blocks.FloatBlock(max_value=20) with self.assertRaises(ValidationError): block.clean("20.01") def test_raises_min_value_validation_error(self): block = blocks.FloatBlock(min_value=20) with self.assertRaises(ValidationError): block.clean("19.99") def test_render_with_validator(self): def validate_is_even(value): if value % 2 > 0: raise ValidationError("Value must be even") block = blocks.FloatBlock(validators=[validate_is_even]) with self.assertRaises(ValidationError): block.clean("3.0") class TestDecimalBlock(TestCase): def test_type(self): block = blocks.DecimalBlock() block_val = block.value_from_form(Decimal("1.63")) self.assertEqual(type(block_val), Decimal) def test_type_to_python(self): block = blocks.DecimalBlock() block_val = block.to_python( "1.63" ) # decimals get saved as string in JSON field self.assertEqual(type(block_val), Decimal) def test_type_to_python_decimal_none_value(self): block = blocks.DecimalBlock() block_val = block.to_python(None) self.assertIsNone(block_val) def test_render(self): block = blocks.DecimalBlock() test_val = Decimal(1.63) block_val = block.value_from_form(test_val) self.assertEqual(block_val, test_val) def test_raises_required_error(self): block = blocks.DecimalBlock() with self.assertRaises(ValidationError): block.clean("") def test_raises_max_value_validation_error(self): block = blocks.DecimalBlock(max_value=20) with self.assertRaises(ValidationError): block.clean("20.01") def test_raises_min_value_validation_error(self): block = blocks.DecimalBlock(min_value=20) with self.assertRaises(ValidationError): block.clean("19.99") def test_render_with_validator(self): def validate_is_even(value): if value % 2 > 0: raise ValidationError("Value must be even") block = blocks.DecimalBlock(validators=[validate_is_even]) with self.assertRaises(ValidationError): block.clean("3.0") def test_round_trip_to_db_preserves_type(self): block = blocks.DecimalBlock() original_value = Decimal(1.63) db_value = json.dumps( block.get_prep_value(original_value), cls=DjangoJSONEncoder ) restored_value = block.to_python(json.loads(db_value)) self.assertEqual(type(restored_value), Decimal) self.assertEqual(original_value, restored_value) class TestRegexBlock(TestCase): def test_render(self): block = blocks.RegexBlock(regex=r"^[0-9]{3}$") test_val = "123" block_val = block.value_from_form(test_val) self.assertEqual(block_val, test_val) def test_raises_required_error(self): block = blocks.RegexBlock(regex=r"^[0-9]{3}$") with self.assertRaises(ValidationError) as context: block.clean("") self.assertIn("This field is required.", context.exception.messages) def test_raises_custom_required_error(self): test_message = "Oops, you missed a bit." block = blocks.RegexBlock( regex=r"^[0-9]{3}$", error_messages={ "required": test_message, }, ) with self.assertRaises(ValidationError) as context: block.clean("") self.assertIn(test_message, context.exception.messages) def test_raises_validation_error(self): block = blocks.RegexBlock(regex=r"^[0-9]{3}$") with self.assertRaises(ValidationError) as context: block.clean("[/]") self.assertIn("Enter a valid value.", context.exception.messages) def test_raises_custom_error_message(self): test_message = "Not a valid library card number." block = blocks.RegexBlock( regex=r"^[0-9]{3}$", error_messages={"invalid": test_message} ) with self.assertRaises(ValidationError) as context: block.clean("[/]") self.assertIn(test_message, context.exception.messages) def test_render_with_validator(self): def validate_is_foo(value): if value != "foo": raise ValidationError("Value must be 'foo'") block = blocks.RegexBlock(regex=r"^.*$", validators=[validate_is_foo]) with self.assertRaises(ValidationError): block.clean("bar") class TestRichTextBlock(TestCase): fixtures = ["test.json"] def test_get_default_with_fallback_value(self): default_value = blocks.RichTextBlock().get_default() self.assertIsInstance(default_value, RichText) self.assertEqual(default_value.source, "") def test_get_default_with_default_none(self): default_value = blocks.RichTextBlock(default=None).get_default() self.assertIsInstance(default_value, RichText) self.assertEqual(default_value.source, "") def test_get_default_with_empty_string(self): default_value = blocks.RichTextBlock(default="").get_default() self.assertIsInstance(default_value, RichText) self.assertEqual(default_value.source, "") def test_get_default_with_nonempty_string(self): default_value = blocks.RichTextBlock(default="
foo
").get_default() self.assertIsInstance(default_value, RichText) self.assertEqual(default_value.source, "foo
") def test_get_default_with_richtext_value(self): default_value = blocks.RichTextBlock( default=RichText("foo
") ).get_default() self.assertIsInstance(default_value, RichText) self.assertEqual(default_value.source, "foo
") def test_render(self): block = blocks.RichTextBlock() value = RichText('Merry Christmas!
') result = block.render(value) self.assertEqual( result, 'Merry Christmas!
' ) def test_adapter(self): from wagtail.test.testapp.rich_text import CustomRichTextArea block = blocks.RichTextBlock(editor="custom") block.set_name("test_richtextblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[0], "test_richtextblock") self.assertIsInstance(js_args[1], CustomRichTextArea) self.assertEqual( js_args[2], { "classname": "w-field w-field--char_field w-field--custom_rich_text_area", "icon": "pilcrow", "label": "Test richtextblock", "description": "", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "required": True, "showAddCommentButton": True, "strings": {"ADD_COMMENT": "Add Comment"}, }, ) def test_adapter_with_draftail(self): from wagtail.admin.rich_text import DraftailRichTextArea block = blocks.RichTextBlock() block.set_name("test_richtextblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[0], "test_richtextblock") self.assertIsInstance(js_args[1], DraftailRichTextArea) self.assertEqual( js_args[2], { "label": "Test richtextblock", "description": "", "required": True, "icon": "pilcrow", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "classname": "w-field w-field--char_field w-field--draftail_rich_text_area", "showAddCommentButton": False, # Draftail manages its own comments "strings": {"ADD_COMMENT": "Add Comment"}, }, ) def test_adapter_with_max_length(self): from wagtail.admin.rich_text import DraftailRichTextArea block = blocks.RichTextBlock(max_length=400) block.set_name("test_richtextblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[0], "test_richtextblock") self.assertIsInstance(js_args[1], DraftailRichTextArea) self.assertEqual( js_args[2], { "label": "Test richtextblock", "description": "", "required": True, "icon": "pilcrow", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "classname": "w-field w-field--char_field w-field--draftail_rich_text_area", "showAddCommentButton": False, # Draftail manages its own comments "strings": {"ADD_COMMENT": "Add Comment"}, "maxLength": 400, }, ) def test_validate_required_richtext_block(self): block = blocks.RichTextBlock() with self.assertRaises(ValidationError): block.clean(RichText("")) def test_validate_non_required_richtext_block(self): block = blocks.RichTextBlock(required=False) result = block.clean(RichText("")) self.assertIsInstance(result, RichText) self.assertEqual(result.source, "") def test_render_with_validator(self): def validate_contains_foo(value): if "foo" not in value: raise ValidationError("Value must contain 'foo'") block = blocks.RichTextBlock(validators=[validate_contains_foo]) with self.assertRaises(ValidationError): block.clean(RichText("bar
")) def test_validate_max_length(self): block = blocks.RichTextBlock(max_length=20) block.clean(RichText("short
")) with self.assertRaises(ValidationError): block.clean(RichText("this exceeds the 20 character limit
")) block.clean( RichText( 'also short
' ) ) def test_get_searchable_content(self): block = blocks.RichTextBlock() value = RichText( 'Merry Christmas! & a happy new year
\n' "Our Santa pet Wagtail has some cool stuff in store for you all!
" ) result = block.get_searchable_content(value) self.assertEqual( result, [ "Merry Christmas! & a happy new year \n" "Our Santa pet Wagtail has some cool stuff in store for you all!" ], ) def test_search_index_get_searchable_content(self): block = blocks.RichTextBlock(search_index=False) value = RichText( 'Merry Christmas! & a happy new year
\n' "Our Santa pet Wagtail has some cool stuff in store for you all!
" ) result = block.get_searchable_content(value) self.assertEqual( result, [], ) def test_get_searchable_content_whitespace(self): block = blocks.RichTextBlock() value = RichText("mashed
potatoes
") result = block.get_searchable_content(value) self.assertEqual(result, ["mashed potatoes"]) def test_extract_references(self): block = blocks.RichTextBlock() value = RichText('Link to an internal page') self.assertEqual(list(block.extract_references(value)), [(Page, "1", "", "")]) def test_normalize(self): block = blocks.RichTextBlock() for value in ("Hello, world", RichText("Hello, world")): with self.subTest(value=value): normalized = block.normalize(value) self.assertIsInstance(normalized, RichText) self.assertEqual(normalized.source, "Hello, world") class TestChoiceBlock(WagtailTestUtils, SimpleTestCase): def setUp(self): from django.db.models.fields import BLANK_CHOICE_DASH self.blank_choice_dash_label = BLANK_CHOICE_DASH[0][1] def test_adapt_choice_block(self): block = blocks.ChoiceBlock(choices=[("tea", "Tea"), ("coffee", "Coffee")]) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[0], "test_choiceblock") self.assertIsInstance(js_args[1], forms.Select) self.assertEqual( list(js_args[1].choices), [("", "---------"), ("tea", "Tea"), ("coffee", "Coffee")], ) self.assertEqual( js_args[2], { "label": "Test choiceblock", "description": "", "required": True, "icon": "placeholder", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "classname": "w-field w-field--choice_field w-field--select", "showAddCommentButton": True, "strings": {"ADD_COMMENT": "Add Comment"}, }, ) def test_choice_block_with_default(self): block = blocks.ChoiceBlock( choices=[("tea", "Tea"), ("coffee", "Coffee")], default="tea" ) self.assertEqual(block.get_default(), "tea") def test_adapt_choice_block_with_callable_choices(self): def callable_choices(): return [("tea", "Tea"), ("coffee", "Coffee")] block = blocks.ChoiceBlock(choices=callable_choices) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertIsInstance(js_args[1], forms.Select) self.assertEqual( list(js_args[1].choices), [("", "---------"), ("tea", "Tea"), ("coffee", "Coffee")], ) def test_validate_required_choice_block(self): block = blocks.ChoiceBlock(choices=[("tea", "Tea"), ("coffee", "Coffee")]) self.assertEqual(block.clean("coffee"), "coffee") with self.assertRaises(ValidationError): block.clean("whisky") with self.assertRaises(ValidationError): block.clean("") with self.assertRaises(ValidationError): block.clean(None) def test_adapt_non_required_choice_block(self): block = blocks.ChoiceBlock( choices=[("tea", "Tea"), ("coffee", "Coffee")], required=False ) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertFalse(js_args[2]["required"]) def test_validate_non_required_choice_block(self): block = blocks.ChoiceBlock( choices=[("tea", "Tea"), ("coffee", "Coffee")], required=False ) self.assertEqual(block.clean("coffee"), "coffee") with self.assertRaises(ValidationError): block.clean("whisky") self.assertEqual(block.clean(""), "") self.assertEqual(block.clean(None), "") def test_adapt_choice_block_with_existing_blank_choice(self): block = blocks.ChoiceBlock( choices=[("tea", "Tea"), ("coffee", "Coffee"), ("", "No thanks")], required=False, ) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual( list(js_args[1].choices), [("tea", "Tea"), ("coffee", "Coffee"), ("", "No thanks")], ) def test_adapt_choice_block_with_existing_blank_choice_and_with_callable_choices( self, ): def callable_choices(): return [("tea", "Tea"), ("coffee", "Coffee"), ("", "No thanks")] block = blocks.ChoiceBlock(choices=callable_choices, required=False) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual( list(js_args[1].choices), [("tea", "Tea"), ("coffee", "Coffee"), ("", "No thanks")], ) def test_named_groups_without_blank_option(self): block = blocks.ChoiceBlock( choices=[ ( "Alcoholic", [ ("gin", "Gin"), ("whisky", "Whisky"), ], ), ( "Non-alcoholic", [ ("tea", "Tea"), ("coffee", "Coffee"), ], ), ] ) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual( list(js_args[1].choices), [ ("", "---------"), ( "Alcoholic", [ ("gin", "Gin"), ("whisky", "Whisky"), ], ), ( "Non-alcoholic", [ ("tea", "Tea"), ("coffee", "Coffee"), ], ), ], ) def test_named_groups_with_blank_option(self): block = blocks.ChoiceBlock( choices=[ ( "Alcoholic", [ ("gin", "Gin"), ("whisky", "Whisky"), ], ), ( "Non-alcoholic", [ ("tea", "Tea"), ("coffee", "Coffee"), ], ), ("Not thirsty", [("", "No thanks")]), ], required=False, ) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual( list(js_args[1].choices), [ # Blank option not added ( "Alcoholic", [ ("gin", "Gin"), ("whisky", "Whisky"), ], ), ( "Non-alcoholic", [ ("tea", "Tea"), ("coffee", "Coffee"), ], ), ("Not thirsty", [("", "No thanks")]), ], ) def test_subclassing(self): class BeverageChoiceBlock(blocks.ChoiceBlock): choices = [ ("tea", "Tea"), ("coffee", "Coffee"), ] block = BeverageChoiceBlock(required=False) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual( list(js_args[1].choices), [ ("", "---------"), ("tea", "Tea"), ("coffee", "Coffee"), ], ) # subclasses of ChoiceBlock should deconstruct to a basic ChoiceBlock for migrations self.assertEqual( block.deconstruct(), ( "wagtail.blocks.ChoiceBlock", [], { "choices": [("tea", "Tea"), ("coffee", "Coffee")], "required": False, }, ), ) def test_searchable_content(self): block = blocks.ChoiceBlock( choices=[ ("choice-1", "Choice 1"), ("choice-2", "Choice 2"), ] ) self.assertEqual(block.get_searchable_content("choice-1"), ["Choice 1"]) def test_search_index_searchable_content(self): block = blocks.ChoiceBlock( choices=[ ("choice-1", "Choice 1"), ("choice-2", "Choice 2"), ], search_index=False, ) self.assertEqual(block.get_searchable_content("choice-1"), []) def test_searchable_content_with_callable_choices(self): def callable_choices(): return [ ("choice-1", "Choice 1"), ("choice-2", "Choice 2"), ] block = blocks.ChoiceBlock(choices=callable_choices) self.assertEqual(block.get_searchable_content("choice-1"), ["Choice 1"]) def test_optgroup_searchable_content(self): block = blocks.ChoiceBlock( choices=[ ( "Section 1", [ ("1-1", "Block 1"), ("1-2", "Block 2"), ], ), ( "Section 2", [ ("2-1", "Block 1"), ("2-2", "Block 2"), ], ), ] ) self.assertEqual(block.get_searchable_content("2-2"), ["Section 2", "Block 2"]) def test_invalid_searchable_content(self): block = blocks.ChoiceBlock( choices=[ ("one", "One"), ("two", "Two"), ] ) self.assertEqual(block.get_searchable_content("three"), []) def test_searchable_content_with_lazy_translation(self): block = blocks.ChoiceBlock( choices=[ ("choice-1", _("Choice 1")), ("choice-2", _("Choice 2")), ] ) result = block.get_searchable_content("choice-1") # result must survive JSON (de)serialisation, which is not the case for # lazy translation objects result = json.loads(json.dumps(result)) self.assertEqual(result, ["Choice 1"]) def test_optgroup_searchable_content_with_lazy_translation(self): block = blocks.ChoiceBlock( choices=[ ( _("Section 1"), [ ("1-1", _("Block 1")), ("1-2", _("Block 2")), ], ), ( _("Section 2"), [ ("2-1", _("Block 1")), ("2-2", _("Block 2")), ], ), ] ) result = block.get_searchable_content("2-2") # result must survive JSON (de)serialisation, which is not the case for # lazy translation objects result = json.loads(json.dumps(result)) self.assertEqual(result, ["Section 2", "Block 2"]) def test_deconstruct_with_callable_choices(self): def callable_choices(): return [ ("tea", "Tea"), ("coffee", "Coffee"), ] block = blocks.ChoiceBlock(choices=callable_choices, required=False) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual( list(js_args[1].choices), [ ("", "---------"), ("tea", "Tea"), ("coffee", "Coffee"), ], ) self.assertEqual( block.deconstruct(), ( "wagtail.blocks.ChoiceBlock", [], { "choices": callable_choices, "required": False, }, ), ) def test_render_with_validator(self): choices = [ ("tea", "Tea"), ("coffee", "Coffee"), ] def validate_tea_is_selected(value): raise ValidationError("You must select 'tea'") block = blocks.ChoiceBlock( choices=choices, validators=[validate_tea_is_selected] ) with self.assertRaises(ValidationError): block.clean("coffee") def test_get_form_state(self): block = blocks.ChoiceBlock(choices=[("tea", "Tea"), ("coffee", "Coffee")]) form_state = block.get_form_state("tea") self.assertEqual(form_state, ["tea"]) def test_get_form_state_with_radio_widget(self): block = blocks.ChoiceBlock( choices=[("tea", "Tea"), ("coffee", "Coffee")], widget=forms.RadioSelect ) form_state = block.get_form_state("tea") self.assertEqual(form_state, ["tea"]) class TestMultipleChoiceBlock(WagtailTestUtils, SimpleTestCase): def setUp(self): from django.db.models.fields import BLANK_CHOICE_DASH self.blank_choice_dash_label = BLANK_CHOICE_DASH[0][1] def test_adapt_multiple_choice_block(self): block = blocks.MultipleChoiceBlock( choices=[("tea", "Tea"), ("coffee", "Coffee")] ) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[0], "test_choiceblock") self.assertIsInstance(js_args[1], forms.Select) self.assertEqual( list(js_args[1].choices), [("tea", "Tea"), ("coffee", "Coffee")] ) self.assertEqual( js_args[2], { "label": "Test choiceblock", "description": "", "required": True, "icon": "placeholder", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "classname": "w-field w-field--multiple_choice_field w-field--select_multiple", "showAddCommentButton": True, "strings": {"ADD_COMMENT": "Add Comment"}, }, ) def test_multiple_choice_block_with_default(self): block = blocks.MultipleChoiceBlock( choices=[("tea", "Tea"), ("coffee", "Coffee")], default="tea" ) self.assertEqual(block.get_default(), "tea") def test_adapt_multiple_choice_block_with_callable_choices(self): def callable_choices(): return [("tea", "Tea"), ("coffee", "Coffee")] block = blocks.MultipleChoiceBlock(choices=callable_choices) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertIsInstance(js_args[1], forms.Select) self.assertEqual( list(js_args[1].choices), [("tea", "Tea"), ("coffee", "Coffee")] ) def test_validate_required_multiple_choice_block(self): block = blocks.MultipleChoiceBlock( choices=[("tea", "Tea"), ("coffee", "Coffee")] ) self.assertEqual(block.clean(["coffee"]), ["coffee"]) with self.assertRaises(ValidationError): block.clean(["whisky"]) with self.assertRaises(ValidationError): block.clean("") with self.assertRaises(ValidationError): block.clean(None) def test_adapt_non_required_multiple_choice_block(self): block = blocks.MultipleChoiceBlock( choices=[("tea", "Tea"), ("coffee", "Coffee")], required=False ) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertFalse(js_args[2]["required"]) def test_validate_non_required_multiple_choice_block(self): block = blocks.MultipleChoiceBlock( choices=[("tea", "Tea"), ("coffee", "Coffee")], required=False ) self.assertEqual(block.clean(["coffee"]), ["coffee"]) with self.assertRaises(ValidationError): block.clean(["whisky"]) self.assertEqual(block.clean(""), []) self.assertEqual(block.clean(None), []) def test_adapt_multiple_choice_block_with_existing_blank_choice(self): block = blocks.MultipleChoiceBlock( choices=[("tea", "Tea"), ("coffee", "Coffee"), ("", "No thanks")], required=False, ) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual( list(js_args[1].choices), [("tea", "Tea"), ("coffee", "Coffee"), ("", "No thanks")], ) def test_adapt_multiple_choice_block_with_existing_blank_choice_and_with_callable_choices( self, ): def callable_choices(): return [("tea", "Tea"), ("coffee", "Coffee"), ("", "No thanks")] block = blocks.MultipleChoiceBlock(choices=callable_choices, required=False) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual( list(js_args[1].choices), [("tea", "Tea"), ("coffee", "Coffee"), ("", "No thanks")], ) def test_named_groups_without_blank_option(self): block = blocks.MultipleChoiceBlock( choices=[ ( "Alcoholic", [ ("gin", "Gin"), ("whisky", "Whisky"), ], ), ( "Non-alcoholic", [ ("tea", "Tea"), ("coffee", "Coffee"), ], ), ] ) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual( list(js_args[1].choices), [ ( "Alcoholic", [ ("gin", "Gin"), ("whisky", "Whisky"), ], ), ( "Non-alcoholic", [ ("tea", "Tea"), ("coffee", "Coffee"), ], ), ], ) def test_named_groups_with_blank_option(self): block = blocks.MultipleChoiceBlock( choices=[ ( "Alcoholic", [ ("gin", "Gin"), ("whisky", "Whisky"), ], ), ( "Non-alcoholic", [ ("tea", "Tea"), ("coffee", "Coffee"), ], ), ("Not thirsty", [("", "No thanks")]), ], required=False, ) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual( list(js_args[1].choices), [ ( "Alcoholic", [ ("gin", "Gin"), ("whisky", "Whisky"), ], ), ( "Non-alcoholic", [ ("tea", "Tea"), ("coffee", "Coffee"), ], ), ("Not thirsty", [("", "No thanks")]), ], ) def test_subclassing(self): class BeverageMultipleChoiceBlock(blocks.MultipleChoiceBlock): choices = [ ("tea", "Tea"), ("coffee", "Coffee"), ] block = BeverageMultipleChoiceBlock(required=False) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual( list(js_args[1].choices), [ ("tea", "Tea"), ("coffee", "Coffee"), ], ) # subclasses of ChoiceBlock should deconstruct to a basic ChoiceBlock for migrations self.assertEqual( block.deconstruct(), ( "wagtail.blocks.MultipleChoiceBlock", [], { "choices": [("tea", "Tea"), ("coffee", "Coffee")], "required": False, }, ), ) def test_searchable_content(self): block = blocks.MultipleChoiceBlock( choices=[ ("choice-1", "Choice 1"), ("choice-2", "Choice 2"), ] ) self.assertEqual(block.get_searchable_content("choice-1"), ["Choice 1"]) def test_search_index_searchable_content(self): block = blocks.MultipleChoiceBlock( choices=[ ("choice-1", "Choice 1"), ("choice-2", "Choice 2"), ], search_index=False, ) self.assertEqual(block.get_searchable_content("choice-1"), []) def test_searchable_content_with_callable_choices(self): def callable_choices(): return [ ("choice-1", "Choice 1"), ("choice-2", "Choice 2"), ] block = blocks.MultipleChoiceBlock(choices=callable_choices) self.assertEqual(block.get_searchable_content("choice-1"), ["Choice 1"]) def test_optgroup_searchable_content(self): block = blocks.MultipleChoiceBlock( choices=[ ( "Section 1", [ ("1-1", "Block 1"), ("1-2", "Block 2"), ], ), ( "Section 2", [ ("2-1", "Block 1"), ("2-2", "Block 2"), ], ), ] ) self.assertEqual(block.get_searchable_content("2-2"), ["Section 2", "Block 2"]) def test_invalid_searchable_content(self): block = blocks.MultipleChoiceBlock( choices=[ ("one", "One"), ("two", "Two"), ] ) self.assertEqual(block.get_searchable_content("three"), []) def test_searchable_content_with_lazy_translation(self): block = blocks.MultipleChoiceBlock( choices=[ ("choice-1", _("Choice 1")), ("choice-2", _("Choice 2")), ] ) result = block.get_searchable_content("choice-1") # result must survive JSON (de)serialisation, which is not the case for # lazy translation objects result = json.loads(json.dumps(result)) self.assertEqual(result, ["Choice 1"]) def test_optgroup_searchable_content_with_lazy_translation(self): block = blocks.MultipleChoiceBlock( choices=[ ( _("Section 1"), [ ("1-1", _("Block 1")), ("1-2", _("Block 2")), ], ), ( _("Section 2"), [ ("2-1", _("Block 1")), ("2-2", _("Block 2")), ], ), ] ) result = block.get_searchable_content("2-2") # result must survive JSON (de)serialisation, which is not the case for # lazy translation objects result = json.loads(json.dumps(result)) self.assertEqual(result, ["Section 2", "Block 2"]) def test_deconstruct_with_callable_choices(self): def callable_choices(): return [ ("tea", "Tea"), ("coffee", "Coffee"), ] block = blocks.MultipleChoiceBlock(choices=callable_choices, required=False) block.set_name("test_choiceblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual( list(js_args[1].choices), [ ("tea", "Tea"), ("coffee", "Coffee"), ], ) self.assertEqual( block.deconstruct(), ( "wagtail.blocks.MultipleChoiceBlock", [], { "choices": callable_choices, "required": False, }, ), ) def test_render_with_validator(self): choices = [ ("tea", "Tea"), ("coffee", "Coffee"), ] def validate_tea_is_selected(value): raise ValidationError("You must select 'tea'") block = blocks.MultipleChoiceBlock( choices=choices, validators=[validate_tea_is_selected] ) with self.assertRaises(ValidationError): block.clean("coffee") def test_get_form_state(self): block = blocks.MultipleChoiceBlock( choices=[("tea", "Tea"), ("coffee", "Coffee")] ) form_state = block.get_form_state(["tea", "coffee"]) self.assertEqual(form_state, ["tea", "coffee"]) def test_get_form_state_with_checkbox_widget(self): block = blocks.ChoiceBlock( choices=[("tea", "Tea"), ("coffee", "Coffee")], widget=forms.CheckboxSelectMultiple, ) form_state = block.get_form_state(["tea", "coffee"]) self.assertEqual(form_state, ["tea", "coffee"]) class TestRawHTMLBlock(unittest.TestCase): def test_get_default_with_fallback_value(self): default_value = blocks.RawHTMLBlock().get_default() self.assertEqual(default_value, "") self.assertIsInstance(default_value, SafeData) def test_get_default_with_none(self): default_value = blocks.RawHTMLBlock(default=None).get_default() self.assertEqual(default_value, "") self.assertIsInstance(default_value, SafeData) def test_get_default_with_empty_string(self): default_value = blocks.RawHTMLBlock(default="").get_default() self.assertEqual(default_value, "") self.assertIsInstance(default_value, SafeData) def test_get_default_with_nonempty_string(self): default_value = blocks.RawHTMLBlock(default="").get_default() self.assertEqual(default_value, "") self.assertIsInstance(default_value, SafeData) def test_serialize(self): block = blocks.RawHTMLBlock() result = block.get_prep_value(mark_safe("")) self.assertEqual(result, "") self.assertNotIsInstance(result, SafeData) def test_deserialize(self): block = blocks.RawHTMLBlock() result = block.to_python("") self.assertEqual(result, "") self.assertIsInstance(result, SafeData) def test_render(self): block = blocks.RawHTMLBlock() result = block.render(mark_safe("")) self.assertEqual(result, "") self.assertIsInstance(result, SafeData) def test_get_form_state(self): block = blocks.RawHTMLBlock() form_state = block.get_form_state("") self.assertEqual(form_state, "") def test_adapt(self): block = blocks.RawHTMLBlock() block.set_name("test_rawhtmlblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[0], "test_rawhtmlblock") self.assertIsInstance(js_args[1], forms.Textarea) self.assertEqual(js_args[1].attrs, {"cols": "40", "rows": "10"}) self.assertEqual( js_args[2], { "label": "Test rawhtmlblock", "description": "", "required": True, "icon": "code", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "classname": "w-field w-field--char_field w-field--textarea", "showAddCommentButton": True, "strings": {"ADD_COMMENT": "Add Comment"}, }, ) def test_form_response(self): block = blocks.RawHTMLBlock() result = block.value_from_datadict( {"rawhtml": ""}, {}, prefix="rawhtml" ) self.assertEqual(result, "") self.assertIsInstance(result, SafeData) def test_value_omitted_from_data(self): block = blocks.RawHTMLBlock() self.assertFalse( block.value_omitted_from_data({"rawhtml": "ohai"}, {}, "rawhtml") ) self.assertFalse(block.value_omitted_from_data({"rawhtml": ""}, {}, "rawhtml")) self.assertTrue( block.value_omitted_from_data({"nothing-here": "nope"}, {}, "rawhtml") ) def test_clean_required_field(self): block = blocks.RawHTMLBlock() result = block.clean(mark_safe("")) self.assertEqual(result, "") self.assertIsInstance(result, SafeData) with self.assertRaises(ValidationError): block.clean(mark_safe("")) def test_clean_nonrequired_field(self): block = blocks.RawHTMLBlock(required=False) result = block.clean(mark_safe("")) self.assertEqual(result, "") self.assertIsInstance(result, SafeData) result = block.clean(mark_safe("")) self.assertEqual(result, "") self.assertIsInstance(result, SafeData) def test_render_with_validator(self): def validate_contains_foo(value): if "foo" not in value: raise ValidationError("Value must contain 'foo'") block = blocks.RawHTMLBlock(validators=[validate_contains_foo]) with self.assertRaises(ValidationError): block.clean(mark_safe("bar
")) class TestMeta(unittest.TestCase): def test_set_template_with_meta(self): class HeadingBlock(blocks.CharBlock): class Meta: template = "heading.html" block = HeadingBlock() self.assertEqual(block.meta.template, "heading.html") def test_set_template_with_constructor(self): block = blocks.CharBlock(template="heading.html") self.assertEqual(block.meta.template, "heading.html") def test_set_template_with_constructor_overrides_meta(self): class HeadingBlock(blocks.CharBlock): class Meta: template = "heading.html" block = HeadingBlock(template="subheading.html") self.assertEqual(block.meta.template, "subheading.html") def test_meta_nested_inheritance(self): """ Check that having a multi-level inheritance chain works """ class HeadingBlock(blocks.CharBlock): class Meta: template = "heading.html" test = "Foo" class SubHeadingBlock(HeadingBlock): class Meta: template = "subheading.html" block = SubHeadingBlock() self.assertEqual(block.meta.template, "subheading.html") self.assertEqual(block.meta.test, "Foo") def test_meta_multi_inheritance(self): """ Check that multi-inheritance and Meta classes work together """ class LeftBlock(blocks.CharBlock): class Meta: template = "template.html" clash = "the band" label = "Left block" class RightBlock(blocks.CharBlock): class Meta: default = "hello" clash = "the album" label = "Right block" class ChildBlock(LeftBlock, RightBlock): class Meta: label = "Child block" block = ChildBlock() # These should be directly inherited from the LeftBlock/RightBlock self.assertEqual(block.meta.template, "template.html") self.assertEqual(block.meta.default, "hello") # This should be inherited from the LeftBlock, solving the collision, # as LeftBlock comes first self.assertEqual(block.meta.clash, "the band") # This should come from ChildBlock itself, ignoring the label on # LeftBlock/RightBlock self.assertEqual(block.meta.label, "Child block") class TestStructBlock(SimpleTestCase): def test_initialisation(self): block = blocks.StructBlock( [ ("title", blocks.CharBlock()), ("link", blocks.URLBlock()), ] ) self.assertEqual(list(block.child_blocks.keys()), ["title", "link"]) def test_initialisation_from_subclass(self): class LinkBlock(blocks.StructBlock): title = blocks.CharBlock() link = blocks.URLBlock() block = LinkBlock() self.assertEqual(list(block.child_blocks.keys()), ["title", "link"]) def test_initialisation_from_subclass_with_extra(self): class LinkBlock(blocks.StructBlock): title = blocks.CharBlock() link = blocks.URLBlock() block = LinkBlock([("classname", blocks.CharBlock())]) self.assertEqual( list(block.child_blocks.keys()), ["title", "link", "classname"] ) def test_initialisation_with_multiple_subclassses(self): class LinkBlock(blocks.StructBlock): title = blocks.CharBlock() link = blocks.URLBlock() class StyledLinkBlock(LinkBlock): classname = blocks.CharBlock() block = StyledLinkBlock() self.assertEqual( list(block.child_blocks.keys()), ["title", "link", "classname"] ) def test_initialisation_with_mixins(self): """ The order of fields of classes with multiple parent classes is slightly surprising at first. Child fields are inherited in a bottom-up order, by traversing the MRO in reverse. In the example below, ``StyledLinkBlock`` will have an MRO of:: [StyledLinkBlock, StylingMixin, LinkBlock, StructBlock, ...] This will result in ``classname`` appearing *after* ``title`` and ``link`` in ``StyleLinkBlock`.child_blocks`, even though ``StylingMixin`` appeared before ``LinkBlock``. """ class LinkBlock(blocks.StructBlock): title = blocks.CharBlock() link = blocks.URLBlock() class StylingMixin(blocks.StructBlock): classname = blocks.CharBlock() class StyledLinkBlock(StylingMixin, LinkBlock): source = blocks.CharBlock() block = StyledLinkBlock() self.assertEqual( list(block.child_blocks.keys()), ["title", "link", "classname", "source"] ) def test_render(self): class LinkBlock(blocks.StructBlock): title = blocks.CharBlock() link = blocks.URLBlock() block = LinkBlock() html = block.render( block.to_python( { "title": "Wagtail site", "link": "http://www.wagtail.org", } ) ) expected_html = "\n".join( [ "this is a paragraph
", }, {}, prefix="foo", ) self.assertEqual(len(value), 2) self.assertEqual(value[0].block_type, "paragraph") self.assertEqual(value[0].id, "") self.assertEqual(value[0].value, "this is a paragraph
") self.assertEqual(value[1].block_type, "heading") self.assertEqual(value[1].id, "0000") self.assertEqual(value[1].value, "this is my heading") def check_get_prep_value(self, stream_data, is_lazy): class ArticleBlock(blocks.StreamBlock): heading = blocks.CharBlock() paragraph = blocks.CharBlock() block = ArticleBlock() value = blocks.StreamValue(block, stream_data, is_lazy=is_lazy) jsonish_value = block.get_prep_value(value) self.assertEqual(len(jsonish_value), 2) self.assertEqual( jsonish_value[0], {"type": "heading", "value": "this is my heading", "id": "0000"}, ) self.assertEqual(jsonish_value[1]["type"], "paragraph") self.assertEqual(jsonish_value[1]["value"], "this is a paragraph
") # get_prep_value should assign a new (random and non-empty) # ID to this block, as it didn't have one already. self.assertTrue(jsonish_value[1]["id"]) # Calling get_prep_value again should preserve existing IDs, including the one # just assigned to block 1 jsonish_value_again = block.get_prep_value(value) self.assertEqual(jsonish_value[0]["id"], jsonish_value_again[0]["id"]) self.assertEqual(jsonish_value[1]["id"], jsonish_value_again[1]["id"]) def test_get_prep_value_not_lazy(self): stream_data = [ ("heading", "this is my heading", "0000"), ("paragraph", "this is a paragraph
"), ] self.check_get_prep_value(stream_data, is_lazy=False) def test_get_prep_value_is_lazy(self): stream_data = [ {"type": "heading", "value": "this is my heading", "id": "0000"}, {"type": "paragraph", "value": "this is a paragraph
"}, ] self.check_get_prep_value(stream_data, is_lazy=True) def check_get_prep_value_nested_streamblocks(self, stream_data, is_lazy): class TwoColumnBlock(blocks.StructBlock): left = blocks.StreamBlock([("text", blocks.CharBlock())]) right = blocks.StreamBlock([("text", blocks.CharBlock())]) block = TwoColumnBlock() value = { k: blocks.StreamValue(block.child_blocks[k], v, is_lazy=is_lazy) for k, v in stream_data.items() } jsonish_value = block.get_prep_value(value) self.assertEqual(len(jsonish_value), 2) self.assertEqual( jsonish_value["left"], [{"type": "text", "value": "some text", "id": "0000"}], ) self.assertEqual(len(jsonish_value["right"]), 1) right_block = jsonish_value["right"][0] self.assertEqual(right_block["type"], "text") self.assertEqual(right_block["value"], "some other text") # get_prep_value should assign a new (random and non-empty) # ID to this block, as it didn't have one already. self.assertTrue(right_block["id"]) def test_get_prep_value_nested_streamblocks_not_lazy(self): stream_data = { "left": [("text", "some text", "0000")], "right": [("text", "some other text")], } self.check_get_prep_value_nested_streamblocks(stream_data, is_lazy=False) def test_get_prep_value_nested_streamblocks_is_lazy(self): stream_data = { "left": [ { "type": "text", "value": "some text", "id": "0000", } ], "right": [ { "type": "text", "value": "some other text", } ], } self.check_get_prep_value_nested_streamblocks(stream_data, is_lazy=True) def test_modifications_to_stream_child_id_are_saved(self): class ArticleBlock(blocks.StreamBlock): heading = blocks.CharBlock() paragraph = blocks.CharBlock() block = ArticleBlock() stream = block.to_python( [ {"type": "heading", "value": "hello", "id": "0001"}, {"type": "paragraph", "value": "world", "id": "0002"}, ] ) stream[1].id = "0003" raw_data = block.get_prep_value(stream) self.assertEqual( raw_data, [ {"type": "heading", "value": "hello", "id": "0001"}, {"type": "paragraph", "value": "world", "id": "0003"}, ], ) def test_modifications_to_stream_child_value_are_saved(self): class ArticleBlock(blocks.StreamBlock): heading = blocks.CharBlock() paragraph = blocks.CharBlock() block = ArticleBlock() stream = block.to_python( [ {"type": "heading", "value": "hello", "id": "0001"}, {"type": "paragraph", "value": "world", "id": "0002"}, ] ) stream[1].value = "earth" raw_data = block.get_prep_value(stream) self.assertEqual( raw_data, [ {"type": "heading", "value": "hello", "id": "0001"}, {"type": "paragraph", "value": "earth", "id": "0002"}, ], ) def test_set_streamvalue_item(self): class ArticleBlock(blocks.StreamBlock): heading = blocks.CharBlock() paragraph = blocks.CharBlock() block = ArticleBlock() stream = block.to_python( [ {"type": "heading", "value": "hello", "id": "0001"}, {"type": "paragraph", "value": "world", "id": "0002"}, ] ) stream[1] = ("heading", "goodbye", "0003") raw_data = block.get_prep_value(stream) self.assertEqual( raw_data, [ {"type": "heading", "value": "hello", "id": "0001"}, {"type": "heading", "value": "goodbye", "id": "0003"}, ], ) def test_delete_streamvalue_item(self): class ArticleBlock(blocks.StreamBlock): heading = blocks.CharBlock() paragraph = blocks.CharBlock() block = ArticleBlock() stream = block.to_python( [ {"type": "heading", "value": "hello", "id": "0001"}, {"type": "paragraph", "value": "world", "id": "0002"}, ] ) del stream[0] raw_data = block.get_prep_value(stream) self.assertEqual( raw_data, [ {"type": "paragraph", "value": "world", "id": "0002"}, ], ) def test_insert_streamvalue_item(self): class ArticleBlock(blocks.StreamBlock): heading = blocks.CharBlock() paragraph = blocks.CharBlock() block = ArticleBlock() stream = block.to_python( [ {"type": "heading", "value": "hello", "id": "0001"}, {"type": "paragraph", "value": "world", "id": "0002"}, ] ) stream.insert(1, ("paragraph", "mutable", "0003")) raw_data = block.get_prep_value(stream) self.assertEqual( raw_data, [ {"type": "heading", "value": "hello", "id": "0001"}, {"type": "paragraph", "value": "mutable", "id": "0003"}, {"type": "paragraph", "value": "world", "id": "0002"}, ], ) def test_append_streamvalue_item(self): class ArticleBlock(blocks.StreamBlock): heading = blocks.CharBlock() paragraph = blocks.CharBlock() block = ArticleBlock() stream = block.to_python( [ {"type": "heading", "value": "hello", "id": "0001"}, {"type": "paragraph", "value": "world", "id": "0002"}, ] ) stream.append(("paragraph", "of warcraft", "0003")) raw_data = block.get_prep_value(stream) self.assertEqual( raw_data, [ {"type": "heading", "value": "hello", "id": "0001"}, {"type": "paragraph", "value": "world", "id": "0002"}, {"type": "paragraph", "value": "of warcraft", "id": "0003"}, ], ) def test_streamvalue_raw_data(self): class ArticleBlock(blocks.StreamBlock): heading = blocks.CharBlock() paragraph = blocks.CharBlock() block = ArticleBlock() stream = block.to_python( [ {"type": "heading", "value": "hello", "id": "0001"}, {"type": "paragraph", "value": "world", "id": "0002"}, ] ) self.assertEqual( stream.raw_data[0], {"type": "heading", "value": "hello", "id": "0001"} ) stream.raw_data[0]["value"] = "bonjour" self.assertEqual( stream.raw_data[0], {"type": "heading", "value": "bonjour", "id": "0001"} ) # changes to raw_data will be written back via get_prep_value... raw_data = block.get_prep_value(stream) self.assertEqual( raw_data, [ {"type": "heading", "value": "bonjour", "id": "0001"}, {"type": "paragraph", "value": "world", "id": "0002"}, ], ) # ...but once the bound-block representation has been accessed, that takes precedence self.assertEqual(stream[0].value, "bonjour") stream.raw_data[0]["value"] = "guten tag" self.assertEqual(stream.raw_data[0]["value"], "guten tag") self.assertEqual(stream[0].value, "bonjour") raw_data = block.get_prep_value(stream) self.assertEqual( raw_data, [ {"type": "heading", "value": "bonjour", "id": "0001"}, {"type": "paragraph", "value": "world", "id": "0002"}, ], ) # Replacing a raw_data entry outright will propagate to the bound block, though stream.raw_data[0] = {"type": "heading", "value": "konnichiwa", "id": "0003"} raw_data = block.get_prep_value(stream) self.assertEqual( raw_data, [ {"type": "heading", "value": "konnichiwa", "id": "0003"}, {"type": "paragraph", "value": "world", "id": "0002"}, ], ) self.assertEqual(stream[0].value, "konnichiwa") # deletions / insertions on raw_data will also propagate to the bound block representation del stream.raw_data[1] stream.raw_data.insert( 0, {"type": "paragraph", "value": "hello kitty says", "id": "0004"} ) raw_data = block.get_prep_value(stream) self.assertEqual( raw_data, [ {"type": "paragraph", "value": "hello kitty says", "id": "0004"}, {"type": "heading", "value": "konnichiwa", "id": "0003"}, ], ) def test_adapt_with_classname_via_kwarg(self): """form_classname from kwargs to be used as an additional class when rendering stream block""" block = blocks.StreamBlock( [ (b"heading", blocks.CharBlock()), (b"paragraph", blocks.CharBlock()), ], form_classname="rocket-section", ) block.set_name("test_streamblock") js_args = StreamBlockAdapter().js_args(block) self.assertEqual( js_args[3], { "label": "Test streamblock", "description": "", "icon": "placeholder", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "minNum": None, "maxNum": None, "blockCounts": {}, "collapsed": False, "required": True, "classname": "rocket-section", "strings": { "DELETE": "Delete", "DUPLICATE": "Duplicate", "MOVE_DOWN": "Move down", "MOVE_UP": "Move up", "DRAG": "Drag", "ADD": "Add", }, }, ) def test_block_names(self): class ArticleBlock(blocks.StreamBlock): heading = blocks.CharBlock() paragraph = blocks.TextBlock() date = blocks.DateBlock() block = ArticleBlock() value = block.to_python( [ { "type": "heading", "value": "My title", }, { "type": "paragraph", "value": "My first paragraph", }, { "type": "paragraph", "value": "My second paragraph", }, ] ) blocks_by_name = value.blocks_by_name() assert isinstance(blocks_by_name, blocks.StreamValue.BlockNameLookup) # unpack results to a dict of {block name: list of block values} for easier comparison result = { block_name: [block.value for block in blocks] for block_name, blocks in blocks_by_name.items() } self.assertEqual( result, { "heading": ["My title"], "paragraph": ["My first paragraph", "My second paragraph"], "date": [], }, ) paragraph_blocks = value.blocks_by_name(block_name="paragraph") # We can also access by indexing on the stream self.assertEqual(paragraph_blocks, value.blocks_by_name()["paragraph"]) self.assertEqual(len(paragraph_blocks), 2) for block in paragraph_blocks: self.assertEqual(block.block_type, "paragraph") self.assertEqual(value.blocks_by_name(block_name="date"), []) self.assertEqual(value.blocks_by_name(block_name="invalid_type"), []) first_heading_block = value.first_block_by_name(block_name="heading") self.assertEqual(first_heading_block.block_type, "heading") self.assertEqual(first_heading_block.value, "My title") self.assertIs(value.first_block_by_name(block_name="date"), None) self.assertIs(value.first_block_by_name(block_name="invalid_type"), None) # first_block_by_name with no argument returns a dict-like lookup of first blocks per name first_blocks_by_name = value.first_block_by_name() first_heading_block = first_blocks_by_name["heading"] self.assertEqual(first_heading_block.block_type, "heading") self.assertEqual(first_heading_block.value, "My title") self.assertIs(first_blocks_by_name["date"], None) self.assertIs(first_blocks_by_name["invalid_type"], None) def test_adapt_with_classname_via_class_meta(self): """form_classname from meta to be used as an additional class when rendering stream block""" class ProfileBlock(blocks.StreamBlock): username = blocks.CharBlock() class Meta: form_classname = "profile-block-large" block = ProfileBlock() block.set_name("test_streamblock") js_args = StreamBlockAdapter().js_args(block) self.assertEqual( js_args[3], { "label": "Test streamblock", "description": "", "icon": "placeholder", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "minNum": None, "maxNum": None, "blockCounts": {}, "collapsed": False, "required": True, "classname": "profile-block-large", "strings": { "DELETE": "Delete", "DUPLICATE": "Duplicate", "MOVE_DOWN": "Move down", "MOVE_UP": "Move up", "DRAG": "Drag", "ADD": "Add", }, }, ) class TestNormalizeStreamBlock(SimpleTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.simple_block = blocks.StreamBlock( [("number", blocks.IntegerBlock()), ("text", blocks.TextBlock())] ) cls.recursive_block = blocks.StreamBlock( [ ( "inner_stream", blocks.StreamBlock( [ ("number", blocks.IntegerBlock()), ("text", blocks.TextBlock()), ("inner_list", blocks.ListBlock(blocks.IntegerBlock)), ] ), ), ("struct", blocks.StructBlock([("bool", blocks.BooleanBlock())])), ("list", blocks.ListBlock(blocks.IntegerBlock)), ] ) def test_normalize_empty_stream(self): values = [[], "", None] for value in values: with self.subTest(value=value): self.assertEqual( self.simple_block.normalize(value), blocks.StreamValue(self.simple_block, []), ) def test_normalize_base_case(self): """ Test normalize when trivially recursive, or already a StreamValue """ value = [("number", 1), ("text", "ichiban")] stream_value = blocks.StreamValue(self.simple_block, value) self.assertEqual(stream_value, self.simple_block.normalize(value)) self.assertEqual(stream_value, self.simple_block.normalize(stream_value)) def test_normalize_recursive(self): """ A stream block is normalized iff all of its sub-blocks are normalized. """ values = ( # A smart, "list of tuples" representation [ ("struct", {"bool": True}), ( "inner_stream", [ ("number", 1), ("text", "one"), ("inner_list", [0, 1, 1, 2, 3, 5]), ], ), ("list", [0, 1, 1, 2, 3, 5]), ], # A json-ish representation - the serialized format [ {"type": "struct", "value": {"bool": True}}, { "type": "inner_stream", "value": [ {"type": "number", "value": 1}, {"type": "text", "value": "one"}, { "type": "inner_list", "value": [ # Unlike StreamBlock, ListBlock requires that its items # have IDs, to distinguish the new serialization format # from the old. {"type": "item", "value": 0, "id": 1}, {"type": "item", "value": 1, "id": 2}, {"type": "item", "value": 2, "id": 3}, ], }, ], }, { "type": "list", "value": [ {"type": "item", "value": 0, "id": 1}, {"type": "item", "value": 1, "id": 2}, {"type": "item", "value": 2, "id": 3}, ], }, ], ) for value in values: with self.subTest(value=value): # Normalize the value. normalized = self.recursive_block.normalize(value) # Then check all of the sub-blocks have been normalized: # the StructBlock child self.assertIsInstance(normalized[0].value, blocks.StructValue) self.assertIsInstance(normalized[0].value["bool"], bool) # the nested StreamBlock child self.assertIsInstance(normalized[1].value, blocks.StreamValue) self.assertIsInstance(normalized[1].value[0].value, int) self.assertIsInstance(normalized[1].value[1].value, str) # the ListBlock child self.assertIsInstance(normalized[2].value[0], int) self.assertIsInstance(normalized[2].value, blocks.list_block.ListValue) # the inner ListBlock nested in the nested streamblock self.assertIsInstance(normalized[1].value[2].value[0], int) self.assertIsInstance( normalized[1].value[2].value, blocks.list_block.ListValue ) class TestStructBlockWithFixtures(TestCase): fixtures = ["test.json"] def test_bulk_to_python(self): page_link_block = blocks.StructBlock( [ ("page", blocks.PageChooserBlock(required=False)), ("link_text", blocks.CharBlock(default="missing title")), ] ) with self.assertNumQueries(1): result = page_link_block.bulk_to_python( [ {"page": 2, "link_text": "page two"}, {"page": 3, "link_text": "page three"}, {"page": None, "link_text": "no page"}, {"page": 4}, ] ) result_types = [type(val) for val in result] self.assertEqual(result_types, [blocks.StructValue] * 4) result_titles = [val["link_text"] for val in result] self.assertEqual( result_titles, ["page two", "page three", "no page", "missing title"] ) result_pages = [val["page"] for val in result] self.assertEqual( result_pages, [ Page.objects.get(id=2), Page.objects.get(id=3), None, Page.objects.get(id=4), ], ) def test_extract_references(self): block = blocks.StructBlock( [ ("page", blocks.PageChooserBlock(required=False)), ("link_text", blocks.CharBlock(default="missing title")), ] ) christmas_page = Page.objects.get(slug="christmas") self.assertListEqual( list( block.extract_references( {"page": christmas_page, "link_text": "Christmas"} ) ), [ (Page, str(christmas_page.id), "page", "page"), ], ) class TestStreamBlockWithFixtures(TestCase): fixtures = ["test.json"] def test_bulk_to_python(self): stream_block = blocks.StreamBlock( [ ("page", blocks.PageChooserBlock()), ("heading", blocks.CharBlock()), ] ) # The naive implementation of bulk_to_python (calling to_python on each item) would perform # NO queries, as StreamBlock.to_python returns a lazy StreamValue that only starts calling # to_python on its children (and thus triggering DB queries) when its items are accessed. # This is a good thing for a standalone to_python call, because loading a model instance # with a StreamField in it will immediately call StreamField.to_python which in turn calls # to_python on the top-level StreamBlock, and we really don't want # SomeModelWithAStreamField.objects.get(id=1) to immediately trigger a cascading fetch of # all objects referenced in the StreamField. # # However, for bulk_to_python that's bad, as it means each stream in the list would end up # doing its own object lookups in isolation, missing the opportunity to group them together # into a single call to the child block's bulk_to_python. Therefore, the ideal outcome is # that we perform one query now (covering all PageChooserBlocks across all streams), # returning a list of non-lazy StreamValues. with self.assertNumQueries(1): results = stream_block.bulk_to_python( [ [ {"type": "heading", "value": "interesting pages"}, {"type": "page", "value": 2}, {"type": "page", "value": 3}, ], [ {"type": "heading", "value": "pages written by dogs"}, {"type": "woof", "value": "woof woof"}, ], [ {"type": "heading", "value": "boring pages"}, {"type": "page", "value": 4}, ], ] ) # If bulk_to_python has indeed given us non-lazy StreamValues, then no further queries # should be performed when iterating over its child blocks. with self.assertNumQueries(0): block_types = [[block.block_type for block in stream] for stream in results] self.assertEqual( block_types, [ ["heading", "page", "page"], ["heading"], ["heading", "page"], ], ) with self.assertNumQueries(0): block_values = [[block.value for block in stream] for stream in results] self.assertEqual( block_values, [ ["interesting pages", Page.objects.get(id=2), Page.objects.get(id=3)], ["pages written by dogs"], ["boring pages", Page.objects.get(id=4)], ], ) def test_extract_references(self): block = blocks.StreamBlock( [ ("page", blocks.PageChooserBlock()), ("heading", blocks.CharBlock()), ] ) christmas_page = Page.objects.get(slug="christmas") saint_patrick_page = Page.objects.get(slug="saint-patrick") self.assertListEqual( list( block.extract_references( block.to_python( [ { "id": "block1", "type": "heading", "value": "Some events that you might like", }, { "id": "block2", "type": "page", "value": christmas_page.id, }, { "id": "block3", "type": "page", "value": saint_patrick_page.id, }, ] ) ) ), [ (Page, str(christmas_page.id), "page", "block2"), (Page, str(saint_patrick_page.id), "page", "block3"), ], ) class TestPageChooserBlock(TestCase): fixtures = ["test.json"] def test_serialize(self): """The value of a PageChooserBlock (a Page object) should serialize to an ID""" block = blocks.PageChooserBlock() christmas_page = Page.objects.get(slug="christmas") self.assertEqual(block.get_prep_value(christmas_page), christmas_page.id) # None should serialize to None self.assertIsNone(block.get_prep_value(None)) def test_deserialize(self): """The serialized value of a PageChooserBlock (an ID) should deserialize to a Page object""" block = blocks.PageChooserBlock() christmas_page = Page.objects.get(slug="christmas") self.assertEqual(block.to_python(christmas_page.id), christmas_page) # None should deserialize to None self.assertIsNone(block.to_python(None)) def test_adapt(self): from wagtail.admin.widgets.chooser import AdminPageChooser block = blocks.PageChooserBlock( help_text="pick a page, any page", description="A featured page" ) block.set_name("test_pagechooserblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[0], "test_pagechooserblock") self.assertIsInstance(js_args[1], AdminPageChooser) self.assertEqual(js_args[1].target_models, [Page]) self.assertFalse(js_args[1].can_choose_root) self.assertEqual( js_args[2], { "label": "Test pagechooserblock", "description": "A featured page", "required": True, "icon": "doc-empty-inverse", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "helpText": "pick a page, any page", "classname": "w-field w-field--model_choice_field w-field--admin_page_chooser", "showAddCommentButton": True, "strings": {"ADD_COMMENT": "Add Comment"}, }, ) def test_adapt_with_target_model_string(self): block = blocks.PageChooserBlock( help_text="pick a page, any page", page_type="tests.SimplePage" ) block.set_name("test_pagechooserblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[1].target_models, [SimplePage]) def test_adapt_with_target_model_literal(self): block = blocks.PageChooserBlock( help_text="pick a page, any page", page_type=SimplePage ) block.set_name("test_pagechooserblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[1].target_models, [SimplePage]) def test_adapt_with_target_model_multiple_strings(self): block = blocks.PageChooserBlock( help_text="pick a page, any page", page_type=["tests.SimplePage", "tests.EventPage"], ) block.set_name("test_pagechooserblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[1].target_models, [SimplePage, EventPage]) def test_adapt_with_target_model_multiple_literals(self): block = blocks.PageChooserBlock( help_text="pick a page, any page", page_type=[SimplePage, EventPage] ) block.set_name("test_pagechooserblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[1].target_models, [SimplePage, EventPage]) def test_adapt_with_can_choose_root(self): block = blocks.PageChooserBlock( help_text="pick a page, any page", can_choose_root=True ) block.set_name("test_pagechooserblock") js_args = FieldBlockAdapter().js_args(block) self.assertTrue(js_args[1].can_choose_root) def test_form_response(self): block = blocks.PageChooserBlock() christmas_page = Page.objects.get(slug="christmas") value = block.value_from_datadict({"page": str(christmas_page.id)}, {}, "page") self.assertEqual(value, christmas_page) empty_value = block.value_from_datadict({"page": ""}, {}, "page") self.assertIsNone(empty_value) def test_clean(self): required_block = blocks.PageChooserBlock() nonrequired_block = blocks.PageChooserBlock(required=False) christmas_page = Page.objects.get(slug="christmas") self.assertEqual(required_block.clean(christmas_page), christmas_page) with self.assertRaises(ValidationError): required_block.clean(None) self.assertEqual(nonrequired_block.clean(christmas_page), christmas_page) self.assertIsNone(nonrequired_block.clean(None)) def test_target_model_default(self): block = blocks.PageChooserBlock() self.assertEqual(block.target_model, Page) def test_target_model_string(self): block = blocks.PageChooserBlock(page_type="tests.SimplePage") self.assertEqual(block.target_model, SimplePage) def test_target_model_literal(self): block = blocks.PageChooserBlock(page_type=SimplePage) self.assertEqual(block.target_model, SimplePage) def test_target_model_multiple_strings(self): block = blocks.PageChooserBlock( page_type=["tests.SimplePage", "tests.EventPage"] ) self.assertEqual(block.target_model, Page) def test_target_model_multiple_literals(self): block = blocks.PageChooserBlock(page_type=[SimplePage, EventPage]) self.assertEqual(block.target_model, Page) def test_deconstruct_target_model_default(self): block = blocks.PageChooserBlock() self.assertEqual( block.deconstruct(), ("wagtail.blocks.PageChooserBlock", (), {}) ) def test_deconstruct_target_model_string(self): block = blocks.PageChooserBlock(page_type="tests.SimplePage") self.assertEqual( block.deconstruct(), ( "wagtail.blocks.PageChooserBlock", (), {"page_type": ["tests.SimplePage"]}, ), ) def test_deconstruct_target_model_literal(self): block = blocks.PageChooserBlock(page_type=SimplePage) self.assertEqual( block.deconstruct(), ( "wagtail.blocks.PageChooserBlock", (), {"page_type": ["tests.SimplePage"]}, ), ) def test_deconstruct_target_model_multiple_strings(self): block = blocks.PageChooserBlock( page_type=["tests.SimplePage", "tests.EventPage"] ) self.assertEqual( block.deconstruct(), ( "wagtail.blocks.PageChooserBlock", (), {"page_type": ["tests.SimplePage", "tests.EventPage"]}, ), ) def test_deconstruct_target_model_multiple_literals(self): block = blocks.PageChooserBlock(page_type=[SimplePage, EventPage]) self.assertEqual( block.deconstruct(), ( "wagtail.blocks.PageChooserBlock", (), {"page_type": ["tests.SimplePage", "tests.EventPage"]}, ), ) def test_bulk_to_python(self): page_ids = [2, 3, 4, 5] expected_pages = Page.objects.filter(pk__in=page_ids) block = blocks.PageChooserBlock() with self.assertNumQueries(1): pages = block.bulk_to_python(page_ids) self.assertSequenceEqual(pages, expected_pages) def test_bulk_to_python_distinct_instances(self): page_ids = [2, 2] block = blocks.PageChooserBlock() with self.assertNumQueries(1): pages = block.bulk_to_python(page_ids) # Ensure that the two retrieved pages are distinct instances self.assertIsNot(pages[0], pages[1]) def test_extract_references(self): block = blocks.PageChooserBlock() christmas_page = Page.objects.get(slug="christmas") self.assertListEqual( list(block.extract_references(christmas_page)), [(Page, str(christmas_page.id), "", "")], ) # None should not yield any references self.assertListEqual(list(block.extract_references(None)), []) class TestStaticBlock(unittest.TestCase): def test_adapt_with_constructor(self): block = blocks.StaticBlock( admin_text="Latest posts - This block doesn't need to be configured, it will be displayed automatically", template="tests/blocks/posts_static_block.html", ) block.set_name("posts_static_block") js_args = StaticBlockAdapter().js_args(block) self.assertEqual(js_args[0], "posts_static_block") self.assertEqual( js_args[1], { "text": "Latest posts - This block doesn't need to be configured, it will be displayed automatically", "icon": "placeholder", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "label": "Posts static block", "description": "", }, ) def test_adapt_with_subclass(self): class PostsStaticBlock(blocks.StaticBlock): class Meta: admin_text = "Latest posts - This block doesn't need to be configured, it will be displayed automatically" template = "tests/blocks/posts_static_block.html" block = PostsStaticBlock() block.set_name("posts_static_block") js_args = StaticBlockAdapter().js_args(block) self.assertEqual(js_args[0], "posts_static_block") self.assertEqual( js_args[1], { "text": "Latest posts - This block doesn't need to be configured, it will be displayed automatically", "icon": "placeholder", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "label": "Posts static block", "description": "", }, ) def test_adapt_with_subclass_displays_default_text_if_no_admin_text(self): class LabelOnlyStaticBlock(blocks.StaticBlock): class Meta: label = "Latest posts" block = LabelOnlyStaticBlock() block.set_name("posts_static_block") js_args = StaticBlockAdapter().js_args(block) self.assertEqual(js_args[0], "posts_static_block") self.assertEqual( js_args[1], { "text": "Latest posts: this block has no options.", "icon": "placeholder", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "label": "Latest posts", "description": "", }, ) def test_adapt_with_subclass_displays_default_text_if_no_admin_text_and_no_label( self, ): class NoMetaStaticBlock(blocks.StaticBlock): pass block = NoMetaStaticBlock() block.set_name("posts_static_block") js_args = StaticBlockAdapter().js_args(block) self.assertEqual(js_args[0], "posts_static_block") self.assertEqual( js_args[1], { "text": "Posts static block: this block has no options.", "icon": "placeholder", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "label": "Posts static block", "description": "", }, ) def test_adapt_works_with_mark_safe(self): block = blocks.StaticBlock( admin_text=mark_safe( "Latest posts - This block doesn't need to be configured, it will be displayed automatically" ), template="tests/blocks/posts_static_block.html", ) block.set_name("posts_static_block") js_args = StaticBlockAdapter().js_args(block) self.assertEqual(js_args[0], "posts_static_block") self.assertEqual( js_args[1], { "html": "Latest posts - This block doesn't need to be configured, it will be displayed automatically", "icon": "placeholder", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "label": "Posts static block", "description": "", }, ) def test_get_default(self): block = blocks.StaticBlock() default_value = block.get_default() self.assertIsNone(default_value) def test_render(self): block = blocks.StaticBlock(template="tests/blocks/posts_static_block.html") result = block.render(None) self.assertEqual(result, "PostsStaticBlock template
") def test_render_without_template(self): block = blocks.StaticBlock() result = block.render(None) self.assertEqual(result, "") def test_serialize(self): block = blocks.StaticBlock() result = block.get_prep_value(None) self.assertIsNone(result) def test_deserialize(self): block = blocks.StaticBlock() result = block.to_python(None) self.assertIsNone(result) def test_normalize(self): """ StaticBlock.normalize always returns None, as a StaticBlock has no value """ self.assertIsNone(blocks.StaticBlock().normalize(11)) class TestDateBlock(TestCase): def test_adapt(self): from wagtail.admin.widgets.datetime import AdminDateInput block = blocks.DateBlock() block.set_name("test_dateblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[0], "test_dateblock") self.assertIsInstance(js_args[1], AdminDateInput) self.assertEqual(js_args[1].js_format, "Y-m-d") self.assertEqual( js_args[2], { "label": "Test dateblock", "description": "", "required": True, "icon": "date", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "classname": "w-field w-field--date_field w-field--admin_date_input", "showAddCommentButton": True, "strings": {"ADD_COMMENT": "Add Comment"}, }, ) def test_adapt_with_format(self): block = blocks.DateBlock(format="%d.%m.%Y") block.set_name("test_dateblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[1].js_format, "d.m.Y") class TestTimeBlock(TestCase): def test_adapt(self): from wagtail.admin.widgets.datetime import AdminTimeInput block = blocks.TimeBlock() block.set_name("test_timeblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[0], "test_timeblock") self.assertIsInstance(js_args[1], AdminTimeInput) self.assertEqual(js_args[1].js_format, "H:i") self.assertEqual( js_args[2], { "label": "Test timeblock", "description": "", "required": True, "icon": "time", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "classname": "w-field w-field--time_field w-field--admin_time_input", "showAddCommentButton": True, "strings": {"ADD_COMMENT": "Add Comment"}, }, ) def test_adapt_with_format(self): block = blocks.TimeBlock(format="%H:%M:%S") block.set_name("test_timeblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[1].js_format, "H:i:s") class TestDateTimeBlock(TestCase): def test_adapt(self): from wagtail.admin.widgets.datetime import AdminDateTimeInput block = blocks.DateTimeBlock() block.set_name("test_datetimeblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[0], "test_datetimeblock") self.assertIsInstance(js_args[1], AdminDateTimeInput) self.assertEqual(js_args[1].js_format, "Y-m-d H:i") self.assertEqual( js_args[2], { "label": "Test datetimeblock", "description": "", "required": True, "icon": "date", "blockDefId": block.definition_prefix, "isPreviewable": block.is_previewable, "classname": "w-field w-field--date_time_field w-field--admin_date_time_input", "showAddCommentButton": True, "strings": {"ADD_COMMENT": "Add Comment"}, }, ) def test_adapt_with_format(self): block = blocks.DateTimeBlock(format="%d.%m.%Y %H:%M") block.set_name("test_datetimeblock") js_args = FieldBlockAdapter().js_args(block) self.assertEqual(js_args[1].js_format, "d.m.Y H:i") class TestSystemCheck(TestCase): def test_name_cannot_contain_non_alphanumeric(self): block = blocks.StreamBlock( [ ("heading", blocks.CharBlock()), ("rich+text", blocks.RichTextBlock()), ] ) errors = block.check() self.assertEqual(len(errors), 1) self.assertEqual(errors[0].id, "wagtailcore.E001") self.assertEqual( errors[0].hint, "Block names should follow standard Python conventions for variable names: alphanumeric and underscores, and cannot begin with a digit", ) self.assertEqual(errors[0].obj, block.child_blocks["rich+text"]) def test_name_must_be_nonempty(self): block = blocks.StreamBlock( [ ("heading", blocks.CharBlock()), ("", blocks.RichTextBlock()), ] ) errors = block.check() self.assertEqual(len(errors), 1) self.assertEqual(errors[0].id, "wagtailcore.E001") self.assertEqual(errors[0].hint, "Block name cannot be empty") self.assertEqual(errors[0].obj, block.child_blocks[""]) def test_name_cannot_contain_spaces(self): block = blocks.StreamBlock( [ ("heading", blocks.CharBlock()), ("rich text", blocks.RichTextBlock()), ] ) errors = block.check() self.assertEqual(len(errors), 1) self.assertEqual(errors[0].id, "wagtailcore.E001") self.assertEqual(errors[0].hint, "Block names cannot contain spaces") self.assertEqual(errors[0].obj, block.child_blocks["rich text"]) def test_name_cannot_contain_dashes(self): block = blocks.StreamBlock( [ ("heading", blocks.CharBlock()), ("rich-text", blocks.RichTextBlock()), ] ) errors = block.check() self.assertEqual(len(errors), 1) self.assertEqual(errors[0].id, "wagtailcore.E001") self.assertEqual(errors[0].hint, "Block names cannot contain dashes") self.assertEqual(errors[0].obj, block.child_blocks["rich-text"]) def test_name_cannot_begin_with_digit(self): block = blocks.StreamBlock( [ ("heading", blocks.CharBlock()), ("99richtext", blocks.RichTextBlock()), ] ) errors = block.check() self.assertEqual(len(errors), 1) self.assertEqual(errors[0].id, "wagtailcore.E001") self.assertEqual(errors[0].hint, "Block names cannot begin with a digit") self.assertEqual(errors[0].obj, block.child_blocks["99richtext"]) def test_system_checks_recurse_into_lists(self): failing_block = blocks.RichTextBlock() block = blocks.StreamBlock( [ ( "paragraph_list", blocks.ListBlock( blocks.StructBlock( [ ("heading", blocks.CharBlock()), ("rich text", failing_block), ] ) ), ) ] ) errors = block.check() self.assertEqual(len(errors), 1) self.assertEqual(errors[0].id, "wagtailcore.E001") self.assertEqual(errors[0].hint, "Block names cannot contain spaces") self.assertEqual(errors[0].obj, failing_block) def test_system_checks_recurse_into_streams(self): failing_block = blocks.RichTextBlock() block = blocks.StreamBlock( [ ( "carousel", blocks.StreamBlock( [ ( "text", blocks.StructBlock( [ ("heading", blocks.CharBlock()), ("rich text", failing_block), ] ), ) ] ), ) ] ) errors = block.check() self.assertEqual(len(errors), 1) self.assertEqual(errors[0].id, "wagtailcore.E001") self.assertEqual(errors[0].hint, "Block names cannot contain spaces") self.assertEqual(errors[0].obj, failing_block) def test_system_checks_recurse_into_structs(self): failing_block_1 = blocks.RichTextBlock() failing_block_2 = blocks.RichTextBlock() block = blocks.StreamBlock( [ ( "two_column", blocks.StructBlock( [ ( "left", blocks.StructBlock( [ ("heading", blocks.CharBlock()), ("rich text", failing_block_1), ] ), ), ( "right", blocks.StructBlock( [ ("heading", blocks.CharBlock()), ("rich text", failing_block_2), ] ), ), ] ), ) ] ) errors = block.check() self.assertEqual(len(errors), 2) self.assertEqual(errors[0].id, "wagtailcore.E001") self.assertEqual(errors[0].hint, "Block names cannot contain spaces") self.assertEqual(errors[0].obj, failing_block_1) self.assertEqual(errors[1].id, "wagtailcore.E001") self.assertEqual(errors[1].hint, "Block names cannot contain spaces") self.assertEqual(errors[1].obj, failing_block_2) class TestTemplateRendering(TestCase): def test_render_with_custom_context(self): block = CustomLinkBlock() value = block.to_python({"title": "Torchbox", "url": "http://torchbox.com/"}) context = {"classname": "important"} result = block.render(value, context) self.assertEqual( result, 'Torchbox' ) @unittest.expectedFailure # TODO(telepath) def test_render_with_custom_form_context(self): block = CustomLinkBlock() value = block.to_python({"title": "Torchbox", "url": "http://torchbox.com/"}) result = block.render_form(value, prefix="my-link-block") self.assertIn('data-prefix="my-link-block"', result) self.assertIn("Hello from get_form_context!
", result) class TestIncludeBlockTag(TestCase): def test_include_block_tag_with_boundblock(self): """ The include_block tag should be able to render a BoundBlock's template while keeping the parent template's context """ block = blocks.CharBlock(template="tests/blocks/heading_block.html") bound_block = block.bind("bonjour") result = render_to_string( "tests/blocks/include_block_test.html", { "test_block": bound_block, "language": "fr", }, ) self.assertIn('