[Zope3-checkins] CVS: Products3/demo/messageboard/step10/tests - __init__.py:1.1 test_fields.py:1.1 test_fs.py:1.1 test_message.py:1.1 test_messageboard.py:1.1 test_messagemail.py:1.1 test_size.py:1.1

Stephan Richter srichter@cosmos.phy.tufts.edu
Thu, 17 Jul 2003 14:23:53 -0400


Update of /cvs-repository/Products3/demo/messageboard/step10/tests
In directory cvs.zope.org:/tmp/cvs-serv3970/step10/tests

Added Files:
	__init__.py test_fields.py test_fs.py test_message.py 
	test_messageboard.py test_messagemail.py test_size.py 
Log Message:
Complimentary code for the recipe:: Providing Online Help Screens


=== Added File Products3/demo/messageboard/step10/tests/__init__.py ===
# Package Maker


=== Added File Products3/demo/messageboard/step10/tests/test_fields.py ===
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL 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.
#
##############################################################################
"""Message Board Tests

$Id: test_fields.py,v 1.1 2003/07/17 18:23:44 srichter Exp $
"""
import unittest
from zope.schema.tests.test_strfield import TextTest

from zopeproducts.messageboard.fields import HTML, ForbiddenTags

class HTMLTest(TextTest):

    _Field_Factory = HTML

    def test_AllowedTagsHTMLValidate(self):
        html = self._Field_Factory(allowed_tags=('h1','pre'))
        html.validate(u'<h1>Blah</h1>') 
        html.validate(u'<pre>Blah</pre>') 
        html.validate(u'<h1><pre>Blah</pre></h1>') 
        html.validate(u'<h1 style="..."><pre>Blah</pre></h1>') 
        html.validate(u'<h1 style="..."><pre f="">Blah</pre></h1>') 

        self.assertRaisesErrorNames(ForbiddenTags, html.validate,
                                    u'<h2>Foo</h2>')
        self.assertRaisesErrorNames(ForbiddenTags, html.validate,
                                    u'<h2><pre>Foo</pre></h2>')
        self.assertRaisesErrorNames(ForbiddenTags, html.validate,
                                    u'<h2 attr="blah">Foo</h2>')


    def test_ForbiddenTagsHTMLValidate(self):
        html = self._Field_Factory(forbidden_tags=('h2','pre'))
        html.validate(u'<h1>Blah</h1>') 
        html.validate(u'<h1 style="...">Blah</h1>') 
        html.validate(u'<h1 style="..."><div>Blah</div></h1>') 
        html.validate(u'<h1 style="..."><div f="">Blah</div></h1>') 

        self.assertRaisesErrorNames(ForbiddenTags, html.validate,
                                    u'<h2>Foo</h2>')
        self.assertRaisesErrorNames(ForbiddenTags, html.validate,
                                    u'<h2><div>Foo</div></h2>')
        self.assertRaisesErrorNames(ForbiddenTags, html.validate,
                                    u'<h2 attr="blah">Foo</h2>')


def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(HTMLTest),
        ))

if __name__ == '__main__':
    unittest.main()


=== Added File Products3/demo/messageboard/step10/tests/test_fs.py ===
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL 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.
#
##############################################################################
"""FTP Views for the MessageBoard and Message component

$Id: test_fs.py,v 1.1 2003/07/17 18:23:44 srichter Exp $
"""
import unittest
from zope.interface.verify import verifyObject
from zope.component.adapter import provideAdapter
from zope.component.tests.placelesssetup import PlacelessSetup

from zopeproducts.messageboard.interfaces import \
     IVirtualContentsFile, IPlainText, IMessage, IMessageBoard

from zopeproducts.messageboard.message import \
     Message, PlainText as MessagePlainText
from zopeproducts.messageboard.messageboard import \
     MessageBoard, PlainText as MessageBoardPlainText
from zopeproducts.messageboard.fs import \
     VirtualContentsFile, ReadDirectory, MessageFactory


class VirtualContentsFileTestBase(PlacelessSetup):

    def _makeFile(self):
        raise NotImplemented

    def _registerPlainTextAdapter(self):
        raise NotImplemented

    def setUp(self):
        PlacelessSetup.setUp(self)
        self._registerPlainTextAdapter()

    def testContentType(self):
        file = self._makeFile()
        self.assertEqual(file.getContentType(), 'text/plain')
        file.setContentType('text/html')
        self.assertEqual(file.getContentType(), 'text/plain')
        self.assertEqual(file.contentType, 'text/plain')

    def testData(self):
        file = self._makeFile()

        file.setData('Foobar')
        self.assert_(file.getData().find('Foobar') >= 0)
        self.assert_(file.data.find('Foobar') >= 0)

        file.edit('Blah', 'text/html')
        self.assertEqual(file.contentType, 'text/plain')
        self.assert_(file.data.find('Blah') >= 0)

    def testInterface(self):
        file = self._makeFile()
        self.failUnless(IVirtualContentsFile.isImplementedBy(file))
        self.failUnless(verifyObject(IVirtualContentsFile, file))


class MessageVirtualContentsFileTest(VirtualContentsFileTestBase,
                                     unittest.TestCase):
    
    def _makeFile(self):
        return VirtualContentsFile(Message())

    def _registerPlainTextAdapter(self):
        provideAdapter(IMessage, IPlainText, MessagePlainText)

    def testMessageSpecifics(self):
        file = self._makeFile()
        self.assertEqual(file.context.title, '')
        self.assertEqual(file.context.body, '')
        file.data = 'Title: Hello\n\nWorld'
        self.assertEqual(file.context.title, 'Hello')
        self.assertEqual(file.context.body, 'World')
        file.data = 'World 2'
        self.assertEqual(file.context.body, 'World 2')


class MessageBoardVirtualContentsFileTest(VirtualContentsFileTestBase,
                                          unittest.TestCase):
    
    def _makeFile(self):
        return VirtualContentsFile(MessageBoard())

    def _registerPlainTextAdapter(self):
        provideAdapter(IMessageBoard, IPlainText, MessageBoardPlainText)

    def testMessageBoardSpecifics(self):
        file = self._makeFile()
        self.assertEqual(file.context.description, '')
        file.data = 'Title: Hello\n\nWorld'
        self.assertEqual(file.context.description, 'Title: Hello\n\nWorld')
        file.data = 'World 2'
        self.assertEqual(file.context.description, 'World 2')


class ReadDirectoryTestBase:

    def _makeDirectoryObject(self):
        raise NotImplemented

    def _makeTree(self):
        base = self._makeDirectoryObject()
        msg1 = Message()
        msg1.title = 'Message 1'
        msg1.description = 'This is Message 1.'
        msg11 = Message()
        msg11.title = 'Message 1-1'
        msg11.description = 'This is Message 1-1.'
        msg2 = Message()
        msg2.title = 'Message 1'
        msg2.description = 'This is Message 1.'
        msg1.setObject('msg11', msg11)
        base.setObject('msg1', msg1)
        base.setObject('msg2', msg2)
        return ReadDirectory(base)

    def testKeys(self):
        tree = self._makeTree()
        keys = list(tree.keys())
        keys.sort()
        self.assertEqual(keys, ['contents', 'msg1', 'msg2'])
        keys = list(ReadDirectory(tree['msg1']).keys())
        keys.sort()
        self.assertEqual(keys, ['contents', 'msg11'])

    def testGet(self):
        tree = self._makeTree()
        self.assertEqual(tree.get('msg1'), tree.context['msg1'])
        self.assertEqual(tree.get('msg3'), None)
        default = object()
        self.assertEqual(tree.get('msg3', default), default)
        self.assertEqual(tree.get('contents').__class__, VirtualContentsFile)

    def testLen(self):
        tree = self._makeTree()
        self.assertEqual(len(tree), 3)
        self.assertEqual(len(ReadDirectory(tree['msg1'])), 2)
        self.assertEqual(len(ReadDirectory(tree['msg2'])), 1)
        

class MessageReadDirectory(ReadDirectoryTestBase, unittest.TestCase):

    def _makeDirectoryObject(self):
        return Message()


class MessageBoardReadDirectory(ReadDirectoryTestBase, unittest.TestCase):

    def _makeDirectoryObject(self):
        return MessageBoard()


def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(MessageVirtualContentsFileTest),
        unittest.makeSuite(MessageBoardVirtualContentsFileTest),
        unittest.makeSuite(MessageReadDirectory),
        unittest.makeSuite(MessageBoardReadDirectory),
        ))

if __name__ == '__main__':
    unittest.main()


=== Added File Products3/demo/messageboard/step10/tests/test_message.py ===
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL 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.
#
##############################################################################
"""Message Board Tests

$Id: test_message.py,v 1.1 2003/07/17 18:23:44 srichter Exp $
"""
import unittest
from zope.testing.doctestunit import DocTestSuite

from zope.app.container.tests.test_icontainer import \
     BaseTestIContainer, DefaultTestData
from zopeproducts.messageboard.message import Message
from zopeproducts.messageboard.interfaces import IMessage


class Test(BaseTestIContainer, unittest.TestCase):

    def makeTestObject(self):
        return Message()

    def makeTestData(self):
        return DefaultTestData()

    def test_interface(self):
        self.assert_(IMessage.isImplementedBy(
            self.makeTestObject()))

def test_title():
    """
    >>> msg = Message()
    >>> msg.title
    u''
    >>> msg.title = u'Message Title'
    >>> msg.title
    u'Message Title'

    """

def test_body():
    """
    >>> msg = Message()
    >>> msg.body
    u''
    >>> msg.body = u'Message Body'
    >>> msg.body
    u'Message Body'

    """


def test_suite():
    return unittest.TestSuite((
        DocTestSuite(),
        unittest.makeSuite(Test),
        ))

if __name__ == '__main__':
    unittest.main()


=== Added File Products3/demo/messageboard/step10/tests/test_messageboard.py ===
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL 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.
#
##############################################################################
"""Message Board Tests

$Id: test_messageboard.py,v 1.1 2003/07/17 18:23:44 srichter Exp $
"""
import unittest

from zope.app.container.tests.test_icontainer import \
     BaseTestIContainer, DefaultTestData
from zopeproducts.messageboard.messageboard import MessageBoard
from zopeproducts.messageboard.interfaces import IMessageBoard


class Test(BaseTestIContainer, unittest.TestCase):

    def makeTestObject(self):
        return MessageBoard()

    def makeTestData(self):
        return DefaultTestData()

    def test_interface(self):
        self.assert_(IMessageBoard.isImplementedBy(
            self.makeTestObject()))

    def test_description(self):
        board = self.makeTestObject()
        self.assertEqual(u'', board.description)
        board.description = u'Message Board Description'
        self.assertEqual('Message Board Description',
                         board.description)


def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(Test),
        ))

if __name__ == '__main__':
    unittest.main()


=== Added File Products3/demo/messageboard/step10/tests/test_messagemail.py ===
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL 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.
#
##############################################################################
"""Messageboard Mail Subscription and Mailer Tests

$Id: test_messagemail.py,v 1.1 2003/07/17 18:23:44 srichter Exp $
"""
import unittest

from zope.app.interfaces.annotation import IAnnotations, IAttributeAnnotatable
from zope.app.interfaces.event import ISubscriber
from zope.app.interfaces.mail import IMailService
from zope.app.interfaces.traversing import IPhysicallyLocatable
from zopeproducts.messageboard.interfaces import IMessage, IMailSubscriptions

from zope.interface import classImplements 
from zope.component.adapter import provideAdapter
from zope.component.tests.placelesssetup import PlacelessSetup
from zope.app.attributeannotations import AttributeAnnotations
from zope.app.context import ContextWrapper
from zope.app.event.objectevent import ObjectModifiedEvent

from zopeproducts.messageboard.message import Message
from zopeproducts.messageboard.message import \
     MailSubscriptions, MessageMailer, mailer

SubscriberKey = 'http://www.zope.org/messageboard#1.0/MailSubscriptions/emails'


from zope.app.traversing.adapters import WrapperPhysicallyLocatable
from zope.component.service import defineService, serviceManager
from zope.interface import implements

mail_result = [] 

class MailServiceStub(object):

    implements(IMailService)

    def send(self, fromaddr, toaddrs, message):
        mail_result.append((fromaddr, toaddrs, message))


class MailSubscriptionTest(PlacelessSetup, unittest.TestCase):

    def setUp(self):
        PlacelessSetup.setUp(self)
        # This needs to be done, since the IAttributeAnnotable interface
        # is usually set in the ZCML
        classImplements(Message, IAttributeAnnotatable)
        provideAdapter(IAttributeAnnotatable, IAnnotations,
                       AttributeAnnotations)
        self._sub = MailSubscriptions(Message())

    def test_Interface(self):
        self.failUnless(IMailSubscriptions.isImplementedBy(self._sub))

    def test_getSubscriptions(self):
        self.assertEqual((), self._sub.getSubscriptions())
        self._sub.context.__annotations__[SubscriberKey] = ('foo@bar.com',)
        self.assertEqual(('foo@bar.com',), self._sub.getSubscriptions())

    def test_addSubscriptions(self):
        self._sub.addSubscriptions(('foo@bar.com',))
        self.assertEqual(('foo@bar.com',),
                         self._sub.context.__annotations__[SubscriberKey])
        self._sub.addSubscriptions(('blah@bar.com',))
        self.assertEqual(('foo@bar.com', 'blah@bar.com'),
                         self._sub.context.__annotations__[SubscriberKey])
        self._sub.addSubscriptions(('blah@bar.com',))
        self.assertEqual(('foo@bar.com', 'blah@bar.com'),
                         self._sub.context.__annotations__[SubscriberKey])
        self._sub.addSubscriptions(('blah@bar.com', 'doh@bar.com'))
        self.assertEqual(('foo@bar.com', 'blah@bar.com', 'doh@bar.com'),
                         self._sub.context.__annotations__[SubscriberKey])

    def test_removeSubscriptions(self):
        self._sub.context.__annotations__[SubscriberKey] = (
            'foo@bar.com', 'blah@bar.com', 'doh@bar.com')
        self._sub.removeSubscriptions(('foo@bar.com',))
        self.assertEqual(('blah@bar.com', 'doh@bar.com'),
                         self._sub.context.__annotations__[SubscriberKey])
        self._sub.removeSubscriptions(('foo@bar.com',))
        self.assertEqual(('blah@bar.com', 'doh@bar.com'),
                         self._sub.context.__annotations__[SubscriberKey])
        self._sub.removeSubscriptions(('blah@bar.com', 'doh@bar.com'))
        self.assertEqual((),
                         self._sub.context.__annotations__[SubscriberKey])


class WikiMailerTest(PlacelessSetup, unittest.TestCase):

    def setUp(self):
        PlacelessSetup.setUp(self)
        # This needs to be done, since the IAttributeAnnotable interface
        # is usually set in the ZCML
        provideAdapter(None, IPhysicallyLocatable, WrapperPhysicallyLocatable)
        classImplements(Message, IAttributeAnnotatable)
        provideAdapter(IMessage, IMailSubscriptions,
                       MailSubscriptions)
        provideAdapter(IAttributeAnnotatable, IAnnotations,
                       AttributeAnnotations)
        defineService('Mail', IMailService)
        serviceManager.provideService('Mail', MailServiceStub())

    def test_Interface(self):
        self.failUnless(ISubscriber.isImplementedBy(mailer))

    def test_getAllSubscribers(self):
        msg1 = Message()
        msg1_sub = MailSubscriptions(msg1)
        msg1_sub.context.__annotations__[SubscriberKey] = ('foo@bar.com',)
        wrapped_msg1 = ContextWrapper(msg1, object(), name='msg1')
        msg2 = Message()
        msg2_sub = MailSubscriptions(msg2)
        msg2_sub.context.__annotations__[SubscriberKey] = ('blah@bar.com',)
        msg1.setObject('msg2', msg2)
        wrapped_msg2 = ContextWrapper(msg2, wrapped_msg1, name="msg2")
        self.assertEqual(('blah@bar.com', 'foo@bar.com'),
                         mailer.getAllSubscribers(wrapped_msg2))

    def test_notify(self):
        msg = Message()
        msg.title = 'Hello'
        msg.body = 'Hello World!'
        msg_sub = MailSubscriptions(msg)
        msg_sub.context.__annotations__[SubscriberKey] = ('foo@bar.com',)
        wrapped_msg = ContextWrapper(msg, object(), name='msg')
        event = ObjectModifiedEvent(wrapped_msg)
        mailer.notify(event)
        self.assertEqual('mailer@messageboard.org', mail_result[0][0])
        self.assertEqual(('foo@bar.com', ), mail_result[0][1])
        self.assertEqual('Subject: Modified: msg\n\n\nHello World!',
                         mail_result[0][2])

def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(MailSubscriptionTest),
        unittest.makeSuite(WikiMailerTest),
        ))

if __name__ == '__main__':
    unittest.main()


=== Added File Products3/demo/messageboard/step10/tests/test_size.py ===
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL 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.
#
##############################################################################
"""Message Size Tests

$Id: test_size.py,v 1.1 2003/07/17 18:23:44 srichter Exp $
"""
import unittest
from zope.app.interfaces.size import ISized
from zopeproducts.messageboard.message import Message, MessageSized

class Stub:
    pass

class SizedTest(unittest.TestCase):

    def test_interface(self):
        self.assert_(ISized.isImplementedBy(MessageSized(Message())))

    def test_sizeForSorting(self):
        size = MessageSized(Message())
        self.assertEqual(('item', 0), size.sizeForSorting())
        size._message.setObject('msg1', Message()) 
        self.assertEqual(('item', 1), size.sizeForSorting())
        size._message.setObject('att1', Stub()) 
        self.assertEqual(('item', 2), size.sizeForSorting())

    def test_sizeForDisplay(self):
        size = MessageSized(Message())
        self.assertEqual('${messages} replies, ${attach} attachments',
                         str(size.sizeForDisplay()))
        self.assertEqual({'attach': '0', 'messages': '0'},
                         size.sizeForDisplay().mapping)
        size._message.setObject('msg1', Message()) 
        self.assertEqual('1 reply, ${attach} attachments',
                         size.sizeForDisplay())
        self.assertEqual({'attach': '0', 'messages': '1'},
                         size.sizeForDisplay().mapping)
        size._message.setObject('msg2', Message()) 
        self.assertEqual('${messages} replies, ${attach} attachments',
                         size.sizeForDisplay())
        self.assertEqual({'attach': '0', 'messages': '2'},
                         size.sizeForDisplay().mapping)
        size._message.setObject('att1', Stub()) 
        self.assertEqual('${messages} replies, 1 attachment',
                         size.sizeForDisplay())
        self.assertEqual({'attach': '1', 'messages': '2'},
                         size.sizeForDisplay().mapping)
        size._message.setObject('att2', Stub()) 
        self.assertEqual('${messages} replies, ${attach} attachments',
                         str(size.sizeForDisplay()))
        self.assertEqual({'attach': '2', 'messages': '2'},
                         size.sizeForDisplay().mapping)

def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(SizedTest),
        ))

if __name__ == '__main__':
    unittest.main()