Testing Zope Page Templates in unittests

testing zope page templates in unittests Articles

This article describes simple and easy way to test ZopePageTemplate object outside Zope’s environment

If we want to unittest a page that is rendered in ZMI and uses ZopePageTemplates its not so easy. Because they are called in web application context they require some data. In most cases this data is required for template to render and it is not connected to logic we put in it. So why can’t just cheat Zope’s rendering mechanism to get some useful result?

Below there is code that wraps object which will be a context for template. It adds some required information, which is very essential to render successfully. It doesn’t matter that this data is mostly empty. The idea is to provide those objects within the context to fulfill what rendering machinery needs.

def wrapObjectForPageTemplates (object):
“””
Do some tricks to enable rendering Page Templates
offline by object
“””
from AccessControl import getSecurityManager
from ZPublisher. BaseRequest import BaseRequest as Request
from ZPublisher. HTTPResponse import HTTPResponse as Response
from OFS. SimpleItem import SimpleItem

#Function that creates dummy REQUEST object
def getRequest ():
request = Request()
request. SESSION = <>
request. RESPONSE = Response()
request._steps = []
request[ ‘BASEPATH1’ ] = ”
request[ ‘URL’ ] = ”
return request

class SimpleObject (SimpleItem):
pass

#Monkey patch PageTemplateFile for tests
def getPhysicalRoot (self):
return self
PageTemplateFile. getPhysicalRoot = getPhysicalRoot

#Patch user role to simulate Manager call
user = getSecurityManager().getUser()
user. roles = tuple (user. roles) + ( ‘Manager’ ,)

#Add some dummy variables
from DateTime import DateTime
object. REQUEST = getRequest ()
object. manage_page_header = ”
object. ZopeTime = DateTime
object. HelpSys = SimpleObject()
object. HelpSys. helpLink = lambda a, b : ”
return object

If we have template we want to test in context of class instance we can create test method that looks like this. It instantiates MyClass object, wraps it with required information and calls the template myTemplate. Of course we can pass any kind of parameters, but REQUEST is necessary. The result of the call is string with rendered template. Then we can test if there are strings that will cause test failure or success.

from ZPublisher. BaseRequest import BaseRequest as Request

def test_myTemplate (self):
obj = MyClass()
obj = wrapObjectForPageTemplates (obj)
result = obj. myTemplate(REQUEST=Request())
#result is a string containing rendered template
self. assertEqual(result. find ( ‘error message’ )>= 0 , False )

This code works in Zope 2.7, 2.8, at least it was used for this versions.

Rate article
Plone and Zope developer
Add a comment