quick hack to unit-test a browserview that depends on plone.protect
Plone provides the plone.protect.authenticator view to protect against Cross Site Request Forgery (CSRF).
However, this makes unit-testing such code slightly more difficult. I'm currently using the following hack, if anyone can point me to a better direction.
Imagine a BrowserView Foo with the following __call__
class Foo(BrowserView):
...
def __call__(self):
...
authenticator = self.context.restrictedTraverse('@@authenticator', None)
if not authenticator.verify():
raise Forbidden
...
Essentially, this means you need to provide the correct _authenticator formvalue in self.app.REQUEST.form in your unittest. The following method handles this:
def _getauth(self):
import re
authenticator = self.portal.restrictedTraverse("@@authenticator")
html = authenticator.authenticator()
handle = re.search('value="(.*)"', html).groups()[0]
return handle
You can use it in your test as follows:
def test_foo(self):
self.app.REQUEST.form['_authenticator'] = self._getauth()
foo = self.portal.restrictedTraverse("@@foo")
foo()
Works for me! (at least for now)