简体   繁体   中英

unit testing buttonAndHandler with a z3c.form

I am simply looking to write a unit test that tests the methods in my dexterity SchemaForm that use the buttonAndHandler, but I wasn't able to find anything appropriate in either the z3c.form documentation nor the Dexterity Developer Manual. I believe I'm getting tripped up on the decorator behavior but I don't know how I should be programmatically calling these methods.

form = self.rf.restrictedTraverse('add-file')
#mform = getMultiAdapter((self.rf,self.request), name='add-file')

Using restrictedTraverse or getMultiAdapter yields the same object. So if I want to call form.addFileSendToEditors I pass the form as the first variable and what for "action"?

Basically you could get the handlers from the form and call the manually.

This is an example with a regular z3c.form and a Dexterity add form.

>>> form_view = self.rf.restrictedTraverse('add-file')

# If your form is a Dexterity DefaultAddForm view.
>>> form_view
<plone.dexterity.browser.add.DefaultAddView object at 0x10cbf0950>
# Get the form from the instance
>>> form_view.form
<class 'plone.dexterity.browser.add.DefaultAddForm'>


# Than you can get all handlers
>>> form_view.form.handlers
<Handlers [<Handler for <Button 'save' u'Save'>>, <Handler for <Button 'cancel' u'Cancel'>>]
# and all buttons
form_view.form.buttons.items()
[('save', <Button 'save' u'Save'>), ('cancel', <Button 'cancel' u'Cancel'>)]

# In _handlers you can see the buttons, with the corresponding handlers
form_view.form.handlers._handlers
((<Button 'save' u'Save'>, <Handler for <Button 'save' u'Save'>>), (<Button 'cancel' u'Cancel'>, Handler for <Button 'cancel' u'Cancel'>>))

# You can also get the handler by button
>>> save_button = form_view.form.buttons.items()[0]
>>> save_handler = form_view.form.handlers.getHandler(save_button)
<Handler for <Button 'save' u'Save'>>

# Once you have your handler, you can call it directly
save_handler.func(form_view.form_instance, save_button)

It depends on what you are doing if you have to setup a little bit more, to make your test work. You did not give us enough informations about what you are doing in you handler.

This is taken from the z3c.form documentation: I did not run this code for myself.

# You can test your actions also this, probably more readable :-)
from z3c.form.testing import TestRequest
from z3c.form import button

>>> request = TestRequest(form={'form.buttons.save': 'Save'})
>>> actions = button.ButtonActions(form_view.form_instance, request, None)
>>> actions.update()
>>> actions.execute()
# This executes your Save actions. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM