[Zope3-checkins] CVS: Zope3/src/zope/app/publication/tests - test_http.py:1.1.2.1 test_httpfactory.py:1.1.2.1 test_browserpublication.py:1.5.2.1 test_simplecomponenttraverser.py:1.2.4.1 test_zopepublication.py:1.5.2.1

Sidnei da Silva sidnei@x3ng.com.br
Tue, 11 Feb 2003 09:41:55 -0500


Update of /cvs-repository/Zope3/src/zope/app/publication/tests
In directory cvs.zope.org:/tmp/cvs-serv18615/src/zope/app/publication/tests

Modified Files:
      Tag: paris-copypasterename-branch
	test_browserpublication.py test_simplecomponenttraverser.py 
	test_zopepublication.py 
Added Files:
      Tag: paris-copypasterename-branch
	test_http.py test_httpfactory.py 
Log Message:
Updating from HEAD to make sure everything still works before merging

=== Added File Zope3/src/zope/app/publication/tests/test_http.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.
#
##############################################################################
"""
$Id: test_http.py,v 1.1.2.1 2003/02/11 14:41:23 sidnei Exp $
"""

from unittest import TestCase, TestSuite, main, makeSuite
import zope.app.publication.http
from zope.publisher.http import HTTPRequest
from zope.app.tests.placelesssetup import PlacelessSetup
from StringIO import StringIO
from zope.component.view import provideView
from zope.interface import Interface
from zope.publisher.interfaces.http import IHTTPPresentation

class I(Interface): pass
class C:
    spammed = 0
    __implements__ = I

class V:

    def __init__(self, context, request):
        self.context = context
    
    def SPAM(self):
        self.context.spammed += 1



class Test(PlacelessSetup, TestCase):
    # Note that zope publication tests cover all of the code but callObject

    def test_callObject(self):
        pub = zope.app.publication.http.HTTPPublication(None)
        request = HTTPRequest(StringIO(''), StringIO(), {})
        request.method = 'SPAM'
        provideView(I, 'SPAM', IHTTPPresentation, V)

        ob = C()
        pub.callObject(request, ob)
        self.assertEqual(ob.spammed, 1)

        

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

if __name__=='__main__':
    main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/publication/tests/test_httpfactory.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.
#
##############################################################################
"""
$Id: test_httpfactory.py,v 1.1.2.1 2003/02/11 14:41:23 sidnei Exp $
"""

from unittest import TestCase, TestSuite, main, makeSuite
from zope.app.publication.httpfactory import HTTPPublicationRequestFactory
from zope.publisher.browser import BrowserRequest
from zope.app.publication.browser import BrowserPublication
from zope.publisher.http import HTTPRequest
from zope.app.publication.http import HTTPPublication
from zope.publisher.xmlrpc import XMLRPCRequest
from zope.app.publication.xmlrpc import XMLRPCPublication
from StringIO import StringIO

class Test(TestCase):

    def setUp(self):
        self.__factory = HTTPPublicationRequestFactory(None)
        self.__env =  {
            'SERVER_URL':         'http://127.0.0.1',
            'HTTP_HOST':          '127.0.0.1',
            'CONTENT_LENGTH':     '0',
            'GATEWAY_INTERFACE':  'TestFooInterface/1.0',
            }

    def test_browser(self):
        r = self.__factory(StringIO(''), StringIO(), self.__env)
        self.assertEqual(r.__class__, BrowserRequest)
        self.assertEqual(r.publication.__class__, BrowserPublication)

        for method in ('GET', 'HEAD', 'POST', 'get', 'head', 'post'):
            self.__env['REQUEST_METHOD'] = method
            r = self.__factory(StringIO(''), StringIO(), self.__env)
            self.assertEqual(r.__class__, BrowserRequest)
            self.assertEqual(r.publication.__class__, BrowserPublication)
            

    def test_http(self):

        for method in ('PUT', 'put', 'XXX'):
            self.__env['REQUEST_METHOD'] = method
            r = self.__factory(StringIO(''), StringIO(), self.__env)
            self.assertEqual(r.__class__, HTTPRequest)
            self.assertEqual(r.publication.__class__, HTTPPublication)

    def test_xmlrpc(self):
        self.__env['CONTENT_TYPE'] = 'text/xml'
        for method in ('POST', 'post'):
            self.__env['REQUEST_METHOD'] = method
            r = self.__factory(StringIO(''), StringIO(), self.__env)
            self.assertEqual(r.__class__, XMLRPCRequest)
            self.assertEqual(r.publication.__class__, XMLRPCPublication)


        # content type doesn't matter for non post
        for method in ('GET', 'HEAD', 'get', 'head'):
            self.__env['REQUEST_METHOD'] = method
            r = self.__factory(StringIO(''), StringIO(), self.__env)
            self.assertEqual(r.__class__, BrowserRequest)
            self.assertEqual(r.publication.__class__, BrowserPublication)

        for method in ('PUT', 'put', 'XXX'):
            self.__env['REQUEST_METHOD'] = method
            r = self.__factory(StringIO(''), StringIO(), self.__env)
            self.assertEqual(r.__class__, HTTPRequest)
            self.assertEqual(r.publication.__class__, HTTPPublication)

    
        

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

if __name__=='__main__':
    main(defaultTest='test_suite')


=== Zope3/src/zope/app/publication/tests/test_browserpublication.py 1.5 => 1.5.2.1 ===
--- Zope3/src/zope/app/publication/tests/test_browserpublication.py:1.5	Mon Jan 20 17:16:00 2003
+++ Zope3/src/zope/app/publication/tests/test_browserpublication.py	Tue Feb 11 09:41:23 2003
@@ -13,9 +13,12 @@
 ##############################################################################
 import unittest
 
+from StringIO import StringIO
+
 from zope.interface import Interface
 
 from zope.component import getService, getServiceManager
+from zope.component.servicenames import Views
 
 from zope.publisher.publish import publish
 from zope.publisher.browser import BrowserView, TestRequest
@@ -191,7 +194,7 @@
                 self.counter+=1
                 return self.context[name]
 
-        provideView=getService(None, "Views").provideView
+        provideView=getService(None, Views).provideView
         provideView(I1, '_traverse', IBrowserPresentation, [Adapter])
         ob = mydict()
         ob['bruce'] =  SimpleObject('bruce')
@@ -214,7 +217,7 @@
             def browserDefault(self, request):
                 return (self.context['bruce'], 'dummy')
 
-        provideView=getService(None, "Views").provideView
+        provideView=getService(None, Views).provideView
         provideView(I1, '_traverse', IBrowserPresentation, [Adapter])
         ob = mydict()
         ob['bruce'] =  SimpleObject('bruce')
@@ -237,7 +240,7 @@
 
         pub = self.klass(self.db)
         ob = C()
-        provideView=getService(None, "Views").provideView
+        provideView=getService(None, Views).provideView
         provideView(I1, 'edit', IBrowserPresentation, [BobView])
 
         r = self._createRequest('/@@edit;skin=zmi',pub)
@@ -256,7 +259,7 @@
             x = SimpleObject(1)
         ob = C()
         r = self._createRequest('/x',pub)
-        provideView=getService(None, "Views").provideView
+        provideView=getService(None, Views).provideView
         provideView(None, '_traverse', IBrowserPresentation, [TestTraverser])
         ob2 = pub.traverseName(r, ob, 'x')
         self.assertEqual(removeAllProxies(ob2).v, 1)
@@ -272,7 +275,7 @@
             def __init__(self, context, request): pass
             __implements__ = IBrowserPresentation
         r = self._createRequest('/@@spam',pub)
-        provideView=getService(None, "Views").provideView
+        provideView=getService(None, Views).provideView
         provideView(I, 'spam', IBrowserPresentation, [V])
         ob2 = pub.traverseName(r, ob, '@@spam')
         self.assertEqual(removeAllProxies(ob2).__class__, V)
@@ -302,6 +305,50 @@
         app = r.publication.getApplication(r)
         self.assertEqual(app, applicationControllerRoot)
 
+
+    def testHEADFuxup(self):
+        pub = self.klass(None)
+
+        class User:
+            def getId(self):
+                return 'bob'
+
+        # With a normal request, we should get a body:
+        output = StringIO()
+        request = TestRequest(StringIO(''), output, {'PATH_INFO': '/'})
+        request.user = User()
+        request.response.setBody("spam")
+        pub.afterCall(request)
+        request.response.outputBody()
+        self.assertEqual(
+            output.getvalue(),
+            'Status: 200 Ok\r\n'
+            'Content-Length: 4\r\n'
+            'Content-Type: text/plain;charset=iso-8859-1\r\n'
+            'X-Powered-By: Zope (www.zope.org), Python (www.python.org)\r\n'
+            '\r\nspam'
+            )
+
+        # But with a HEAD request, the body should be empty
+        output = StringIO()
+        request = TestRequest(StringIO(''), output, {'PATH_INFO': '/'})
+        request.user = User()
+        request.method = 'HEAD'
+        request.response.setBody("spam")
+        pub.afterCall(request)
+        request.response.outputBody()
+        self.assertEqual(
+            output.getvalue(),
+            'Status: 200 Ok\r\n'
+            'Content-Length: 0\r\n'
+            'Content-Type: text/plain;charset=iso-8859-1\r\n'
+            'X-Powered-By: Zope (www.zope.org), Python (www.python.org)\r\n'
+            '\r\n'
+            )
+
+        
+        
+        
 
 def test_suite():
     t2 = unittest.makeSuite(BrowserPublicationTests, 'test')


=== Zope3/src/zope/app/publication/tests/test_simplecomponenttraverser.py 1.2 => 1.2.4.1 ===
--- Zope3/src/zope/app/publication/tests/test_simplecomponenttraverser.py:1.2	Wed Dec 25 09:13:08 2002
+++ Zope3/src/zope/app/publication/tests/test_simplecomponenttraverser.py	Tue Feb 11 09:41:23 2003
@@ -20,6 +20,7 @@
 from zope.component.tests.request import Request
 from zope.app.publication.traversers import SimpleComponentTraverser
 from zope.component import getService
+from zope.component.servicenames import Views
 from zope.interface import Interface
 from zope.exceptions import NotFoundError
 from zope.app.tests.placelesssetup import PlacelessSetup
@@ -66,7 +67,7 @@
         req = Request( I, '')
 
         T = SimpleComponentTraverser(c, req)
-        getService(None,"Views").provideView(None , 'foo', I, [View])
+        getService(None,Views).provideView(None , 'foo', I, [View])
 
         self.failUnless(T.publishTraverse(req,'foo').__class__ is View )
 


=== Zope3/src/zope/app/publication/tests/test_zopepublication.py 1.5 => 1.5.2.1 ===
--- Zope3/src/zope/app/publication/tests/test_zopepublication.py:1.5	Mon Dec 30 22:35:09 2002
+++ Zope3/src/zope/app/publication/tests/test_zopepublication.py	Tue Feb 11 09:41:23 2003
@@ -12,6 +12,7 @@
 #
 ##############################################################################
 import unittest
+import sys
 
 from zope.interface.verify import verifyClass
 from zope.interface.implements import instancesOfObjectImplements
@@ -20,6 +21,7 @@
 
 from zope.app.tests.placelesssetup import PlacelessSetup
 from zope.component.adapter import provideAdapter
+from zope.component.view import provideView, setDefaultViewName
 
 from zope.i18n.interfaces import IUserPreferredCharsets
 
@@ -43,9 +45,9 @@
 from zope.component.service import serviceManager
 
 from transaction import get_transaction
+from cStringIO import StringIO
 
 class BasePublicationTests(PlacelessSetup, unittest.TestCase):
-    klass = ZopePublication
 
     def setUp(self):
         PlacelessSetup.setUp(self)
@@ -80,7 +82,7 @@
         PlacelessSetup.tearDown(self)
 
     def testInterfacesVerify(self):
-        for interface in instancesOfObjectImplements(self.klass):
+        for interface in instancesOfObjectImplements(ZopePublication):
             verifyClass(interface, TestPublication)
 
 class Principal:
@@ -121,18 +123,147 @@
 
     __implements__ = IServiceService # a dirty lie
 
-    def __init__(self, auth):   self.auth = auth
-    def get(self, key, d=None):      return self.auth
+    def __init__(self, auth):
+        self.auth = auth
+
+    def get(self, key, d=None):
+        return self.auth
+
     __getitem__ = get
-    def __contains__(self, key): return 1
+
+    def __contains__(self, key):
+        return 1
 
     def getService(self, name):
         # I just wanna get the test to pass. Waaaaa
         return serviceManager.getService(name)
 
 
+class ZopePublicationErrorHandling(BasePublicationTests):
+
+    def setUp(self):
+        BasePublicationTests.setUp(self)
+        root = self.db.open().root()
+        self.out = StringIO()
+        self.request = TestRequest('/f1/f2', outstream=self.out)
+        from zope.interface import Interface
+        self.presentation_type = Interface
+        self.request._presentation_type = self.presentation_type
+        self.publication = ZopePublication(self.db)
+        self.object = object()  # doesn't matter what it is
+
+    def testRetryAllowed(self):
+        from zodb.interfaces import ConflictError
+        from zope.publisher.interfaces import Retry
+        try:
+            raise ConflictError
+        except:
+            pass
+        self.assertRaises(Retry, self.publication.handleException,
+            self.object, self.request, sys.exc_info(), retry_allowed=True)
+
+    def testRetryNotAllowed(self):
+        from zodb.interfaces import ConflictError
+        from zope.publisher.interfaces import Retry
+        try:
+            raise ConflictError
+        except:
+            pass
+        self.publication.handleException(
+            self.object, self.request, sys.exc_info(), retry_allowed=False)
+        self.request.response.outputBody()
+        value = self.out.getvalue().split()
+        self.assertEqual(' '.join(value[:6]),
+                         'Traceback (most recent call last): File')
+        self.assertEqual(' '.join(value[9:]),
+                         'in testRetryNotAllowed raise ConflictError'
+                         ' ConflictError: database conflict error')
+
+    def testViewOnException(self):
+        from zodb.interfaces import ConflictError
+        from zope.interface import Interface
+        from zope.interface.implements import implements
+        class IConflictError(Interface):
+            pass
+        implements(ConflictError, IConflictError)
+        setDefaultViewName(IConflictError, self.presentation_type, 'name')
+        view_text = 'You had a conflict error'
+        provideView(IConflictError, 'name', self.presentation_type,
+                    [lambda obj,request: lambda: view_text])
+        try:
+            raise ConflictError
+        except:
+            pass
+        self.publication.handleException(
+            self.object, self.request, sys.exc_info(), retry_allowed=False)
+        self.request.response.outputBody()
+        self.assertEqual(self.out.getvalue(), view_text)
+
+    def testNoViewOnClassicClassException(self):
+        from zodb.interfaces import ConflictError
+        from zope.interface import Interface
+        from zope.interface.implements import implements
+        from types import ClassType
+        class ClassicError:
+            __metaclass__ = ClassType
+        class IClassicError(Interface):
+            pass
+        implements(ClassicError, IClassicError)
+        setDefaultViewName(IClassicError, self.presentation_type, 'name')
+        view_text = 'You made a classic error ;-)'
+        provideView(IClassicError, 'name', self.presentation_type,
+                    [lambda obj,request: lambda: view_text])
+        try:
+            raise ClassicError
+        except:
+            pass
+        self.publication.handleException(
+            self.object, self.request, sys.exc_info(), retry_allowed=False)
+        self.request.response.outputBody()
+        # check we don't get the view we registered
+        self.failIf(self.out.getvalue() == view_text)
+        # check we do actually get something
+        self.failIf(self.out.getvalue() == '')
+
+    def testExceptionSideEffects(self):
+        from zope.publisher.interfaces import IExceptionSideEffects
+        class SideEffects:
+            __implements__ = IExceptionSideEffects
+            def __init__(self, exception):
+                self.exception = exception
+            def __call__(self, obj, request, exc_info):
+                self.obj = obj
+                self.request = request
+                self.exception_type = exc_info[0]
+                self.exception_from_info = exc_info[1]
+        class SideEffectsFactory:
+            def __call__(self, exception):
+                self.adapter = SideEffects(exception)
+                return self.adapter
+        factory = SideEffectsFactory()
+        from zodb.interfaces import ConflictError
+        from zope.interface import Interface
+        from zope.interface.implements import implements
+        class IConflictError(Interface):
+            pass
+        implements(ConflictError, IConflictError)
+        provideAdapter(IConflictError, IExceptionSideEffects, factory)
+        exception = ConflictError()
+        try:
+            raise exception
+        except:
+            pass
+        self.publication.handleException(
+            self.object, self.request, sys.exc_info(), retry_allowed=False)
+        adapter = factory.adapter
+        self.assertEqual(exception, adapter.exception)
+        self.assertEqual(exception, adapter.exception_from_info)
+        self.assertEqual(ConflictError, adapter.exception_type)
+        self.assertEqual(self.object, adapter.obj)
+        self.assertEqual(self.request, adapter.request)
+
+
 class ZopePublicationTests(BasePublicationTests):
-    klass = ZopePublication
 
     def testPlacefulAuth(self):
         principalRegistry.defineDefaultPrincipal('anonymous', '')
@@ -151,8 +282,7 @@
 
         from zope.component.view import provideView
         from zope.app.interfaces.container import ISimpleReadContainer
-        from zope.app.container.traversal \
-             import ContainerTraverser
+        from zope.app.container.traversal import ContainerTraverser
         from zope.component.interfaces import IPresentation
         provideView(ISimpleReadContainer, '_traverse', IPresentation,
                     ContainerTraverser)
@@ -164,7 +294,7 @@
 
         request.setViewType(IPresentation)
 
-        publication = self.klass(self.db)
+        publication = ZopePublication(self.db)
 
         publication.beforeTraversal(request)
         self.assertEqual(request.user.getId(), 'anonymous')
@@ -179,7 +309,10 @@
         self.assertEqual(request.user.getId(), 'test.bob')
 
 def test_suite():
-    return unittest.makeSuite(ZopePublicationTests)
+    return unittest.TestSuite((
+        unittest.makeSuite(ZopePublicationTests),
+        unittest.makeSuite(ZopePublicationErrorHandling),
+        ))
 
 if __name__ == '__main__':
     unittest.TextTestRunner().run( test_suite() )