testWebDavSupport.py 11.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2004, 2010 Nexedi SA and Contributors.
# All Rights Reserved.
#          Nicolas Delaby <nicolas@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################

import re
import unittest
import os
import transaction
from AccessControl import Unauthorized
from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import getSecurityManager
from Testing import ZopeTestCase
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Type.tests.utils import DummyLocalizer,\
     createZODBPythonScript, FileUpload
from Products.ERP5Type.tests.backportUnittest import expectedFailure

import httplib
from StringIO import StringIO
from DateTime import DateTime

from lxml import etree

def makeFilePath(name):
  return os.path.join(os.path.dirname(__file__), 'test_data', name)

def makeFileUpload(name, as_name=None):
  if as_name is None:
    as_name = name
  path = makeFilePath(name)
  return FileUpload(path, as_name)

class TestWebDavSupport(ERP5TypeTestCase):
  """Test for WEBDAV access.
  """

  authentication = 'ERP5TypeTestCase:'

  def getTitle(self):
    return "Test WebDav Support"

  def getBusinessTemplateList(self):
    """
    Return the list of required business templates.
    """
    return ('erp5_base',
            'erp5_ingestion',
            'erp5_ingestion_mysql_innodb_catalog',
            'erp5_web',
            'erp5_dms',
            )

  def afterSetUp(self):
    portal = self.getPortal()

  def clearModule(self, module):
    module.manage_delObjects(list(module.objectIds()))
    transaction.commit()
    self.tic()

  def beforeTearDown(self):
    self.clearModule(self.portal.document_module)
    self.clearModule(self.portal.web_page_module)

  def getDocumentModule(self):
    return self.portal.getDefaultModule('Text')

  def getWebPageModule(self):
    return self.portal.getDefaultModule('Web Page')

  def test_PUT_on_contributionTool(self):
    """Test Portal Contribution through Webdav calls
    Create a document
    """
    # Create a new document via FTP/DAV
    path = self.portal.portal_contributions.getPath()
    filename = 'P-DMS-Presentation.3.Pages-001-en.odp'
    file_object = makeFileUpload(filename)
    response = self.publish('%s/%s' % (path, filename),
                            request_method='PUT',
                            stdin=file_object,
                            basic=self.authentication)

    self.assertEqual(response.getStatus(), httplib.CREATED)
    document_module = self.getDocumentModule()
    self.failUnless(filename in document_module.objectIds())
    self.assertEquals(document_module[filename].getPortalType(), 'Presentation')
    file_object.seek(0)
    self.assertEquals(document_module[filename].getData(), file_object.read())

  def test_GET_on_contributionTool(self):
    """Get a document through Contribution Tool.

    XXX not sure if this test is usefull as listing all Documents from ZODB
    can collapse the portal
    """
    # Create a new document via FTP/DAV
    path = self.portal.portal_contributions.getPath()
    filename = 'P-DMS-Presentation.3.Pages-001-en.odp'
    file_object = makeFileUpload(filename)
    response = self.publish('%s/%s' % (path, filename),
                            request_method='PUT',
                            stdin=file_object,
                            basic=self.authentication)

    self.assertEqual(response.getStatus(), httplib.CREATED)
    transaction.commit()
    self.tic()

    # check Document fetching
    document_module = self.getDocumentModule()
    document = document_module[filename]
    document_id = '%s-%s' % (document.getUid(), filename,)
140 141
    # This is HTTPServer.zhttp_server not HTTPServer.zwebdav_server
    # force usage of manage_FTPget like zwebdav_server does
142
    response = self.publish('%s/%s/manage_FTPget' % (path, document_id),
143 144 145 146
                            request_method='GET',
                            stdin=StringIO(),
                            basic=self.authentication)
    self.assertEquals(response.getStatus(), httplib.OK)
147 148
    self.assertEquals(response.getBody(), document.getData(),
          'Error in getting data, get:%r' % response.getHeader('content-type'))
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208

  def test_PUT_on_web_page(self):
    """Edit a web_page in webdav
    with encoded data in iso-8859-1
    """
    # Create a new document via FTP/DAV
    path = self.portal.portal_contributions.getPath()
    filename = 'my_document.html'
    response = self.publish('%s/%s' % (path, filename),
                            request_method='PUT',
                            basic=self.authentication)

    self.assertEqual(response.getStatus(), httplib.CREATED)
    web_page_module = self.getWebPageModule()
    self.failUnless(filename in web_page_module.objectIds())
    self.assertEquals(web_page_module[filename].getPortalType(), 'Web Page')

    # Edit a new document via FTP/DAV
    text_content= """<html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
      </head>
      <body>
        <p>Content edited through webdav in iso-8859-1</p>
        <p>éàèùêôîç</p>
      </body>
    </html>
    """
    iso_text_content = text_content.decode('utf-8').encode('iso-8859-1')
    path = web_page_module.getPath()
    response = self.publish('%s/%s' % (path, filename),
                            request_method='PUT',
                            stdin=StringIO(iso_text_content),
                            basic=self.authentication)
    self.assertEqual(response.getStatus(), httplib.NO_CONTENT)
    self.assertEquals(web_page_module[filename].getData(), iso_text_content)
    # Convert to base format and run conversion into utf-8
    transaction.commit()
    self.tic()
    # Content-Type header is replaced if sonversion encoding succeed
    new_text_content = text_content.replace('charset=iso-8859-1', 'charset=utf-8')
    self.assertEquals(web_page_module[filename].getTextContent(), new_text_content)

  def test_GET_on_document(self):
    """Get data from document in webdav
    """
    path = self.portal.portal_contributions.getPath()
    filename = 'P-DMS-Presentation.3.Pages-001-en.odp'
    file_object = makeFileUpload(filename)
    response = self.publish('%s/%s' % (path, filename),
                            request_method='PUT',
                            stdin=file_object,
                            basic=self.authentication)
    # Convert to base format and run conversion into utf-8
    transaction.commit()
    self.tic()

    document_module = self.getDocumentModule()
    document = document_module[filename]

209 210 211
    # This is HTTPServer.zhttp_server not HTTPServer.zwebdav_server
    # force usage of manage_FTPget like zwebdav_server does
    response = self.publish(document.getPath()+'/manage_FTPget',
212 213 214 215 216
                            request_method='GET',
                            stdin=StringIO(),
                            basic=self.authentication)

    self.assertEquals(response.getStatus(), httplib.OK)
217 218
    self.assertEquals(response.getBody(), document.getData(),
             'Error in getting data, get:%r' % response.getHeader('content-type'))
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

  def test_PROPFIND_on_document(self):
    """test Metadata extraction from webdav protocol
    """
    path = self.portal.portal_contributions.getPath()
    filename = 'P-DMS-Presentation.3.Pages-001-en.odp'
    file_object = makeFileUpload(filename)
    response = self.publish('%s/%s' % (path, filename),
                            request_method='PUT',
                            stdin=file_object,
                            basic=self.authentication)
    document_module = self.getDocumentModule()
    document = document_module[filename]

    # Do a PROPFIND on document, this needs to result in a 207
    response = self.publish(document.getPath(),
                            request_method='PROPFIND',
                            env={'HTTP_DEPTH': '0'},
                            stdin=StringIO(),
                            basic=self.authentication)

    self.assertEquals(response.getStatus(), httplib.MULTI_STATUS)
    xml_metadata_string = response.getBody()
    xml_metadata = etree.fromstring(xml_metadata_string)
    self.assertEquals(xml_metadata.find('{DAV:}response/{DAV:}href').text,
                      document.getPath())
    self.assertEquals(xml_metadata.find(
                      '{DAV:}response/{DAV:}propstat/{DAV:}prop/'\
                      '{DAV:}getcontenttype').text,
                      document.getContentType())
    # Outputed string is not reproductable for comparaison.
    # So we need to parse the date and use the same format
    self.assertEquals(DateTime(xml_metadata.find('{DAV:}response/'\
                      '{DAV:}propstat/{DAV:}prop/{DAV:}getlastmodified')\
                      .text).ISO8601(),
                      document.getModificationDate().toZone('UTC').ISO8601())

  @expectedFailure
  def test_PROPFIND_on_document_bis(self):
    """same test than test_PROPFIND_on_document
    But with expected failure which is non blocking.
    """
    path = self.portal.portal_contributions.getPath()
    filename = 'P-DMS-Presentation.3.Pages-001-en.odp'
    file_object = makeFileUpload(filename)
    response = self.publish('%s/%s' % (path, filename),
                            request_method='PUT',
                            stdin=file_object,
                            basic=self.authentication)
    document_module = self.getDocumentModule()
    document = document_module[filename]

    # Do a PROPFIND on document, this needs to result in a 207
    response = self.publish(document.getPath(),
                            request_method='PROPFIND',
                            env={'HTTP_DEPTH': '0'},
                            stdin=StringIO(),
                            basic=self.authentication)

    self.assertEquals(response.getStatus(), httplib.MULTI_STATUS)
    xml_metadata_string = response.getBody()
    xml_metadata = etree.fromstring(xml_metadata_string)
    self.assertEquals(xml_metadata.find(
           '{DAV:}response/{DAV:}propstat/{DAV:}prop/{DAV:}creationdate').text,
                      document.getCreationDate().HTML4())

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