英文:
How to add a unit test for Wagtail RichText block contents?
问题
I can help with the translation:
在为Wagtail CMS项目编写内容导入器。在我的导入器中,我将字符串解析为StreamField的RichText块:
from wagtail.rich_text import RichText
block_content = """<p>一些段落</p>"""
block_tuple = (
"rich_text",
RichText(block_content),
)
expected_block_tuple = (
"rich_text",
RichText(block_content),
)
assertEqual(
block_tuple,
expected_block_tuple
)
这个单元测试非常重要,可以减少我们导入脚本中丢失数据的可能性。
然而,断言失败,因为块元组具有不同的字符串表示,如下所示:
> ('rich_text', <wagtail.rich_text.RichText object at 0x7ff683745b50>)
如何编写断言以确保解析的RichText块的输出与预期值匹配?
英文:
I am writing content importers for a Wagtail CMS project. In my importers, I parse strings to a RichText block for a StreamField:
from wagtail.rich_text import RichText
block_content = """<p>Some paragraph</p>"""
block_tuple = (
"rich_text",
RichText(block_content),
)
expected_block_tuple = (
"rich_text",
RichText(block_content),
)
assertEqual(
block_tuple,
expected_block_tuple
)
This unit test is really important to reduce the likelihood of losing data in our import scripts.
However, the assertion fails since the block tuples have different string representations, like the following.
> ('rich_text', <wagtail.rich_text.RichText object at 0x7ff683745b50>)
How can I write an assertion to ensure the output of the parsed RichText block matches an expected value?
答案1
得分: 1
我已在Wagtail上打开了这个问题(https://github.com/wagtail/wagtail/issues/10523) - 两个具有相同值的RichText
对象确实应该被视为相等,但由于RichText
目前没有实现__eq__
方法,所以这不是这种情况。
目前的解决方法是,您可以检查这两个对象的source
属性是否相等:
block_tuple_source = (block_tuple[0], block_tuple[1].source)
expected_block_tuple_source = (expected_block_tuple[0], expected_block_tuple[1].source)
assertEqual(block_tuple_source, expected_block_tuple_source)
英文:
I've opened this as an issue on Wagtail (https://github.com/wagtail/wagtail/issues/10523) - two RichText
objects with the same value really ought to compare as equal, but this isn't the case because RichText
doesn't currently implement an __eq__
method.
As a workaround for now, you can check the source
attribute on the two objects for equality:
block_tuple_source = (block_tuple[0], block_tuple[1].source)
expected_block_tuple_source = (expected_block_tuple[0], expected_block_tuple[1].source)
assertEqual(block_tuple_source, expected_block_tuple_source)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论