Skip to content. | Skip to navigation

Sections
Personal tools
What is this?
Hi, my name is Tom Lazar and I'm a Plone and Zope developer based in Berlin, Germany and this is my personal and professional (no big difference, really...) website.
 

Annotatable TestRequest

Filed Under:

How to test browser views without (the overhead of) a browser test in Zope and Plone

Browser tests aren't the only (and often not the best) way to test browser views. Much nicer to just instantiate the view directly, like so:

>>> view = FooView(context, request)

Then just call any method of the view directly:

>>> self.assertEqual(view.foo(), [])

But where to get the request? Enter TestRequest:

>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> view = FooView(context, request)
>>> self.assertEqual(view.foo(), [])

However, sometimes this can result in the following error:

TypeError: ('Could not adapt', <zope.publisher.browser.TestRequest instance URL=http://127.0.0.1>, 
    <InterfaceClass zope.annotation.interfaces.IAnnotations>)

In that case you additionally need to make the request object you've just created annotatable, like so:

>>> from zope.publisher.browser import TestRequest
>>> from zope.annotation.interfaces import IAttributeAnnotatable
>>> from zope.interface import alsoProvides
>>> request = TestRequest()
>>> alsoProvides(request, IAttributeAnnotatable)