我有一个简单的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.dexterity,所以z3c.form在使用表单时会自动执行,但我想用单元测试来测试它。
答案 0 :(得分:3)
event.description名义上是一个IModificationDescription对象,它本质上是一个IAttributes对象列表:每个Attributes对象都有一个接口(例如架构)和属性(例如字段名称列表)被修改。
最简单的解决方案是为每个更改的字段创建一个zope.lifecycleevent.Attributes对象,并将其作为参数传递给事件构造函数 - 例如:
# imports elided...
changelog = [
Attributes(IFoo, 'some_fieldname_here'),
Attributes(IMyBehaviorHere, 'some_behavior_provided_fieldname_here',
]
notify(ObjectModifiedEvent(context, *changelog)
答案 1 :(得分:0)
我也可能误解了一些东西,但你可以简单地在代码中触发事件,使用与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.form.form)中,它遍历表单字段并计算包含所有更改的字典。
你应该在那里设置一个断点来检查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(...)
嘲笑整个逻辑的IMHO对未来可能是一个坏主意,如果代码改变并且可能完全不同,你的测试仍然会很好。