testWebDavSupport.py 11.9 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
# -*- 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
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()))
    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')

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
  def test_PUT_embedded_file(self):
    """Test a file can be uploaded on a document allowing embedded files
    """
    person = self.portal.person_module.newContent()
    self.tic()
    file_object = makeFileUpload('images/erp5_logo.png')
    response = self.publish(person.getPath() + '/erp5_logo.png',
                            request_method='PUT',
                            stdin=file_object,
                            basic=self.authentication)
    self.assertEqual(response.getStatus(), httplib.CREATED)
    image = person['erp5_logo.png']
    self.assertEqual(image.getPortalType(), 'Embedded File')
    self.assertEqual(image.getContentType(), 'image/png')
    file_object.seek(0)
    self.assertEqual(image.getData(), file_object.read())

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
  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()
127 128
    self.assertTrue(filename in document_module.objectIds())
    self.assertEqual(document_module[filename].getPortalType(), 'Presentation')
129
    file_object.seek(0)
130
    self.assertEqual(document_module[filename].getData(), file_object.read())
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153

  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)
    self.tic()

    # check Document fetching
    document_module = self.getDocumentModule()
    document = document_module[filename]
    document_id = '%s-%s' % (document.getUid(), filename,)
154 155
    # This is HTTPServer.zhttp_server not HTTPServer.zwebdav_server
    # force usage of manage_FTPget like zwebdav_server does
156
    response = self.publish('%s/%s/manage_FTPget' % (path, document_id),
157 158 159
                            request_method='GET',
                            stdin=StringIO(),
                            basic=self.authentication)
160 161
    self.assertEqual(response.getStatus(), httplib.OK)
    self.assertEqual(response.getBody(), document.getData(),
162
          'Error in getting data, get:%r' % response.getHeader('content-type'))
163 164 165 166 167 168 169 170 171 172 173 174 175 176

  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()
177 178
    self.assertTrue(filename in web_page_module.objectIds())
    self.assertEqual(web_page_module[filename].getPortalType(), 'Web Page')
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

    # 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)
198
    self.assertEqual(web_page_module[filename].getData(), iso_text_content)
199 200 201 202
    # Convert to base format and run conversion into utf-8
    self.tic()
    # Content-Type header is replaced if sonversion encoding succeed
    new_text_content = text_content.replace('charset=iso-8859-1', 'charset=utf-8')
203
    self.assertEqual(web_page_module[filename].getTextContent(), new_text_content)
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

  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
    self.tic()

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

221 222 223
    # 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',
224 225 226 227
                            request_method='GET',
                            stdin=StringIO(),
                            basic=self.authentication)

228 229
    self.assertEqual(response.getStatus(), httplib.OK)
    self.assertEqual(response.getBody(), document.getData(),
230
             'Error in getting data, get:%r' % response.getHeader('content-type'))
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

  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)

252
    self.assertEqual(response.getStatus(), httplib.MULTI_STATUS)
253 254
    xml_metadata_string = response.getBody()
    xml_metadata = etree.fromstring(xml_metadata_string)
255
    self.assertEqual(xml_metadata.find('{DAV:}response/{DAV:}href').text,
256
                      document.getPath())
257
    self.assertEqual(xml_metadata.find(
258 259 260 261 262
                      '{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
263
    self.assertEqual(DateTime(xml_metadata.find('{DAV:}response/'\
264 265
                      '{DAV:}propstat/{DAV:}prop/{DAV:}getlastmodified')\
                      .text).ISO8601(),
266
                      document.bobobase_modification_time().toZone('UTC').ISO8601())
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

  @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)

290
    self.assertEqual(response.getStatus(), httplib.MULTI_STATUS)
291 292
    xml_metadata_string = response.getBody()
    xml_metadata = etree.fromstring(xml_metadata_string)
293
    self.assertEqual(xml_metadata.find(
294 295 296 297 298 299 300
           '{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