如何以编程方式创建像z3c.form这样的详细事件?

2024-10-02 10:31:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的event handler查找实际更改的内容(它是为IObjectModifiedEvent事件注册的),代码如下所示:

def on_change_do_something(obj, event):
    modified = False
    # check if the publication has changed
    for change in event.descriptions:
        if change.interface == IPublication:
            modified = True
            break

    if modified:
        # do something

所以我的问题是:如何以编程方式生成这些描述?我在用plone.app.灵巧在任何地方,所以z3c.form在使用表单时都是自动执行的,但是我想用unittest来测试它。你知道吗


Tags: 代码eventfalseobj内容ifondef
2条回答

你知道吗事件描述名义上是一个IModificationDescription对象,本质上是一个IAttributes对象列表:每个属性对象都有一个修改过的接口(例如schema)和属性(例如字段名列表)。你知道吗

最简单的解决方案是创建一个zope.lifecycleevent.Attributes属性对象,并作为参数传递给事件构造函数示例:

# imports elided...

changelog = [
    Attributes(IFoo, 'some_fieldname_here'),
    Attributes(IMyBehaviorHere, 'some_behavior_provided_fieldname_here',
    ]
notify(ObjectModifiedEvent(context, *changelog)

我也可能误解了一些东西,但是您可以在代码中简单地触发事件,使用与z3c.form相同的参数(类似于@keul的注释)?你知道吗

在Plone 4.3.x中进行了一个简短的搜索之后,我在z3c.form.form中找到了这个:

def applyChanges(self, data):
    content = self.getContent()
    changes = applyChanges(self, content, data)
    # ``changes`` is a dictionary; if empty, there were no changes
    if changes:
        # Construct change-descriptions for the object-modified event
        descriptions = []
        for interface, names in changes.items():
            descriptions.append(
                zope.lifecycleevent.Attributes(interface, *names))
        # Send out a detailed object-modified event
        zope.event.notify(
            zope.lifecycleevent.ObjectModifiedEvent(content, *descriptions))
    return changes

您需要两个测试用例,一个什么都不做,另一个遍历您的代码。你知道吗

applyChanges在同一个模块中(z3c。窗体。窗体)它遍历表单字段并计算包含所有更改的dict。你知道吗

您应该在那里设置一个断点来检查dict是如何构建的。你知道吗

之后,您可以在测试用例中执行相同的操作。你知道吗

这样您就可以编写可读的测试用例。你知道吗

def test_do_something_in_event(self)

    content = self.get_my_content()
    descriptions = self.get_event_descriptions()

    zope.event.notify(zope.lifecycleevent.ObjectModifiedEvent(content, *descriptions))

    self.assertSomething(...)        

对于未来来说,模仿整个逻辑可能是个坏主意,如果代码发生了变化,并且可能工作方式完全不同,那么您的测试仍然可以。你知道吗

相关问题 更多 >

    热门问题