##############################################################################
# Copyright (c) 2005 The Open Planning Project, Rob Miller, and contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the GNU General Public
# License, Version 2.0 (GPL).  A copy of the GPL should accompany this
# distribution.  THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL
# EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY,
# AGAINST INFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
##############################################################################
import unittest

from Products.CMFCore.utils import getToolByName

from base import AnonymailerTestCase

class AnonymailerToolTestCase(AnonymailerTestCase):

    def afterSetUp(self):
        AnonymailerTestCase.afterSetUp(self)
        self.anontool = getToolByName(self.portal, 'portal_anonymailer')
        mtool = getToolByName(self.portal, 'portal_membership')
        self.mem_id = mtool.getAuthenticatedMember().getId()
        self.msg_vars = {'foo': 'bar',
                         'sna': 'foo',
                         'tar': 'foo',
                         'comment': 'This is the comment',
                         'mem_id': self.mem_id,
                         }
        
    def test_msgCache(self):
        anontool = self.anontool
        msg_key = anontool.cacheMessageVars(self.mem_id, self.msg_vars)
        cached_vars = anontool.getCachedMessageVars(msg_key)
        self.failUnless(cached_vars == self.msg_vars)

    def test_anonReplyCache(self):
        anontool = self.anontool
        orig_msg_key = anontool.cacheMessageVars(self.mem_id, self.msg_vars)
        form = {'anonymize': 1,
                'subject': 'Some Subject',
                'message': 'Some message contents.'}
        reply_vars = anontool.anonReply(orig_msg_key, form, test_mode=True)
        self.failUnless(reply_vars.get('mem_id', '') == self.mem_id)

        reply_key = reply_vars.get('msg_key')
        msg_cache = anontool._msgcache
        msg_keys = msg_cache.keys()
        self.failUnless(len(msg_keys) == 2)
        self.failUnless(orig_msg_key in msg_keys and reply_key in msg_keys)
        cached_reply_vars = anontool.getCachedMessageVars(reply_key)
        self.failIf(cached_reply_vars == reply_vars)
        uncached_vars = ['msg_key', 'send_to_address', 'template']
        for var in uncached_vars:
            reply_vars.pop(var)
        self.failUnless(cached_reply_vars == reply_vars)

def test_suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(AnonymailerToolTestCase))
    return suite

if __name__ == '__main__':
    framework()
