【发布时间】:2021-12-29 13:22:12
【问题描述】:
我正在尝试在 StructBlock 上运行一些单元测试,它由普通块字段和 StreamBlock 组成。
我遇到的问题是我可以构建一个渲染块的测试,但我无法测试 StreamBlock 验证(即,我无法测试块的clean())
堆栈
- Python 3.9.6
- Django 3.2
- 鹡鸰 2.13
- pytest 6.2
- pytest-django 4.4
块定义
MyStructBlock
class MyStructBlock(blocks.StructBlock):
image = ImageChooserBlock()
heading = blocks.CharBlock(required=True)
description = blocks.RichTextBlock(features=["bold", "italic"])
links = blocks.StreamBlock([("link", LinkBlock())], icon="link", min_num=1, max_num=6)
class Meta:
icon = "list-ul"
template = "blocks/two_column_with_link_list_block.html"
链接块
class LinkBlock(blocks.StructBlock):
link_text = blocks.CharBlock()
internal_link = blocks.PageChooserBlock()
internal_document = DocumentChooserBlock()
external_link = blocks.URLBlock()
通过这个设置,我创建了这种block_definition:
{
'image': <Image: Thumbnail of subject>,
'heading': 'SomeText',
'description': 'Hello, Son',
'links':
[
{'value':
{
'link_text': 'Walk trip thought region.',
'internal_link': None,
'document_link': None,
'external_link': 'www.example.com'
}
},
{'value': {...}},
{'value': {...}},
]
}
那么这样的测试就可以正常工作了:
def test_structure():
my_struct_block = MyStructBlock()
block_def = block_definition
rendered_block_html = BeautifulSoup(my_struct_block.render(value=block_def)))
assert <<THINGS ABOUT THE STRUCTURE>>
块渲染,一切都很好,但是当我尝试clean块时,一切都开始横向移动。
def test_validation():
my_struct_block = MyStructBlock()
block_def = block_definition
rendered_block_html = BeautifulSoup(my_struct_block.render(my_struct_block.clean(block_def)))
会产生这样的结果:
self = <wagtail.core.blocks.field_block.RichTextBlock object at 0x7f874f430580>, value = 'Hello, Son'
def value_for_form(self, value):
# Rich text editors take the source-HTML string as input (and takes care
# of expanding it for the purposes of the editor)
> return value.source
E AttributeError: 'str' object has no attribute 'source'
.direnv/python-3.9.6/lib/python3.9/site-packages/wagtail/core/blocks/field_block.py:602: AttributeError
哪个描述性足够——我知道它需要一个 Richtext Block 定义——但为什么会有区别?
注意:我尝试使用RichText 将block_definition 定义为期望RichText 的字段的值,但失败了。如果我删除 RichText 字段,则清理将在我用来定义 LinkBlock 的 dicts 上失败。
问题
是否有一种规范的方法来设置这样的测试来处理复杂的块,以便块定义的公共来源可以测试render 以及clean 和render?或者,这种类型的块在某种程度上是否需要一种集成方法,在该方法中我构建一个页面,其中添加了复杂的块为stream_data,然后请求该页面并使用响应的呈现?
【问题讨论】: