如何为Wagtail RichText块内容添加单元测试?

huangapple go评论43阅读模式
英文:

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 = &quot;&quot;&quot;&lt;p&gt;Some paragraph&lt;/p&gt;&quot;&quot;&quot;

block_tuple = (
    &quot;rich_text&quot;, 
    RichText(block_content),
)

expected_block_tuple = (
    &quot;rich_text&quot;,
    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)

huangapple
  • 本文由 发表于 2023年6月9日 01:45:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76434460.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定