Commit 015af31a authored by Julien Muchembled's avatar Julien Muchembled

MailTemplates: fix newlines in BaseMailTemplate.py (LF, no trailing space)

parent cd4ae3d6
# Copyright (c) 2005-2006 Simplistix Ltd # Copyright (c) 2005-2006 Simplistix Ltd
# #
# This Software is released under the MIT License: # This Software is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.html # http://www.opensource.org/licenses/mit-license.html
# See license.txt for more details. # See license.txt for more details.
import os import os
import rfc822 import rfc822
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from DateTime import DateTime from DateTime import DateTime
from email.MIMEMultipart import MIMEMultipart from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText from email.MIMEText import MIMEText
from App.class_init import default__class_init__ as InitializeClass from App.class_init import default__class_init__ as InitializeClass
from App.Common import package_home from App.Common import package_home
from MTMultipart import MTMultipart from MTMultipart import MTMultipart
from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
from Products.PageTemplates.PageTemplateFile import PageTemplateFile from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from ZPublisher import HTTPResponse from ZPublisher import HTTPResponse
# Configured using zope.conf in Zope 2.7.8, Zope 2.8.2, and above # Configured using zope.conf in Zope 2.7.8, Zope 2.8.2, and above
default_encoding = getattr(HTTPResponse,'default_encoding','iso-8859-15') default_encoding = getattr(HTTPResponse,'default_encoding','iso-8859-15')
class BaseMailTemplate: class BaseMailTemplate:
security = ClassSecurityInfo() security = ClassSecurityInfo()
_properties = () _properties = ()
ZScriptHTML_tryForm = None ZScriptHTML_tryForm = None
content_type = 'text/plain' content_type = 'text/plain'
mailhost = None mailhost = None
security.declarePrivate('_process') security.declarePrivate('_process')
def _process(self,kw): def _process(self,kw):
# sort out what encoding we're going to use # sort out what encoding we're going to use
encoding = kw.get('encoding', encoding = kw.get('encoding',
self.getProperty('encoding', self.getProperty('encoding',
default_encoding)) default_encoding))
text = self.__class__.__bases__[1].__call__(self,**kw) text = self.__class__.__bases__[1].__call__(self,**kw)
if not self.html(): if not self.html():
text = text.encode(encoding,'replace') text = text.encode(encoding,'replace')
# now turn the result into a MIMEText object # now turn the result into a MIMEText object
msg = MIMEText( msg = MIMEText(
text.replace('\r',''), text.replace('\r',''),
self.content_type.split('/')[1], self.content_type.split('/')[1],
encoding encoding
) )
# sort out what headers and addresses we're going to use # sort out what headers and addresses we're going to use
headers = {} headers = {}
values = {} values = {}
# headers from the headers property # headers from the headers property
for header in getattr(self,'headers',()): for header in getattr(self,'headers',()):
name,value = header.split(':',1) name,value = header.split(':',1)
headers[name]=value headers[name]=value
# headers from the headers parameter # headers from the headers parameter
headers_param = kw.get('headers',{}) headers_param = kw.get('headers',{})
headers.update(headers_param) headers.update(headers_param)
# values and some specific headers # values and some specific headers
for key,header in (('mfrom','From'), for key,header in (('mfrom','From'),
('mto','To'), ('mto','To'),
('mcc','Cc'), ('mcc','Cc'),
('mbcc','Bcc'), ('mbcc','Bcc'),
('subject','Subject')): ('subject','Subject')):
value = kw.get(key, value = kw.get(key,
headers_param.get(header, headers_param.get(header,
getattr(self, getattr(self,
key, key,
headers.get(header)))) headers.get(header))))
if value is not None: if value is not None:
values[key]=value values[key]=value
# turn some sequences in coma-seperated strings # turn some sequences in coma-seperated strings
if isinstance(value,tuple) or isinstance(value,list): if isinstance(value,tuple) or isinstance(value,list):
value = ', '.join(value) value = ', '.join(value)
# make sure we have no unicode headers # make sure we have no unicode headers
if isinstance(value,unicode): if isinstance(value,unicode):
value = value.encode(encoding) value = value.encode(encoding)
headers[header]=value headers[header]=value
# check required values have been supplied # check required values have been supplied
errors = [] errors = []
for param in ('mfrom','mto','subject'): for param in ('mfrom','mto','subject'):
if not values.get(param): if not values.get(param):
errors.append(param) errors.append(param)
if errors: if errors:
raise TypeError( raise TypeError(
'The following parameters were required by not specified: '+( 'The following parameters were required by not specified: '+(
', '.join(errors) ', '.join(errors)
)) ))
# add date header # add date header
headers['Date']=DateTime().rfc822() headers['Date']=DateTime().rfc822()
# turn headers into an ordered list for predictable header order # turn headers into an ordered list for predictable header order
keys = headers.keys() keys = headers.keys()
keys.sort() keys.sort()
return msg,values,[(key,headers[key]) for key in keys] return msg,values,[(key,headers[key]) for key in keys]
security.declarePrivate('_send') security.declarePrivate('_send')
def _send(self,mfrom,mto,msg): def _send(self,mfrom,mto,msg):
mailhost = self.restrictedTraverse(self.mailhost,None) mailhost = self.restrictedTraverse(self.mailhost,None)
if not getattr(mailhost,'meta_type',None) in ( if not getattr(mailhost,'meta_type',None) in (
'Mail Host','Maildrop Host' 'Mail Host','Maildrop Host'
): ):
raise RuntimeError( raise RuntimeError(
'Could not traverse to MailHost %r' % self.mailhost 'Could not traverse to MailHost %r' % self.mailhost
) )
mailhost._send(mfrom,mto,msg.as_string()) mailhost._send(mfrom,mto,msg.as_string())
security.declareProtected('View', 'send') security.declareProtected('View', 'send')
def send(self,**kw): def send(self,**kw):
msg,values,headers = self._process(kw) msg,values,headers = self._process(kw)
for header,value in headers: for header,value in headers:
msg[header]=value msg[header]=value
to_addrs = () to_addrs = ()
for key in ('mto', 'mcc', 'mbcc'): for key in ('mto', 'mcc', 'mbcc'):
v = values.get(key) v = values.get(key)
if v: if v:
if isinstance(v, basestring): if isinstance(v, basestring):
v = [rfc822.dump_address_pair(addr) for addr \ v = [rfc822.dump_address_pair(addr) for addr \
in rfc822.AddressList(v)] in rfc822.AddressList(v)]
to_addrs += tuple(v) to_addrs += tuple(v)
self._send(values['mfrom'], to_addrs, msg) self._send(values['mfrom'], to_addrs, msg)
security.declareProtected('View', '__call__') security.declareProtected('View', '__call__')
__call__ = send __call__ = send
security.declareProtected('View', 'as_message') security.declareProtected('View', 'as_message')
def as_message(self,**kw): def as_message(self,**kw):
msg,values,headers = self._process(kw) msg,values,headers = self._process(kw)
multipart_kw = {} multipart_kw = {}
#subtype = kw.get('subtype') #subtype = kw.get('subtype')
#if subtype: #if subtype:
# multipart_kw['_subtype'] = subtype # multipart_kw['_subtype'] = subtype
#boundary = kw.get('boundary') #boundary = kw.get('boundary')
#if boundary: #if boundary:
# multipart_kw['boundary'] = boundary # multipart_kw['boundary'] = boundary
multipart = MTMultipart(self, multipart = MTMultipart(self,
values['mfrom'], values['mfrom'],
values['mto'], values['mto'],
**multipart_kw) **multipart_kw)
# set the encoding for the container # set the encoding for the container
#multipart.set_charset(msg.get_charset()) #multipart.set_charset(msg.get_charset())
for header,value in headers: for header,value in headers:
multipart[header]=value multipart[header]=value
multipart.attach(msg) multipart.attach(msg)
return multipart return multipart
InitializeClass(BaseMailTemplate) InitializeClass(BaseMailTemplate)
# Copyright (c) 2005-2006 Simplistix Ltd # Copyright (c) 2005-2006 Simplistix Ltd
# #
# This Software is released under the MIT License: # This Software is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.html # http://www.opensource.org/licenses/mit-license.html
# See license.txt for more details. # See license.txt for more details.
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from AccessControl import getSecurityManager from AccessControl import getSecurityManager
from App.class_init import default__class_init__ as InitializeClass from App.class_init import default__class_init__ as InitializeClass
from Products.CMFCore.FSPageTemplate import FSPageTemplate from Products.CMFCore.FSPageTemplate import FSPageTemplate
from Products.CMFCore.DirectoryView import registerFileExtension from Products.CMFCore.DirectoryView import registerFileExtension
from Products.CMFCore.DirectoryView import registerMetaType from Products.CMFCore.DirectoryView import registerMetaType
from BaseMailTemplate import BaseMailTemplate from BaseMailTemplate import BaseMailTemplate
from MailTemplate import MailTemplate from MailTemplate import MailTemplate
class FSMailTemplate(BaseMailTemplate,FSPageTemplate): class FSMailTemplate(BaseMailTemplate,FSPageTemplate):
"Wrapper for Mail Template" "Wrapper for Mail Template"
security = ClassSecurityInfo() security = ClassSecurityInfo()
meta_type = 'Filesystem Mail Template' meta_type = 'Filesystem Mail Template'
def __init__(self, id, filepath, fullname=None, properties=None): def __init__(self, id, filepath, fullname=None, properties=None):
FSPageTemplate.__init__(self,id,filepath,fullname,properties) FSPageTemplate.__init__(self,id,filepath,fullname,properties)
self._properties = properties self._properties = properties
security.declarePrivate('_createZODBClone') security.declarePrivate('_createZODBClone')
def _createZODBClone(self): def _createZODBClone(self):
"""Create a ZODB (editable) equivalent of this object.""" """Create a ZODB (editable) equivalent of this object."""
obj = MailTemplate(self.getId(), self._text, self.content_type) obj = MailTemplate(self.getId(), self._text, self.content_type)
obj.expand = 0 obj.expand = 0
obj.write(self.read()) obj.write(self.read())
obj._setPropValue('mailhost',self.mailhost) obj._setPropValue('mailhost',self.mailhost)
obj.content_type = self.content_type obj.content_type = self.content_type
if self._properties: if self._properties:
keys = self._properties.keys() keys = self._properties.keys()
keys.sort() keys.sort()
for id in keys: for id in keys:
if id not in ('mailhost','content_type'): if id not in ('mailhost','content_type'):
obj.manage_addProperty(id,self._properties[id],'string') obj.manage_addProperty(id,self._properties[id],'string')
return obj return obj
security.declarePrivate('_readFile') security.declarePrivate('_readFile')
def _readFile(self, reparse): def _readFile(self, reparse):
fp = self._filepath fp = self._filepath
file = open(fp, 'r') # not 'rb', as this is a text file! file = open(fp, 'r') # not 'rb', as this is a text file!
try: try:
data = file.read() data = file.read()
finally: finally:
file.close() file.close()
if reparse: if reparse:
self.write(data) self.write(data)
def _exec(self, bound_names, args, kw): def _exec(self, bound_names, args, kw):
"""Call a FSPageTemplate""" """Call a FSPageTemplate"""
try: try:
response = self.REQUEST.RESPONSE response = self.REQUEST.RESPONSE
except AttributeError: except AttributeError:
response = None response = None
# Read file first to get a correct content_type default value. # Read file first to get a correct content_type default value.
self._updateFromFS() self._updateFromFS()
if not kw.has_key('args'): if not kw.has_key('args'):
kw['args'] = args kw['args'] = args
bound_names['options'] = kw bound_names['options'] = kw
security=getSecurityManager() security=getSecurityManager()
bound_names['user'] = security.getUser().getIdOrUserName() bound_names['user'] = security.getUser().getIdOrUserName()
# Retrieve the value from the cache. # Retrieve the value from the cache.
keyset = None keyset = None
if self.ZCacheable_isCachingEnabled(): if self.ZCacheable_isCachingEnabled():
# Prepare a cache key. # Prepare a cache key.
keyset = { keyset = {
# Why oh why? # Why oh why?
# All this code is cut and paste # All this code is cut and paste
# here to make sure that we # here to make sure that we
# dont call _getContext and hence can't cache # dont call _getContext and hence can't cache
# Annoying huh? # Annoying huh?
'here': self.aq_parent.getPhysicalPath(), 'here': self.aq_parent.getPhysicalPath(),
'bound_names': bound_names} 'bound_names': bound_names}
result = self.ZCacheable_get(keywords=keyset) result = self.ZCacheable_get(keywords=keyset)
if result is not None: if result is not None:
# Got a cached value. # Got a cached value.
return result return result
# Execute the template in a new security context. # Execute the template in a new security context.
security.addContext(self) security.addContext(self)
try: try:
result = self.pt_render(extra_context=bound_names) result = self.pt_render(extra_context=bound_names)
if keyset is not None: if keyset is not None:
# Store the result in the cache. # Store the result in the cache.
self.ZCacheable_set(result, keywords=keyset) self.ZCacheable_set(result, keywords=keyset)
return result return result
finally: finally:
security.removeContext(self) security.removeContext(self)
return result return result
InitializeClass(FSMailTemplate) InitializeClass(FSMailTemplate)
registerFileExtension('mt', FSMailTemplate) registerFileExtension('mt', FSMailTemplate)
registerMetaType('Mail Template', FSMailTemplate) registerMetaType('Mail Template', FSMailTemplate)
# Copyright (c) 2005-2006 Simplistix Ltd # Copyright (c) 2005-2006 Simplistix Ltd
# #
# This Software is released under the MIT License: # This Software is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.html # http://www.opensource.org/licenses/mit-license.html
# See license.txt for more details. # See license.txt for more details.
import os import os
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from AccessControl import getSecurityManager from AccessControl import getSecurityManager
from App.class_init import default__class_init__ as InitializeClass from App.class_init import default__class_init__ as InitializeClass
from App.Common import package_home from App.Common import package_home
from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
from Products.PageTemplates.PageTemplate import PageTemplate from Products.PageTemplates.PageTemplate import PageTemplate
from Products.PageTemplates.PageTemplateFile import PageTemplateFile from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from BaseMailTemplate import BaseMailTemplate from BaseMailTemplate import BaseMailTemplate
class MailTemplate(BaseMailTemplate,ZopePageTemplate): class MailTemplate(BaseMailTemplate,ZopePageTemplate):
"A ZPT-like template for sending mails" "A ZPT-like template for sending mails"
security = ClassSecurityInfo() security = ClassSecurityInfo()
meta_type = 'Mail Template' meta_type = 'Mail Template'
_properties = () _properties = ()
manage_options = ZopePageTemplate.manage_options[0:1] + \ manage_options = ZopePageTemplate.manage_options[0:1] + \
ZopePageTemplate.manage_options[2:] ZopePageTemplate.manage_options[2:]
_default_content_fn = os.path.join(package_home(globals()), _default_content_fn = os.path.join(package_home(globals()),
'www', 'default.txt') 'www', 'default.txt')
security.declareProtected('View management screens','pt_editForm') security.declareProtected('View management screens','pt_editForm')
pt_editForm = PageTemplateFile('www/mtEdit', globals(), pt_editForm = PageTemplateFile('www/mtEdit', globals(),
__name__='pt_editForm') __name__='pt_editForm')
manage = manage_main = pt_editForm manage = manage_main = pt_editForm
security.declareProtected('Change Page Templates','pt_editAction') security.declareProtected('Change Page Templates','pt_editAction')
def pt_editAction(self, REQUEST, mailhost, text, content_type, expand): def pt_editAction(self, REQUEST, mailhost, text, content_type, expand):
"""Change the mailhost and document.""" """Change the mailhost and document."""
if self.wl_isLocked(): if self.wl_isLocked():
raise ResourceLockedError, "File is locked via WebDAV" raise ResourceLockedError, "File is locked via WebDAV"
self.expand=expand self.expand=expand
self._setPropValue('mailhost',mailhost) self._setPropValue('mailhost',mailhost)
self.pt_edit(text, content_type) self.pt_edit(text, content_type)
REQUEST.set('text', self.read()) # May not equal 'text'! REQUEST.set('text', self.read()) # May not equal 'text'!
message = "Saved changes." message = "Saved changes."
if getattr(self, '_v_warnings', None): if getattr(self, '_v_warnings', None):
message = ("<strong>Warning:</strong> <i>%s</i>" message = ("<strong>Warning:</strong> <i>%s</i>"
% '<br>'.join(self._v_warnings)) % '<br>'.join(self._v_warnings))
return self.pt_editForm(manage_tabs_message=message) return self.pt_editForm(manage_tabs_message=message)
def om_icons(self): def om_icons(self):
"""Return a list of icon URLs to be displayed by an ObjectManager""" """Return a list of icon URLs to be displayed by an ObjectManager"""
icons = ({'path': 'misc_/MailTemplates/mt.gif', icons = ({'path': 'misc_/MailTemplates/mt.gif',
'alt': self.meta_type, 'title': self.meta_type},) 'alt': self.meta_type, 'title': self.meta_type},)
if not self._v_cooked: if not self._v_cooked:
self._cook() self._cook()
if self._v_errors: if self._v_errors:
icons = icons + ({'path': 'misc_/PageTemplates/exclamation.gif', icons = icons + ({'path': 'misc_/PageTemplates/exclamation.gif',
'alt': 'Error', 'alt': 'Error',
'title': 'This template has an error'},) 'title': 'This template has an error'},)
return icons return icons
def _exec(self, bound_names, args, kw): def _exec(self, bound_names, args, kw):
"""Call a Page Template""" """Call a Page Template"""
if not kw.has_key('args'): if not kw.has_key('args'):
kw['args'] = args kw['args'] = args
bound_names['options'] = kw bound_names['options'] = kw
security=getSecurityManager() security=getSecurityManager()
bound_names['user'] = security.getUser().getIdOrUserName() bound_names['user'] = security.getUser().getIdOrUserName()
# Retrieve the value from the cache. # Retrieve the value from the cache.
keyset = None keyset = None
if self.ZCacheable_isCachingEnabled(): if self.ZCacheable_isCachingEnabled():
# Prepare a cache key. # Prepare a cache key.
keyset = {'here': self._getContext(), keyset = {'here': self._getContext(),
'bound_names': bound_names} 'bound_names': bound_names}
result = self.ZCacheable_get(keywords=keyset) result = self.ZCacheable_get(keywords=keyset)
if result is not None: if result is not None:
# Got a cached value. # Got a cached value.
return result return result
# Execute the template in a new security context. # Execute the template in a new security context.
security.addContext(self) security.addContext(self)
try: try:
result = self.pt_render(extra_context=bound_names) result = self.pt_render(extra_context=bound_names)
if keyset is not None: if keyset is not None:
# Store the result in the cache. # Store the result in the cache.
self.ZCacheable_set(result, keywords=keyset) self.ZCacheable_set(result, keywords=keyset)
return result return result
finally: finally:
security.removeContext(self) security.removeContext(self)
def pt_render(self, source=False, extra_context={}): def pt_render(self, source=False, extra_context={}):
# Override to support empty strings # Override to support empty strings
result = PageTemplate.pt_render(self, source, extra_context) or u'' result = PageTemplate.pt_render(self, source, extra_context) or u''
assert isinstance(result, unicode) assert isinstance(result, unicode)
return result return result
InitializeClass(MailTemplate) InitializeClass(MailTemplate)
# Copyright (c) 2005-2006 Simplistix Ltd # Copyright (c) 2005-2006 Simplistix Ltd
# #
# This Software is released under the MIT License: # This Software is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.html # http://www.opensource.org/licenses/mit-license.html
# See license.txt for more details. # See license.txt for more details.
from AccessControl import allow_module,allow_class from AccessControl import allow_module,allow_class
from Products.PageTemplates.PageTemplateFile import PageTemplateFile from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from MailTemplate import MailTemplate from MailTemplate import MailTemplate
from types import ClassType from types import ClassType
from urllib import quote from urllib import quote
try: try:
import Products.CMFCore import Products.CMFCore
except ImportError: except ImportError:
pass pass
else: else:
import FSMailTemplate import FSMailTemplate
import Products.CMFCore.utils import Products.CMFCore.utils
Products.CMFCore.utils.registerIcon(FSMailTemplate.FSMailTemplate, Products.CMFCore.utils.registerIcon(FSMailTemplate.FSMailTemplate,
'www/fsmt.gif', globals()) 'www/fsmt.gif', globals())
def initialize( context ): def initialize( context ):
context.registerClass( context.registerClass(
MailTemplate, MailTemplate,
# we use the same permission as page templates # we use the same permission as page templates
# in order to keep things simple. # in order to keep things simple.
permission='Add Page Templates', permission='Add Page Templates',
constructors=(addMailTemplateForm, constructors=(addMailTemplateForm,
addMailTemplate), addMailTemplate),
icon='www/mt.gif', icon='www/mt.gif',
) )
addMailTemplateForm = PageTemplateFile( addMailTemplateForm = PageTemplateFile(
'www/mtAdd', 'www/mtAdd',
globals(), globals(),
__name__='addMailTemplateForm' __name__='addMailTemplateForm'
) )
def addMailTemplate(self, id, mailhost=None, text=None, def addMailTemplate(self, id, mailhost=None, text=None,
REQUEST=None, submit=None): REQUEST=None, submit=None):
"Add a Mail Template with optional file content." "Add a Mail Template with optional file content."
id = str(id) id = str(id)
if REQUEST is None: if REQUEST is None:
self._setObject(id, MailTemplate(id, text)) self._setObject(id, MailTemplate(id, text))
ob = getattr(self, id) ob = getattr(self, id)
if mailhost: if mailhost:
ob._setPropValue('mailhost',mailhost) ob._setPropValue('mailhost',mailhost)
return ob return ob
else: else:
file = REQUEST.form.get('file') file = REQUEST.form.get('file')
headers = getattr(file, 'headers', None) headers = getattr(file, 'headers', None)
if headers is None or not file.filename: if headers is None or not file.filename:
mt = MailTemplate(id, text) mt = MailTemplate(id, text)
else: else:
mt = MailTemplate(id, file, headers.get('content_type')) mt = MailTemplate(id, file, headers.get('content_type'))
self._setObject(id, mt) self._setObject(id, mt)
ob = getattr(self, id) ob = getattr(self, id)
if mailhost: if mailhost:
ob._setPropValue('mailhost',mailhost) ob._setPropValue('mailhost',mailhost)
if submit == " Add and Edit ": if submit == " Add and Edit ":
u = ob.absolute_url() u = ob.absolute_url()
else: else:
u = ob.aq_parent.absolute_url() u = ob.aq_parent.absolute_url()
REQUEST.RESPONSE.redirect(u+'/manage_main') REQUEST.RESPONSE.redirect(u+'/manage_main')
# allow all the email module's public bits # allow all the email module's public bits
import email import email
for name in email.__all__: for name in email.__all__:
path = 'email.'+name path = 'email.'+name
allow_module(path) allow_module(path)
try: try:
mod = __import__(path) mod = __import__(path)
except ImportError: except ImportError:
pass pass
else: else:
mod = getattr(mod,name) mod = getattr(mod,name)
for mod_name in dir(mod): for mod_name in dir(mod):
obj = getattr(mod,mod_name) obj = getattr(mod,mod_name)
if isinstance(obj,ClassType): if isinstance(obj,ClassType):
allow_class(obj) allow_class(obj)
# Copyright (c) 2005-2006 Simplistix Ltd # Copyright (c) 2005-2006 Simplistix Ltd
# #
# This Software is released under the MIT License: # This Software is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.html # http://www.opensource.org/licenses/mit-license.html
# See license.txt for more details. # See license.txt for more details.
<tal:body xmlns:tal="http://xml.zope.org/namespaces/tal" <tal:body xmlns:tal="http://xml.zope.org/namespaces/tal"
xmlns:metal="http://xml.zope.org/namespaces/metal" xmlns:metal="http://xml.zope.org/namespaces/metal"
>Dear <tal:x replace="options/mto"/>, >Dear <tal:x replace="options/mto"/>,
<tal:x replace="user/getId"/> would like to thank you for <tal:x replace="user/getId"/> would like to thank you for
your interest in: your interest in:
<tal:x replace="root/absolute_url"/> <tal:x replace="root/absolute_url"/>
<tal:x replace="options/message"/> <tal:x replace="options/message"/>
cheers, cheers,
The Web Team The Web Team
</tal:body> </tal:body>
<tal:body xmlns:tal="http://xml.zope.org/namespaces/tal" <tal:body xmlns:tal="http://xml.zope.org/namespaces/tal"
xmlns:metal="http://xml.zope.org/namespaces/metal" xmlns:metal="http://xml.zope.org/namespaces/metal"
>Dear <tal:x replace="options/mto"/>, >Dear <tal:x replace="options/mto"/>,
Please find attached the file you requested. Please find attached the file you requested.
cheers, cheers,
The Web Team The Web Team
</tal:body> </tal:body>
<tal:body xmlns:tal="http://xml.zope.org/namespaces/tal" <tal:body xmlns:tal="http://xml.zope.org/namespaces/tal"
xmlns:metal="http://xml.zope.org/namespaces/metal" xmlns:metal="http://xml.zope.org/namespaces/metal"
>Dear <tal:x replace="options/mto"/>, >Dear <tal:x replace="options/mto"/>,
Welcome to our site! Welcome to our site!
cheers, cheers,
The Web Team The Web Team
</tal:body> </tal:body>
# Copyright (c) 2005-2006 Simplistix Ltd # Copyright (c) 2005-2006 Simplistix Ltd
# #
# This Software is released under the MIT License: # This Software is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.html # http://www.opensource.org/licenses/mit-license.html
# See license.txt for more details. # See license.txt for more details.
import os import os
from AccessControl.SecurityManagement import newSecurityManager from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import noSecurityManager from AccessControl.SecurityManagement import noSecurityManager
from AccessControl.User import system as SystemUser,SimpleUser from AccessControl.User import system as SystemUser,SimpleUser
from OFS.Folder import Folder from OFS.Folder import Folder
from test_MailTemplate import DummyMailHost,Zope,get_transaction from test_MailTemplate import DummyMailHost,Zope,get_transaction
from Testing.makerequest import makerequest from Testing.makerequest import makerequest
from unittest import TestCase,TestSuite,makeSuite,main from unittest import TestCase,TestSuite,makeSuite,main
try: try:
import Products.CMFCore import Products.CMFCore
except ImportError: except ImportError:
# no CMF, no use ;-) # no CMF, no use ;-)
class TestFSMailTemplate(TestCase): class TestFSMailTemplate(TestCase):
pass pass
else: else:
from Products.CMFCore.DirectoryView import addDirectoryViews from Products.CMFCore.DirectoryView import addDirectoryViews
from Products.CMFCore.tests.base.testcase import FSDVTest from Products.CMFCore.tests.base.testcase import FSDVTest
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from App.class_init import default__class_init__ as InitializeClass from App.class_init import default__class_init__ as InitializeClass
class DummyMember: class DummyMember:
security = ClassSecurityInfo() security = ClassSecurityInfo()
security.declareObjectPublic() security.declareObjectPublic()
security.setDefaultAccess('allow') security.setDefaultAccess('allow')
security.declarePublic('getUserName') security.declarePublic('getUserName')
def getUserName(self): def getUserName(self):
return 'Test Member' return 'Test Member'
security.declarePublic('getProperty') security.declarePublic('getProperty')
def getProperty(self,name): def getProperty(self,name):
return 'member@example.com' return 'member@example.com'
InitializeClass(DummyMember) InitializeClass(DummyMember)
class DummyMembershipTool: class DummyMembershipTool:
security = ClassSecurityInfo() security = ClassSecurityInfo()
security.declareObjectPublic() security.declareObjectPublic()
security.setDefaultAccess('allow') security.setDefaultAccess('allow')
security.declarePublic('listMembers') security.declarePublic('listMembers')
def listMembers(self): def listMembers(self):
return (DummyMember(),) return (DummyMember(),)
InitializeClass(DummyMembershipTool) InitializeClass(DummyMembershipTool)
class TestFSMailTemplate(FSDVTest): class TestFSMailTemplate(FSDVTest):
_sourceprefix = os.path.dirname(__file__) _sourceprefix = os.path.dirname(__file__)
def setUp(self): def setUp(self):
FSDVTest.setUp(self) FSDVTest.setUp(self)
self.app = makerequest(Zope.app()) self.app = makerequest(Zope.app())
self._registerDirectory() self._registerDirectory()
ob = self.ob = self.app ob = self.ob = self.app
addDirectoryViews(ob, self._skinname, self.tempname) addDirectoryViews(ob, self._skinname, self.tempname)
self.r = self.app.REQUEST self.r = self.app.REQUEST
self.r.other['URL1'] = 'http://foo/test_mt' self.r.other['URL1'] = 'http://foo/test_mt'
self._add= self.app.manage_addProduct['MailTemplates'].addMailTemplate self._add= self.app.manage_addProduct['MailTemplates'].addMailTemplate
self.folder = Folder('folder') self.folder = Folder('folder')
if getattr(self.app,'test_mt',None): if getattr(self.app,'test_mt',None):
self.app.manage_delObjects(ids=['test_mt']) self.app.manage_delObjects(ids=['test_mt'])
if getattr(self.app,'MailHost',None): if getattr(self.app,'MailHost',None):
self.app.manage_delObjects(ids=['MailHost']) self.app.manage_delObjects(ids=['MailHost'])
self.MailHost = self.app.MailHost = DummyMailHost() self.MailHost = self.app.MailHost = DummyMailHost()
newSecurityManager( None, SystemUser ) newSecurityManager( None, SystemUser )
def tearDown(self): def tearDown(self):
noSecurityManager() noSecurityManager()
get_transaction().abort() get_transaction().abort()
self.app._p_jar.close() self.app._p_jar.close()
try: try:
FSDVTest.tearDown(self) FSDVTest.tearDown(self)
except OSError: except OSError:
# waggh, on windows, files in .svn get locked for some reason :-( # waggh, on windows, files in .svn get locked for some reason :-(
pass pass
def test_render(self): def test_render(self):
self.MailHost.setExpected(mfrom='from@example.com', self.MailHost.setExpected(mfrom='from@example.com',
mto=('to@example.com','to2@example.com'), mto=('to@example.com','to2@example.com'),
filename='mail_FSSendSimple.txt') filename='mail_FSSendSimple.txt')
self.ob.fake_skin.test.send(subject=self.ob.fake_skin.test.subject % 'out', self.ob.fake_skin.test.send(subject=self.ob.fake_skin.test.subject % 'out',
mcc=('cc@example.com',), mcc=('cc@example.com',),
mbcc=('bcc@example.com',), mbcc=('bcc@example.com',),
headers={ headers={
'To':('to@example.com','to2@example.com'), 'To':('to@example.com','to2@example.com'),
'Subject':'cheese', 'Subject':'cheese',
}) })
self.MailHost.checkSent() self.MailHost.checkSent()
# check we're not setting a content type # check we're not setting a content type
self.assertFalse(self.r.RESPONSE.headers.get('content-type'), self.assertFalse(self.r.RESPONSE.headers.get('content-type'),
self.r.RESPONSE.headers) self.r.RESPONSE.headers)
def test_properties(self): def test_properties(self):
self.assertEqual(self.ob.fake_skin.test.mailhost,'MailHost') self.assertEqual(self.ob.fake_skin.test.mailhost,'MailHost')
self.assertEqual(self.ob.fake_skin.test.subject,'Hello %s there') self.assertEqual(self.ob.fake_skin.test.subject,'Hello %s there')
self.assertEqual(self.ob.fake_skin.test.mfrom,'from@example.com') self.assertEqual(self.ob.fake_skin.test.mfrom,'from@example.com')
def test_zodbclone(self): def test_zodbclone(self):
from Products.MailTemplates.MailTemplate import MailTemplate from Products.MailTemplates.MailTemplate import MailTemplate
clone = self.ob.fake_skin.test._createZODBClone() clone = self.ob.fake_skin.test._createZODBClone()
self.assertTrue(isinstance(clone,MailTemplate),'Clone not a MailTemplate!') self.assertTrue(isinstance(clone,MailTemplate),'Clone not a MailTemplate!')
self.assertEqual(self.ob.fake_skin.test.read(),clone.read()) self.assertEqual(self.ob.fake_skin.test.read(),clone.read())
self.assertEqual(clone.getProperty('mailhost'),None) self.assertEqual(clone.getProperty('mailhost'),None)
self.assertEqual(clone.mailhost,'MailHost') self.assertEqual(clone.mailhost,'MailHost')
self.assertEqual(clone.getProperty('subject'),'Hello %s there') self.assertEqual(clone.getProperty('subject'),'Hello %s there')
self.assertEqual(clone.getProperty('mfrom'),'from@example.com') self.assertEqual(clone.getProperty('mfrom'),'from@example.com')
self.assertEqual(clone.content_type,'text/notplain') self.assertEqual(clone.content_type,'text/notplain')
def test_view_manage_workspace(self): def test_view_manage_workspace(self):
from zExceptions import Redirect from zExceptions import Redirect
try: try:
self.assertRaises(self.ob.fake_skin.test.manage_workspace(self.r)) self.assertRaises(self.ob.fake_skin.test.manage_workspace(self.r))
except Redirect,r: except Redirect,r:
# this may appear to be incorrect, but http://foo/test_mt # this may appear to be incorrect, but http://foo/test_mt
# is what we set as REQUEST['URL1'] # is what we set as REQUEST['URL1']
self.assertEqual(r.args,('http://foo/test_mt/manage_main',)) self.assertEqual(r.args,('http://foo/test_mt/manage_main',))
self.ob.fake_skin.test.manage_main() self.ob.fake_skin.test.manage_main()
# ugh, okay, so we can't really test for security, but lets # ugh, okay, so we can't really test for security, but lets
# test for the missing docstring that was causing problems! # test for the missing docstring that was causing problems!
self.assertTrue(self.ob.fake_skin.test.__doc__) self.assertTrue(self.ob.fake_skin.test.__doc__)
def test_example2(self): def test_example2(self):
# login # login
noSecurityManager() noSecurityManager()
self.app.aq_chain[-1].id = 'testing' self.app.aq_chain[-1].id = 'testing'
newSecurityManager( newSecurityManager(
None, None,
SimpleUser('Test User','',('Manager',),[]).__of__(self.app) SimpleUser('Test User','',('Manager',),[]).__of__(self.app)
) )
try: try:
# setup # setup
self.app.portal_membership = DummyMembershipTool() self.app.portal_membership = DummyMembershipTool()
# set expected # set expected
self.MailHost.setExpected(mfrom='webmaster@example.com', self.MailHost.setExpected(mfrom='webmaster@example.com',
mto='member@example.com', mto='member@example.com',
filename='example2.txt') filename='example2.txt')
# test # test
self.ob.fake_skin.send_mails() self.ob.fake_skin.send_mails()
finally: finally:
# logout # logout
noSecurityManager() noSecurityManager()
newSecurityManager( None, SystemUser ) newSecurityManager( None, SystemUser )
def test_suite(): def test_suite():
return TestSuite(( return TestSuite((
makeSuite(TestFSMailTemplate), makeSuite(TestFSMailTemplate),
)) ))
if __name__ == '__main__': if __name__ == '__main__':
main(defaultTest='test_suite') main(defaultTest='test_suite')
# -*- coding: latin-1 -*- # -*- coding: latin-1 -*-
# Copyright (c) 2005-2006 Simplistix Ltd # Copyright (c) 2005-2006 Simplistix Ltd
# #
# This Software is released under the MIT License: # This Software is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.html # http://www.opensource.org/licenses/mit-license.html
# See license.txt for more details. # See license.txt for more details.
import os import os
try: try:
import Zope2 as Zope import Zope2 as Zope
except ImportError: except ImportError:
import Zope import Zope
from AccessControl.SecurityManagement import newSecurityManager from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import noSecurityManager from AccessControl.SecurityManagement import noSecurityManager
from AccessControl.User import system as SystemUser, SimpleUser from AccessControl.User import system as SystemUser, SimpleUser
from cStringIO import StringIO from cStringIO import StringIO
from difflib import unified_diff from difflib import unified_diff
from Products.MailHost.MailHost import MailHost from Products.MailHost.MailHost import MailHost
from Testing.makerequest import makerequest from Testing.makerequest import makerequest
from unittest import TestCase,TestSuite,makeSuite,main from unittest import TestCase,TestSuite,makeSuite,main
try: try:
# Zope 2.8 only # Zope 2.8 only
from transaction import get as get_transaction from transaction import get as get_transaction
except ImportError: except ImportError:
# Zope 2.7 only, allows get_transaction # Zope 2.7 only, allows get_transaction
# to be imported from test_FSMailTemplate. # to be imported from test_FSMailTemplate.
get_transaction = get_transaction get_transaction = get_transaction
test_folder = os.path.dirname(__file__) test_folder = os.path.dirname(__file__)
class DummyFieldStorage: class DummyFieldStorage:
def __init__(self,filename,value): def __init__(self,filename,value):
self.filename = filename self.filename = filename
self.value = value self.value = value
self.file = StringIO(value) self.file = StringIO(value)
self.content_type = None self.content_type = None
self.headers = {} self.headers = {}
class DummyMailHost(MailHost): class DummyMailHost(MailHost):
sent = False sent = False
def setExpected(self,mfrom,mto,filename): def setExpected(self,mfrom,mto,filename):
self.mfrom = mfrom self.mfrom = mfrom
self.mto = mto self.mto = mto
self.messageText = open( self.messageText = open(
os.path.join(test_folder,filename) os.path.join(test_folder,filename)
).read().replace('\r','') ).read().replace('\r','')
self.filename = filename self.filename = filename
def getId(self): def getId(self):
return 'MailHost' return 'MailHost'
def title_and_id(self): def title_and_id(self):
return 'MHTID' return 'MHTID'
def assertEqual(self,x,y,message=None,field=None): def assertEqual(self,x,y,message=None,field=None):
if x!=y: if x!=y:
if message: if message:
raise AssertionError(message) raise AssertionError(message)
error = '%r!=%r' % (x,y) error = '%r!=%r' % (x,y)
if field: if field:
error = field+':'+error error = field+':'+error
raise AssertionError(error) raise AssertionError(error)
def _send(self,mfrom,mto,messageText): def _send(self,mfrom,mto,messageText):
self.assertEqual(self.mfrom,mfrom,field='mfrom') self.assertEqual(self.mfrom,mfrom,field='mfrom')
self.assertEqual(self.mto,mto,field='mto') self.assertEqual(self.mto,mto,field='mto')
expected_data = self.messageText.strip().split('\n') expected_data = self.messageText.strip().split('\n')
actual_data = messageText.strip().split('\n') actual_data = messageText.strip().split('\n')
# ignore dates # ignore dates
for i in range(len(actual_data)): for i in range(len(actual_data)):
if actual_data[i].startswith('Date:'): if actual_data[i].startswith('Date:'):
actual_data[i]='Date:' actual_data[i]='Date:'
diff = tuple(unified_diff( diff = tuple(unified_diff(
expected_data, expected_data,
actual_data, actual_data,
self.filename, self.filename,
'Test results', 'Test results',
)) ))
if diff: if diff:
raise AssertionError( raise AssertionError(
'Mail sent was not as expected:\n\n'+'\n'.join(diff) 'Mail sent was not as expected:\n\n'+'\n'.join(diff)
) )
self.sent = True self.sent = True
def checkSent(self,value=True): def checkSent(self,value=True):
if value: if value:
error = "Mail not sent" error = "Mail not sent"
else: else:
error = "Mail sent when it shouldn't have been" error = "Mail sent when it shouldn't have been"
self.assertEqual(self.sent,value,error) self.assertEqual(self.sent,value,error)
class DummyMailDropHost(DummyMailHost): class DummyMailDropHost(DummyMailHost):
meta_type = 'Maildrop Host' meta_type = 'Maildrop Host'
class TestMailTemplate(TestCase): class TestMailTemplate(TestCase):
def setUp(self): def setUp(self):
self.app = makerequest(Zope.app()) self.app = makerequest(Zope.app())
self.r = self.app.REQUEST self.r = self.app.REQUEST
self.r.other['URL1'] = 'http://foo/test_mt' self.r.other['URL1'] = 'http://foo/test_mt'
self._add= self.app.manage_addProduct['MailTemplates'].addMailTemplate self._add= self.app.manage_addProduct['MailTemplates'].addMailTemplate
if getattr(self.app,'test_mt',None): if getattr(self.app,'test_mt',None):
self.app.manage_delObjects(ids=['test_mt']) self.app.manage_delObjects(ids=['test_mt'])
if getattr(self.app,'MailHost',None): if getattr(self.app,'MailHost',None):
self.app.manage_delObjects(ids=['MailHost']) self.app.manage_delObjects(ids=['MailHost'])
self.MailHost = self.app.MailHost = DummyMailHost() self.MailHost = self.app.MailHost = DummyMailHost()
o = list(self.app._objects) o = list(self.app._objects)
o.append({'meta_type': 'Mail Host', 'id': 'MailHost'}) o.append({'meta_type': 'Mail Host', 'id': 'MailHost'})
self.app._objects = tuple(o) self.app._objects = tuple(o)
newSecurityManager( None, SystemUser ) newSecurityManager( None, SystemUser )
def tearDown(self): def tearDown(self):
noSecurityManager() noSecurityManager()
get_transaction().abort() get_transaction().abort()
self.app._p_jar.close() self.app._p_jar.close()
def makeFileUpload(self,filename='test.txt',value='test text', def makeFileUpload(self,filename='test.txt',value='test text',
diskname=''): diskname=''):
if diskname: if diskname:
filename = diskname filename = diskname
value = open( value = open(
os.path.join(test_folder,diskname) os.path.join(test_folder,diskname)
).read().replace('\r','').strip() ).read().replace('\r','').strip()
from ZPublisher.HTTPRequest import FileUpload from ZPublisher.HTTPRequest import FileUpload
return FileUpload(DummyFieldStorage( return FileUpload(DummyFieldStorage(
filename, filename,
value value
)) ))
def checkContent(self,text='test text'): def checkContent(self,text='test text'):
if text is None: if text is None:
text = open(os.path.join(test_folder,'..','www','default.txt')).read() text = open(os.path.join(test_folder,'..','www','default.txt')).read()
self.assertEqual( self.assertEqual(
self.app.test_mt.document_src({'raw':1}), self.app.test_mt.document_src({'raw':1}),
text text
) )
# Test Adding # Test Adding
def test_addAddForm(self): def test_addAddForm(self):
self.app.manage_addProduct['MailTemplates'].addMailTemplateForm() self.app.manage_addProduct['MailTemplates'].addMailTemplateForm()
def test_addAddFormNoMailHosts(self): def test_addAddFormNoMailHosts(self):
self.app.manage_delObjects(ids=['MailHost']) self.app.manage_delObjects(ids=['MailHost'])
res = self.app.manage_addProduct['MailTemplates'].addMailTemplateForm() res = self.app.manage_addProduct['MailTemplates'].addMailTemplateForm()
self.assertTrue( self.assertTrue(
res.find( res.find(
'<option value="MailHost">MHTID</option>' '<option value="MailHost">MHTID</option>'
)==-1 )==-1
) )
def test_addAddFormMailHost(self): def test_addAddFormMailHost(self):
self.app._objects = ({'meta_type': 'Mail Host', 'id': 'MailHost'},) self.app._objects = ({'meta_type': 'Mail Host', 'id': 'MailHost'},)
res = self.app.manage_addProduct['MailTemplates'].addMailTemplateForm() res = self.app.manage_addProduct['MailTemplates'].addMailTemplateForm()
self.assertFalse( self.assertFalse(
res.find( res.find(
'<option value="MailHost">MHTID</option>' '<option value="MailHost">MHTID</option>'
)==-1 )==-1
) )
def test_addAddFormMailDropHost(self): def test_addAddFormMailDropHost(self):
if getattr(self.app,'MailHost',None): if getattr(self.app,'MailHost',None):
self.app.manage_delObjects(ids=['MailHost']) self.app.manage_delObjects(ids=['MailHost'])
self.MailHost = self.app.MailHost = DummyMailDropHost() self.MailHost = self.app.MailHost = DummyMailDropHost()
self.app._objects = ({'meta_type': 'Maildrop Host', 'id': 'MailHost'},) self.app._objects = ({'meta_type': 'Maildrop Host', 'id': 'MailHost'},)
res = self.app.manage_addProduct['MailTemplates'].addMailTemplateForm() res = self.app.manage_addProduct['MailTemplates'].addMailTemplateForm()
self.assertFalse( self.assertFalse(
res.find( res.find(
'<option value="MailHost">MHTID</option>' '<option value="MailHost">MHTID</option>'
)==-1 )==-1
) )
def test_addNoREQUEST(self): def test_addNoREQUEST(self):
self._add('test_mt','MailHost') self._add('test_mt','MailHost')
# check settings # check settings
self.assertEqual(self.app.test_mt.expand,0) self.assertEqual(self.app.test_mt.expand,0)
self.assertEqual(self.app.test_mt.mailhost,'MailHost') self.assertEqual(self.app.test_mt.mailhost,'MailHost')
self.assertEqual(self.app.test_mt.content_type,'text/plain') self.assertEqual(self.app.test_mt.content_type,'text/plain')
# check default content # check default content
self.checkContent(None) self.checkContent(None)
def test_addNoMailHostSelected(self): def test_addNoMailHostSelected(self):
self._add('test_mt',REQUEST=self.r) self._add('test_mt',REQUEST=self.r)
# check settings # check settings
self.assertEqual(self.app.test_mt.expand,0) self.assertEqual(self.app.test_mt.expand,0)
self.assertEqual(self.app.test_mt.mailhost,None) self.assertEqual(self.app.test_mt.mailhost,None)
self.assertEqual(self.app.test_mt.content_type,'text/plain') self.assertEqual(self.app.test_mt.content_type,'text/plain')
# check default content # check default content
self.checkContent(None) self.checkContent(None)
# check the error we get when we try to send # check the error we get when we try to send
self.assertRaises( self.assertRaises(
RuntimeError,self.app.test_mt, RuntimeError,self.app.test_mt,
mfrom='from@example.com', mfrom='from@example.com',
mto='to@example.com', mto='to@example.com',
subject='Test Subject', subject='Test Subject',
) )
# no put a mogus mailhost in and check we get the same error # no put a mogus mailhost in and check we get the same error
self.app.test_mt.mailhost='bogus' self.app.test_mt.mailhost='bogus'
self.assertRaises( self.assertRaises(
RuntimeError,self.app.test_mt, RuntimeError,self.app.test_mt,
mfrom='from@example.com', mfrom='from@example.com',
mto='to@example.com', mto='to@example.com',
subject='Test Subject', subject='Test Subject',
) )
def test_add(self,body = None): def test_add(self,body = None):
text = open(os.path.join(test_folder,'..','www','default.txt')).read() text = open(os.path.join(test_folder,'..','www','default.txt')).read()
if body is not None: if body is not None:
text = text[:-12] + body + text[-11:] text = text[:-12] + body + text[-11:]
self._add('test_mt','MailHost',text=text,REQUEST=self.r) self._add('test_mt','MailHost',text=text,REQUEST=self.r)
else: else:
self._add('test_mt','MailHost',REQUEST=self.r) self._add('test_mt','MailHost',REQUEST=self.r)
self.assertEqual( self.assertEqual(
self.r.RESPONSE.headers, self.r.RESPONSE.headers,
{'status': '302 Moved Temporarily', 'location': 'http://foo/manage_main'} {'status': '302 Moved Temporarily', 'location': 'http://foo/manage_main'}
) )
self.mt = self.app.test_mt self.mt = self.app.test_mt
# check settings # check settings
self.assertEqual(self.mt.expand,0) self.assertEqual(self.mt.expand,0)
self.assertEqual(self.mt.mailhost,'MailHost') self.assertEqual(self.mt.mailhost,'MailHost')
self.assertEqual(self.mt.content_type,'text/plain') self.assertEqual(self.mt.content_type,'text/plain')
# check default content # check default content
self.assertEqual( self.assertEqual(
self.app.test_mt.read(), self.app.test_mt.read(),
text text
) )
# check default content type is text/plain # check default content type is text/plain
self.assertEqual(self.app.test_mt.content_type,'text/plain') self.assertEqual(self.app.test_mt.content_type,'text/plain')
def test_addFile(self): def test_addFile(self):
self.r.form['file'] = self.makeFileUpload() self.r.form['file'] = self.makeFileUpload()
self._add('test_mt','MailHost',REQUEST=self.r) self._add('test_mt','MailHost',REQUEST=self.r)
# check settings # check settings
self.assertEqual(self.app.test_mt.expand,0) self.assertEqual(self.app.test_mt.expand,0)
self.assertEqual(self.app.test_mt.mailhost,'MailHost') self.assertEqual(self.app.test_mt.mailhost,'MailHost')
self.assertEqual(self.app.test_mt.content_type,'text/plain') self.assertEqual(self.app.test_mt.content_type,'text/plain')
# check default content # check default content
self.checkContent() self.checkContent()
def test_addEdit(self): def test_addEdit(self):
self._add('test_mt','MailHost',REQUEST=self.r,submit=' Add and Edit ') self._add('test_mt','MailHost',REQUEST=self.r,submit=' Add and Edit ')
self.assertEqual( self.assertEqual(
self.r.RESPONSE.headers, self.r.RESPONSE.headers,
{'status': '302 Moved Temporarily', 'location': 'http://foo/test_mt/manage_main'} {'status': '302 Moved Temporarily', 'location': 'http://foo/test_mt/manage_main'}
) )
# check settings # check settings
self.assertEqual(self.app.test_mt.expand,0) self.assertEqual(self.app.test_mt.expand,0)
self.assertEqual(self.app.test_mt.mailhost,'MailHost') self.assertEqual(self.app.test_mt.mailhost,'MailHost')
self.assertEqual(self.app.test_mt.content_type,'text/plain') self.assertEqual(self.app.test_mt.content_type,'text/plain')
# check default content # check default content
self.checkContent(None) self.checkContent(None)
def test_addEditFile(self): def test_addEditFile(self):
self.r.form['file'] = self.makeFileUpload() self.r.form['file'] = self.makeFileUpload()
self._add('test_mt','MailHost',REQUEST=self.r,submit=' Add and Edit ') self._add('test_mt','MailHost',REQUEST=self.r,submit=' Add and Edit ')
self.assertEqual( self.assertEqual(
self.r.RESPONSE.headers, self.r.RESPONSE.headers,
{'status': '302 Moved Temporarily', 'location': 'http://foo/test_mt/manage_main'} {'status': '302 Moved Temporarily', 'location': 'http://foo/test_mt/manage_main'}
) )
# check settings # check settings
self.assertEqual(self.app.test_mt.expand,0) self.assertEqual(self.app.test_mt.expand,0)
self.assertEqual(self.app.test_mt.mailhost,'MailHost') self.assertEqual(self.app.test_mt.mailhost,'MailHost')
self.assertEqual(self.app.test_mt.content_type,'text/plain') self.assertEqual(self.app.test_mt.content_type,'text/plain')
# check default content # check default content
self.checkContent() self.checkContent()
# Test Properties Tab # Test Properties Tab
# Not much here, as we assume PropertyManager does its job ;-) # Not much here, as we assume PropertyManager does its job ;-)
def test_PropertiesForm(self): def test_PropertiesForm(self):
self.test_add() self.test_add()
self.mt.manage_propertiesForm() self.mt.manage_propertiesForm()
def test_PropertiesStartsEmpty(self): def test_PropertiesStartsEmpty(self):
self.test_add() self.test_add()
self.assertFalse(self.mt.propertyMap()) self.assertFalse(self.mt.propertyMap())
# Test Test tab, well, actually, make sure it's not there ;-) # Test Test tab, well, actually, make sure it's not there ;-)
def test_NoTestTab(self): def test_NoTestTab(self):
from Products.MailTemplates.MailTemplate import MailTemplate from Products.MailTemplates.MailTemplate import MailTemplate
for option in MailTemplate.manage_options: for option in MailTemplate.manage_options:
if option['label']=='Test': if option['label']=='Test':
self.fail('Test label found') self.fail('Test label found')
self.assertFalse(MailTemplate.ZScriptHTML_tryForm, 'try form not None') self.assertFalse(MailTemplate.ZScriptHTML_tryForm, 'try form not None')
# Test Editing # Test Editing
def test_editForm(self): def test_editForm(self):
self.test_add() self.test_add()
self.mt.pt_editForm() self.mt.pt_editForm()
def test_editFormMailHostGone(self): def test_editFormMailHostGone(self):
self.test_add() self.test_add()
self.app.manage_delObjects('MailHost') self.app.manage_delObjects('MailHost')
r = self.mt.pt_editForm() r = self.mt.pt_editForm()
self.assertFalse( self.assertFalse(
r.find( r.find(
"""<option selected="selected" value="MailHost">'MailHost' is no longer valid!</option>""" """<option selected="selected" value="MailHost">'MailHost' is no longer valid!</option>"""
)==-1,'No warning for MailHost being invalid found in:\n'+r )==-1,'No warning for MailHost being invalid found in:\n'+r
) )
def test_editAction(self): def test_editAction(self):
self.test_add() self.test_add()
self.mt.pt_editAction(REQUEST=self.r, self.mt.pt_editAction(REQUEST=self.r,
mailhost='MH2', mailhost='MH2',
text='new text', text='new text',
content_type='text/fish', content_type='text/fish',
expand=1) expand=1)
self.assertEqual(self.mt.expand,1) self.assertEqual(self.mt.expand,1)
self.assertEqual(self.mt.mailhost,'MH2') self.assertEqual(self.mt.mailhost,'MH2')
self.assertEqual(self.mt.content_type,'text/fish') self.assertEqual(self.mt.content_type,'text/fish')
self.checkContent('new text') self.checkContent('new text')
def test_view_manage_workspace(self): def test_view_manage_workspace(self):
self.test_add() self.test_add()
from zExceptions import Redirect from zExceptions import Redirect
try: try:
self.assertRaises(self.mt.manage_workspace(self.r)) self.assertRaises(self.mt.manage_workspace(self.r))
except Redirect,r: except Redirect,r:
# this may appear to be incorrect, but http://foo/test_mt # this may appear to be incorrect, but http://foo/test_mt
# is what we set as REQUEST['URL1'] # is what we set as REQUEST['URL1']
self.assertEqual(r.args,('http://foo/test_mt/pt_editForm',)) self.assertEqual(r.args,('http://foo/test_mt/pt_editForm',))
# ugh, okay, so we can't really test for security, but lets # ugh, okay, so we can't really test for security, but lets
# test for the missing docstring that was causing problems! # test for the missing docstring that was causing problems!
self.assertTrue(self.mt.__doc__) self.assertTrue(self.mt.__doc__)
def test_view_manage_main(self): def test_view_manage_main(self):
self.test_add() self.test_add()
# for some bizare reason the output differs by a newline the first time these are called :-( # for some bizare reason the output differs by a newline the first time these are called :-(
self.mt.manage_main() self.mt.manage_main()
self.mt.pt_editForm() self.mt.pt_editForm()
self.assertEqual(self.mt.manage_main(),self.mt.pt_editForm()) self.assertEqual(self.mt.manage_main(),self.mt.pt_editForm())
# Test Sending # Test Sending
def testSendSimple(self): def testSendSimple(self):
self.test_add('Test Body') self.test_add('Test Body')
self.MailHost.setExpected(mfrom='from@example.com', self.MailHost.setExpected(mfrom='from@example.com',
mto=('to@example.com', 'to2@example.com', mto=('to@example.com', 'to2@example.com',
'cc@example.com', 'bcc@example.com'), 'cc@example.com', 'bcc@example.com'),
filename='mail_SendSimple.txt') filename='mail_SendSimple.txt')
self.mt.send( self.mt.send(
mfrom='from@example.com', mfrom='from@example.com',
mto=('to@example.com','to2@example.com'), mto=('to@example.com','to2@example.com'),
mcc=('cc@example.com',), mcc=('cc@example.com',),
mbcc=('bcc@example.com',), mbcc=('bcc@example.com',),
subject='Hello out there', subject='Hello out there',
) )
self.MailHost.checkSent() self.MailHost.checkSent()
# check we're not setting a content type # check we're not setting a content type
self.assertFalse(self.r.RESPONSE.headers.get('content-type'), self.assertFalse(self.r.RESPONSE.headers.get('content-type'),
self.r.RESPONSE.headers) self.r.RESPONSE.headers)
def testMailHostNotAMailHost(self): def testMailHostNotAMailHost(self):
self.test_add('Test Body') self.test_add('Test Body')
self.app.MailHost='Hahaha, not a MailHost' self.app.MailHost='Hahaha, not a MailHost'
self.assertRaises( self.assertRaises(
RuntimeError, RuntimeError,
self.mt.send, self.mt.send,
mfrom='from@example.com', mfrom='from@example.com',
mto=('to@example.com','to2@example.com'), mto=('to@example.com','to2@example.com'),
mcc=('cc@example.com',), mcc=('cc@example.com',),
mbcc=('bcc@example.com',), mbcc=('bcc@example.com',),
subject='Hello out there', subject='Hello out there',
) )
def _shouldFail(self,error,**params): def _shouldFail(self,error,**params):
self.test_add('Test Body') self.test_add('Test Body')
try: try:
self.mt.send(**params) self.mt.send(**params)
except TypeError,e: except TypeError,e:
self.assertEqual(e.args[0],error) self.assertEqual(e.args[0],error)
else: else:
self.fail('Mail sent even though params missing') self.fail('Mail sent even though params missing')
self.MailHost.checkSent(False) self.MailHost.checkSent(False)
def testSendMissingParams1(self): def testSendMissingParams1(self):
self._shouldFail( self._shouldFail(
'The following parameters were required by not specified: subject', 'The following parameters were required by not specified: subject',
mto='to@example.com', mto='to@example.com',
mfrom='from@example.com' mfrom='from@example.com'
) )
def testSendMissingParams2(self): def testSendMissingParams2(self):
self._shouldFail( self._shouldFail(
'The following parameters were required by not specified: mfrom', 'The following parameters were required by not specified: mfrom',
mto='to@example.com', mto='to@example.com',
subject='Test Subject' subject='Test Subject'
) )
def testSendMissingParams3(self): def testSendMissingParams3(self):
self._shouldFail( self._shouldFail(
'The following parameters were required by not specified: mto', 'The following parameters were required by not specified: mto',
mfrom='from@example.com', mfrom='from@example.com',
subject='Test Subject' subject='Test Subject'
) )
def testSendMissingParamsAll(self): def testSendMissingParamsAll(self):
self._shouldFail( self._shouldFail(
'The following parameters were required by not specified: mfrom, mto, subject', 'The following parameters were required by not specified: mfrom, mto, subject',
) )
def testSendProperties(self): def testSendProperties(self):
self.test_add('Test Body') self.test_add('Test Body')
self.MailHost.setExpected(mfrom='from@example.com', self.MailHost.setExpected(mfrom='from@example.com',
mto=('to@example.com', 'to2@example.com', mto=('to@example.com', 'to2@example.com',
'cc@example.com', 'bcc@example.com'), 'cc@example.com', 'bcc@example.com'),
filename='mail_SendSimple.txt') filename='mail_SendSimple.txt')
for name,type,value in ( for name,type,value in (
('mfrom','string','from@example.com'), ('mfrom','string','from@example.com'),
('mto','string','to@example.com, to2@example.com'), ('mto','string','to@example.com, to2@example.com'),
('mbcc','lines',('bcc@example.com',)), ('mbcc','lines',('bcc@example.com',)),
('subject','string','Hello out there'), ('subject','string','Hello out there'),
('headers','lines', ('headers','lines',
('Cc:cc@example.com',)), ('Cc:cc@example.com',)),
): ):
self.mt.manage_addProperty(name,value,type) self.mt.manage_addProperty(name,value,type)
self.mt.send() self.mt.send()
self.MailHost.checkSent() self.MailHost.checkSent()
def testSendHeadersDict(self): def testSendHeadersDict(self):
self.test_add('Test Body') self.test_add('Test Body')
self.MailHost.setExpected(mfrom='from@example.com', self.MailHost.setExpected(mfrom='from@example.com',
mto=('to@example.com','to2@example.com', mto=('to@example.com','to2@example.com',
'cc@example.com', 'bcc@example.com'), 'cc@example.com', 'bcc@example.com'),
filename='mail_SendHeaders.txt') filename='mail_SendHeaders.txt')
self.mt.send( self.mt.send(
headers = { headers = {
'From':'from@example.com', 'From':'from@example.com',
'To':('to@example.com','to2@example.com'), 'To':('to@example.com','to2@example.com'),
'Cc':('cc@example.com',), 'Cc':('cc@example.com',),
'Bcc':('bcc@example.com',), 'Bcc':('bcc@example.com',),
'Subject':'Hello out there', 'Subject':'Hello out there',
'X-Mailer':'MailTemplates', 'X-Mailer':'MailTemplates',
} }
) )
self.MailHost.checkSent() self.MailHost.checkSent()
def testSendParametersOverrideHeadersDictOverridesProperties(self): def testSendParametersOverrideHeadersDictOverridesProperties(self):
self.test_add('Test Body') self.test_add('Test Body')
self.MailHost.setExpected(mfrom='from@example.com', self.MailHost.setExpected(mfrom='from@example.com',
mto=('to@example.com','to2@example.com', mto=('to@example.com','to2@example.com',
'cc@example.com', 'bcc@example.com'), 'cc@example.com', 'bcc@example.com'),
filename='mail_SendHeaders2.txt') filename='mail_SendHeaders2.txt')
for name,type,value in ( for name,type,value in (
('mfrom','string','from@example.com'), ('mfrom','string','from@example.com'),
('mto','string','frog@example.com'), ('mto','string','frog@example.com'),
('mcc','lines',('cc@example.com',)), ('mcc','lines',('cc@example.com',)),
('mbcc','lines',('bcc@example.com',)), ('mbcc','lines',('bcc@example.com',)),
('subject','string','Hello %s there'), ('subject','string','Hello %s there'),
('headers','lines',( ('headers','lines',(
'X-Mailer: MailTemplates', 'X-Mailer: MailTemplates',
'X-Mailer2: MailTemplatesBad', 'X-Mailer2: MailTemplatesBad',
)) ))
): ):
self.mt.manage_addProperty(name,value,type) self.mt.manage_addProperty(name,value,type)
self.mt.send(subject=self.mt.subject % 'out', self.mt.send(subject=self.mt.subject % 'out',
headers={ headers={
'To':('to@example.com','to2@example.com'), 'To':('to@example.com','to2@example.com'),
'Subject':'cheese', 'Subject':'cheese',
'X-Mailer2':'MailTemplates', 'X-Mailer2':'MailTemplates',
}) })
self.MailHost.checkSent() self.MailHost.checkSent()
def testSendParametersGoToOptions(self): def testSendParametersGoToOptions(self):
self.test_add('Test <tal:x replace="options/body"/>') self.test_add('Test <tal:x replace="options/body"/>')
self.MailHost.setExpected(mfrom='from@example.com', self.MailHost.setExpected(mfrom='from@example.com',
mto=('to@example.com','to2@example.com', mto=('to@example.com','to2@example.com',
'cc@example.com', 'bcc@example.com'), 'cc@example.com', 'bcc@example.com'),
filename='mail_SendSimple.txt') filename='mail_SendSimple.txt')
for name,type,value in ( for name,type,value in (
('mfrom','string','from@example.com'), ('mfrom','string','from@example.com'),
('mto','string','frog@example.com'), ('mto','string','frog@example.com'),
('mcc','lines',('cc@example.com',)), ('mcc','lines',('cc@example.com',)),
('mbcc','lines',('bcc@example.com',)), ('mbcc','lines',('bcc@example.com',)),
('subject','string','Hello %s there'), ('subject','string','Hello %s there'),
): ):
self.mt.manage_addProperty(name,value,type) self.mt.manage_addProperty(name,value,type)
self.mt.send(subject=self.mt.subject % 'out', self.mt.send(subject=self.mt.subject % 'out',
headers={ headers={
'To':('to@example.com','to2@example.com'), 'To':('to@example.com','to2@example.com'),
'Subject':'cheese', 'Subject':'cheese',
}, },
body='Body') body='Body')
self.MailHost.checkSent() self.MailHost.checkSent()
def testPropertiesParametersAndSubstitution(self): def testPropertiesParametersAndSubstitution(self):
self.test_add('Test Body') self.test_add('Test Body')
self.MailHost.setExpected(mfrom='from@example.com', self.MailHost.setExpected(mfrom='from@example.com',
mto=('to@example.com', 'to2@example.com', mto=('to@example.com', 'to2@example.com',
'cc@example.com', 'bcc@example.com'), 'cc@example.com', 'bcc@example.com'),
filename='mail_SendSimple.txt') filename='mail_SendSimple.txt')
for name,type,value in ( for name,type,value in (
('mfrom','string','from@example.com'), ('mfrom','string','from@example.com'),
('mto','string','to@example.com, to2@example.com'), ('mto','string','to@example.com, to2@example.com'),
('mcc','lines',('cc@example.com',)), ('mcc','lines',('cc@example.com',)),
('mbcc','lines',('bcc@example.com',)), ('mbcc','lines',('bcc@example.com',)),
('subject','string','Hello %s there'), ('subject','string','Hello %s there'),
): ):
self.mt.manage_addProperty(name,value,type) self.mt.manage_addProperty(name,value,type)
self.mt.send(subject=self.mt.subject % 'out') self.mt.send(subject=self.mt.subject % 'out')
self.MailHost.checkSent() self.MailHost.checkSent()
def testGetMessage(self): def testGetMessage(self):
from email.MIMEMultipart import MIMEMultipart from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText from email.MIMEText import MIMEText
self.test_add('Test <tal:x replace="options/body"/>') self.test_add('Test <tal:x replace="options/body"/>')
self.MailHost.setExpected(mfrom='from@example.com', self.MailHost.setExpected(mfrom='from@example.com',
mto=('to@example.com','to2@example.com'), mto=('to@example.com','to2@example.com'),
filename='mail_SendAttachment.txt') filename='mail_SendAttachment.txt')
for name,type,value in ( for name,type,value in (
('mfrom','string','from@example.com'), ('mfrom','string','from@example.com'),
('mto','string','frog@example.com'), ('mto','string','frog@example.com'),
('mcc','lines',('cc@example.com',)), ('mcc','lines',('cc@example.com',)),
('mbcc','lines',('bcc@example.com',)), ('mbcc','lines',('bcc@example.com',)),
('subject','string','Hello %s there'), ('subject','string','Hello %s there'),
): ):
self.mt.manage_addProperty(name,value,type) self.mt.manage_addProperty(name,value,type)
msg = self.mt.as_message(subject=self.mt.subject % 'out', msg = self.mt.as_message(subject=self.mt.subject % 'out',
headers={ headers={
'To':('to@example.com','to2@example.com'), 'To':('to@example.com','to2@example.com'),
'Subject':'cheese', 'Subject':'cheese',
}, },
body='Body', body='Body',
boundary='111', boundary='111',
subtype='alternative') subtype='alternative')
self.assertTrue(isinstance(msg,MIMEMultipart)) self.assertTrue(isinstance(msg,MIMEMultipart))
attachment = MIMEText('A Test Attachment',_subtype='plain') attachment = MIMEText('A Test Attachment',_subtype='plain')
attachment.add_header('Content-Disposition', 'attachment', filename='test.txt') attachment.add_header('Content-Disposition', 'attachment', filename='test.txt')
msg.attach(attachment) msg.attach(attachment)
msg.send() msg.send()
self.MailHost.checkSent() self.MailHost.checkSent()
def _addFileSetup(self): def _addFileSetup(self):
from email.MIMEMultipart import MIMEMultipart from email.MIMEMultipart import MIMEMultipart
self.test_add('Test <tal:x replace="options/body"/>') self.test_add('Test <tal:x replace="options/body"/>')
self.MailHost.setExpected(mfrom='from@example.com', self.MailHost.setExpected(mfrom='from@example.com',
mto=('to@example.com','to2@example.com'), mto=('to@example.com','to2@example.com'),
filename='mail_SendFile.txt') filename='mail_SendFile.txt')
for name,type,value in ( for name,type,value in (
('mfrom','string','from@example.com'), ('mfrom','string','from@example.com'),
('mto','string','frog@example.com'), ('mto','string','frog@example.com'),
('mcc','lines',('cc@example.com',)), ('mcc','lines',('cc@example.com',)),
('mbcc','lines',('bcc@example.com',)), ('mbcc','lines',('bcc@example.com',)),
('subject','string','Hello %s there'), ('subject','string','Hello %s there'),
): ):
self.mt.manage_addProperty(name,value,type) self.mt.manage_addProperty(name,value,type)
msg = self.mt.as_message(subject=self.mt.subject % 'out', msg = self.mt.as_message(subject=self.mt.subject % 'out',
headers={ headers={
'To':('to@example.com','to2@example.com'), 'To':('to@example.com','to2@example.com'),
'Subject':'cheese', 'Subject':'cheese',
}, },
body='Body', body='Body',
boundary='111', boundary='111',
subtype='alternative') subtype='alternative')
self.assertTrue(isinstance(msg,MIMEMultipart)) self.assertTrue(isinstance(msg,MIMEMultipart))
return msg return msg
def testZopeFileObject(self): def testZopeFileObject(self):
self.app.manage_addFile('test.txt', self.app.manage_addFile('test.txt',
'A Test Attachment') 'A Test Attachment')
msg = self._addFileSetup() msg = self._addFileSetup()
msg.add_file(self.app['test.txt']) msg.add_file(self.app['test.txt'])
msg.send() msg.send()
self.MailHost.checkSent() self.MailHost.checkSent()
def testPythonFileObject(self): def testPythonFileObject(self):
msg = self._addFileSetup() msg = self._addFileSetup()
msg.add_file(open( msg.add_file(open(
os.path.join(test_folder,'test.txt') os.path.join(test_folder,'test.txt')
)) ))
msg.send() msg.send()
self.MailHost.checkSent() self.MailHost.checkSent()
def testFileUploadObject(self): def testFileUploadObject(self):
msg = self._addFileSetup() msg = self._addFileSetup()
msg.add_file(self.makeFileUpload( msg.add_file(self.makeFileUpload(
value='A Test Attachment' value='A Test Attachment'
)) ))
msg.send() msg.send()
self.MailHost.checkSent() self.MailHost.checkSent()
def testStringWithContentType(self): def testStringWithContentType(self):
msg = self._addFileSetup() msg = self._addFileSetup()
msg.add_file( msg.add_file(
data=open( data=open(
os.path.join(test_folder,'test.txt') os.path.join(test_folder,'test.txt')
).read(), ).read(),
filename='test.txt', filename='test.txt',
content_type='text/plain' content_type='text/plain'
) )
msg.send() msg.send()
self.MailHost.checkSent() self.MailHost.checkSent()
def testStringWithoutContentType(self): def testStringWithoutContentType(self):
msg = self._addFileSetup() msg = self._addFileSetup()
msg.add_file( msg.add_file(
data=open( data=open(
os.path.join(test_folder,'test.txt') os.path.join(test_folder,'test.txt')
).read(), ).read(),
filename='test.txt' filename='test.txt'
) )
msg.send() msg.send()
self.MailHost.checkSent() self.MailHost.checkSent()
def testTooManyParameters(self): def testTooManyParameters(self):
msg = self._addFileSetup() msg = self._addFileSetup()
self.assertRaises( self.assertRaises(
TypeError, TypeError,
msg.add_file, msg.add_file,
self.makeFileUpload( self.makeFileUpload(
value='A Test Attachment' value='A Test Attachment'
), ),
data=open( data=open(
os.path.join(test_folder,'test.txt') os.path.join(test_folder,'test.txt')
).read(), ).read(),
filename='test.txt', filename='test.txt',
content_type='text/plain' content_type='text/plain'
) )
def testTooFewParameters(self): def testTooFewParameters(self):
msg = self._addFileSetup() msg = self._addFileSetup()
self.assertRaises( self.assertRaises(
TypeError, TypeError,
msg.add_file msg.add_file
) )
def testDataWithoutFilename(self): def testDataWithoutFilename(self):
msg = self._addFileSetup() msg = self._addFileSetup()
self.assertRaises( self.assertRaises(
TypeError, TypeError,
msg.add_file, msg.add_file,
data=open( data=open(
os.path.join(test_folder,'test.txt') os.path.join(test_folder,'test.txt')
).read(), ).read(),
content_type='text/plain' content_type='text/plain'
) )
def testFilenameWithoutData(self): def testFilenameWithoutData(self):
msg = self._addFileSetup() msg = self._addFileSetup()
self.assertRaises( self.assertRaises(
TypeError, TypeError,
msg.add_file, msg.add_file,
filename='test.txt', filename='test.txt',
content_type='text/plain' content_type='text/plain'
) )
def testCallAliasesSend(self): def testCallAliasesSend(self):
self.test_add('Test Body') self.test_add('Test Body')
self.MailHost.setExpected(mfrom='from@example.com', self.MailHost.setExpected(mfrom='from@example.com',
mto=('to@example.com',), mto=('to@example.com',),
filename='mail_SendSimpleSomeHeaders.txt') filename='mail_SendSimpleSomeHeaders.txt')
self.mt( self.mt(
mfrom='from@example.com', mfrom='from@example.com',
mto=('to@example.com',), mto=('to@example.com',),
subject='Test Subject' subject='Test Subject'
) )
self.MailHost.checkSent() self.MailHost.checkSent()
def test_encoded_not_html_mode(self): def test_encoded_not_html_mode(self):
self.MailHost.setExpected(mfrom='from@example.com', self.MailHost.setExpected(mfrom='from@example.com',
mto=('to@example.com',), mto=('to@example.com',),
filename='mail_unicode.txt') filename='mail_unicode.txt')
self.test_add('Test <tal:x replace="options/unicode"/>') self.test_add('Test <tal:x replace="options/unicode"/>')
# we get a unicode error here because we're trying to # we get a unicode error here because we're trying to
# use an encoded string in a non-html-mode page template. # use an encoded string in a non-html-mode page template.
# It should have been decoded first. # It should have been decoded first.
self.assertRaises( self.assertRaises(
UnicodeDecodeError, UnicodeDecodeError,
self.mt, self.mt,
mfrom='from@example.com', mfrom='from@example.com',
mto=('to@example.com',), mto=('to@example.com',),
subject='Test Subject', subject='Test Subject',
unicode=u''.encode('utf-8'), unicode=u''.encode('utf-8'),
encoding='utf-8' encoding='utf-8'
) )
def test_encoded_html_mode(self): def test_encoded_html_mode(self):
self.MailHost.setExpected(mfrom='from@example.com', self.MailHost.setExpected(mfrom='from@example.com',
mto=('to@example.com',), mto=('to@example.com',),
filename='mail_unicode2.txt') filename='mail_unicode2.txt')
self.test_add('') self.test_add('')
self.mt.pt_edit('Test <tal:x replace="options/unicode"/>', self.mt.pt_edit('Test <tal:x replace="options/unicode"/>',
'text/html') 'text/html')
self.mt( self.mt(
mfrom='from@example.com', mfrom='from@example.com',
mto=('to@example.com',), mto=('to@example.com',),
subject='Test Subject', subject='Test Subject',
unicode=u''.encode('utf-8'), unicode=u''.encode('utf-8'),
encoding='utf-8' encoding='utf-8'
) )
def test_unicode_not_html_mode(self): def test_unicode_not_html_mode(self):
self.MailHost.setExpected(mfrom='from@example.com', self.MailHost.setExpected(mfrom='from@example.com',
mto=('to@example.com',), mto=('to@example.com',),
filename='mail_unicode.txt') filename='mail_unicode.txt')
self.test_add('Test <tal:x replace="options/unicode"/>') self.test_add('Test <tal:x replace="options/unicode"/>')
self.mt( self.mt(
mfrom='from@example.com', mfrom='from@example.com',
mto=('to@example.com',), mto=('to@example.com',),
subject='Test Subject', subject='Test Subject',
unicode=u'', unicode=u'',
encoding='utf-8' encoding='utf-8'
) )
def test_unicode_html_mode(self): def test_unicode_html_mode(self):
self.MailHost.setExpected(mfrom='from@example.com', self.MailHost.setExpected(mfrom='from@example.com',
mto=('to@example.com',), mto=('to@example.com',),
filename='mail_unicode2.txt') filename='mail_unicode2.txt')
self.test_add('') self.test_add('')
self.mt.pt_edit('Test <tal:x replace="options/unicode"/>', self.mt.pt_edit('Test <tal:x replace="options/unicode"/>',
'text/html') 'text/html')
# We get a unicode error here because we're trying to # We get a unicode error here because we're trying to
# insert a unicode into an html-mode template. # insert a unicode into an html-mode template.
# It should have been encoded first. # It should have been encoded first.
self.assertRaises( self.assertRaises(
UnicodeEncodeError, UnicodeEncodeError,
self.mt, self.mt,
mfrom='from@example.com', mfrom='from@example.com',
mto=('to@example.com',), mto=('to@example.com',),
subject='Test Subject', subject='Test Subject',
unicode=u'', unicode=u'',
encoding='utf-8' encoding='utf-8'
) )
def test_example1(self): def test_example1(self):
# login # login
noSecurityManager() noSecurityManager()
self.app.aq_chain[-1].id = 'testing' self.app.aq_chain[-1].id = 'testing'
newSecurityManager( newSecurityManager(
None, None,
SimpleUser('Test User','',('Manager',),[]).__of__(self.app) SimpleUser('Test User','',('Manager',),[]).__of__(self.app)
) )
try: try:
# setup # setup
self.r.form['file']=self.makeFileUpload(diskname='example1.mt') self.r.form['file']=self.makeFileUpload(diskname='example1.mt')
self.app.manage_addProduct['MailTemplates'].addMailTemplate( self.app.manage_addProduct['MailTemplates'].addMailTemplate(
id='my_mt', id='my_mt',
mailhost='MailHost', mailhost='MailHost',
REQUEST=self.r REQUEST=self.r
) )
self.r.form['file']=self.makeFileUpload(diskname='example1.py') self.r.form['file']=self.makeFileUpload(diskname='example1.py')
self.app.manage_addProduct['PythonScripts'].manage_addPythonScript( self.app.manage_addProduct['PythonScripts'].manage_addPythonScript(
id='test_mt', id='test_mt',
REQUEST=self.r REQUEST=self.r
) )
# set expected # set expected
self.MailHost.setExpected(mfrom='webmaster@example.com', self.MailHost.setExpected(mfrom='webmaster@example.com',
mto=('user@example.com',), mto=('user@example.com',),
filename='example1.txt') filename='example1.txt')
# test # test
self.assertEqual(self.app.test_mt(),'Mail Sent!') self.assertEqual(self.app.test_mt(),'Mail Sent!')
self.MailHost.checkSent() self.MailHost.checkSent()
finally: finally:
# logout # logout
noSecurityManager() noSecurityManager()
newSecurityManager( None, SystemUser ) newSecurityManager( None, SystemUser )
def test_example3(self): def test_example3(self):
# login # login
noSecurityManager() noSecurityManager()
self.app.aq_chain[-1].id = 'testing' self.app.aq_chain[-1].id = 'testing'
newSecurityManager( newSecurityManager(
None, None,
SimpleUser('Test User','',('Manager',),[]).__of__(self.app) SimpleUser('Test User','',('Manager',),[]).__of__(self.app)
) )
try: try:
# setup # setup
self.r.form['file']=self.makeFileUpload(diskname='example3.mt') self.r.form['file']=self.makeFileUpload(diskname='example3.mt')
self.app.manage_addProduct['MailTemplates'].addMailTemplate( self.app.manage_addProduct['MailTemplates'].addMailTemplate(
id='my_mt', id='my_mt',
mailhost='MailHost', mailhost='MailHost',
REQUEST=self.r REQUEST=self.r
) )
self.app.manage_addFile( self.app.manage_addFile(
id='myfile.bin', id='myfile.bin',
file=self.makeFileUpload(diskname='example3.bin') file=self.makeFileUpload(diskname='example3.bin')
) )
self.r.form['file']=self.makeFileUpload(diskname='example3.py') self.r.form['file']=self.makeFileUpload(diskname='example3.py')
self.app.manage_addProduct['PythonScripts'].manage_addPythonScript( self.app.manage_addProduct['PythonScripts'].manage_addPythonScript(
id='send_mail', id='send_mail',
REQUEST=self.r REQUEST=self.r
) )
# set expected # set expected
self.MailHost.setExpected(mfrom='from@example.com', self.MailHost.setExpected(mfrom='from@example.com',
mto='to1@example.com', mto='to1@example.com',
filename='example3.txt') filename='example3.txt')
# test # test
self.assertEqual(self.app.send_mail(),'Mail Sent!') self.assertEqual(self.app.send_mail(),'Mail Sent!')
self.MailHost.checkSent() self.MailHost.checkSent()
finally: finally:
# logout # logout
noSecurityManager() noSecurityManager()
newSecurityManager( None, SystemUser ) newSecurityManager( None, SystemUser )
def test_example4(self): def test_example4(self):
# login # login
noSecurityManager() noSecurityManager()
self.app.aq_chain[-1].id = 'testing' self.app.aq_chain[-1].id = 'testing'
newSecurityManager( newSecurityManager(
None, None,
SimpleUser('Test User','',('Manager',),[]).__of__(self.app) SimpleUser('Test User','',('Manager',),[]).__of__(self.app)
) )
try: try:
# setup # setup
self.r.form['file']=self.makeFileUpload(diskname='example4.mt') self.r.form['file']=self.makeFileUpload(diskname='example4.mt')
self.app.manage_addProduct['MailTemplates'].addMailTemplate( self.app.manage_addProduct['MailTemplates'].addMailTemplate(
id='my_mt', id='my_mt',
mailhost='MailHost', mailhost='MailHost',
REQUEST=self.r REQUEST=self.r
) )
self.app.my_mt.manage_addProperty( self.app.my_mt.manage_addProperty(
'subject','Welcome to %s','string' 'subject','Welcome to %s','string'
) )
self.app.my_mt.manage_addProperty( self.app.my_mt.manage_addProperty(
'mfrom','webmaster@example.com','string' 'mfrom','webmaster@example.com','string'
) )
self.r.form['file']=self.makeFileUpload(diskname='example4.py') self.r.form['file']=self.makeFileUpload(diskname='example4.py')
self.app.manage_addProduct['PythonScripts'].manage_addPythonScript( self.app.manage_addProduct['PythonScripts'].manage_addPythonScript(
id='send_mail', id='send_mail',
REQUEST=self.r REQUEST=self.r
) )
# set expected # set expected
self.MailHost.setExpected(mfrom='webmaster@example.com', self.MailHost.setExpected(mfrom='webmaster@example.com',
mto=('user@example.com',), mto=('user@example.com',),
filename='example4.txt') filename='example4.txt')
# test # test
self.assertEqual(self.app.send_mail(),'Mail Sent!') self.assertEqual(self.app.send_mail(),'Mail Sent!')
self.MailHost.checkSent() self.MailHost.checkSent()
finally: finally:
# logout # logout
noSecurityManager() noSecurityManager()
newSecurityManager( None, SystemUser ) newSecurityManager( None, SystemUser )
def test_suite(): def test_suite():
return TestSuite(( return TestSuite((
makeSuite(TestMailTemplate), makeSuite(TestMailTemplate),
)) ))
if __name__ == '__main__': if __name__ == '__main__':
main(defaultTest='test_suite') main(defaultTest='test_suite')
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment