我有一个简单的事件处理程序,它查找实际更改的内容(它是为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在使用表单时是自动地这样做的,但是我想用一个单元测试来测试它。
发布于 2016-02-18 18:02:05
event.description名义上是一个IModificationDescription对象,本质上是一个IAttributes对象列表:每个属性对象都有一个接口(例如模式)和属性(例如字段名列表)被修改。
最简单的解决方案是为每个更改的字段创建一个zope.lifecycleevent.Attributes对象,并将其作为参数传递给事件构造函数--例如:
# imports elided...
changelog = [
Attributes(IFoo, 'some_fieldname_here'),
Attributes(IMyBehaviorHere, 'some_behavior_provided_fieldname_here',
]
notify(ObjectModifiedEvent(context, *changelog)发布于 2016-02-18 16:13:18
我也可能误解了一些东西,但是您可以在代码中简单地触发事件,使用类似于z3c.form (类似于@keul的注释)的参数?
在plone4.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。
您应该在那里设置一个断点,以检查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对整个逻辑的嘲弄对未来可能是个坏主意,如果代码发生了变化,并且工作方式可能完全不同,那么您的测试仍然会很好。
https://stackoverflow.com/questions/35475391
复制相似问题