testIngestion.py 83.9 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
##############################################################################
3
#
Nicolas Delaby's avatar
Nicolas Delaby committed
4
# Copyright (c) 2010 Nexedi SA and Contributors. All Rights Reserved.
5 6
#                    Bartek Gorny <bg@erp5.pl>
#                    Jean-Paul Smets <jp@nexedi.com>
7
#                    Ivan Tyagov <ivan@nexedi.com>
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability 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
# garantees 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.
#
##############################################################################

Jérome Perrin's avatar
Jérome Perrin committed
32 33
import unittest
import os, cStringIO, zipfile
Nicolas Delaby's avatar
Nicolas Delaby committed
34
from lxml import etree
35 36
from Testing import ZopeTestCase
from DateTime import DateTime
37
from AccessControl.SecurityManagement import newSecurityManager
38
from Products.ERP5Type.Utils import convertToUpperCase
Nicolas Delaby's avatar
Nicolas Delaby committed
39 40
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase,\
                                                       _getConversionServerDict
41
from Products.ERP5Type.tests.Sequence import SequenceList
Nicolas Delaby's avatar
Nicolas Delaby committed
42
from Products.ERP5Type.tests.utils import FileUpload, createZODBPythonScript
43
from Products.ERP5OOo.Document.OOoDocument import ConversionError
Nicolas Delaby's avatar
Nicolas Delaby committed
44
from Products.ERP5OOo.OOoUtils import OOoBuilder
45
from zLOG import LOG, INFO, ERROR
46
from Products.CMFCore.utils import getToolByName
47
from zExceptions import BadRequest
48
from Products.ERP5Type.tests.backportUnittest import expectedFailure
49 50 51 52
import urllib
import urllib2
import httplib
import urlparse
53

54
# test files' home
55
TEST_FILES_HOME = os.path.join(os.path.dirname(__file__), 'test_document')
Nicolas Delaby's avatar
Nicolas Delaby committed
56
FILENAME_REGULAR_EXPRESSION = "(?P<reference>[A-Z&é@{]{3,7})-(?P<language>[a-z]{2})-(?P<version>[0-9]{3})"
57
REFERENCE_REGULAR_EXPRESSION = "(?P<reference>[A-Z&é@{]{3,7})(-(?P<language>[a-z]{2}))?(-(?P<version>[0-9]{3}))?"
58

59 60

def makeFilePath(name):
61
  return os.path.join(TEST_FILES_HOME, name)
62

63 64 65
def makeFileUpload(name, as_name=None):
  if as_name is None:
    as_name = name
66
  path = makeFilePath(name)
67
  return FileUpload(path, as_name)
68 69 70 71 72 73 74 75 76 77 78 79 80 81

class TestIngestion(ERP5TypeTestCase):
  """
    ERP5 Document Management System - test file ingestion mechanism
  """

  ##################################
  ##  ZopeTestCase Skeleton
  ##################################

  def getTitle(self):
    """
      Return the title of the current test set.
    """
82
    return "ERP5 DMS - Ingestion"
83 84 85 86 87

  def getBusinessTemplateList(self):
    """
      Return the list of required business templates.
    """
88
    return ('erp5_core_proxy_field_legacy', 'erp5_base',
89
            'erp5_ingestion', 'erp5_ingestion_mysql_innodb_catalog',
90
            'erp5_web', 'erp5_crm', 'erp5_dms')
91

Nicolas Delaby's avatar
Nicolas Delaby committed
92
  def afterSetUp(self):
93 94 95 96
    """
      Initialize the ERP5 site.
    """
    self.login()
97 98
    self.datetime = DateTime()
    self.portal = self.getPortal()
99
    self.portal_categories = self.getCategoryTool()
100 101 102
    self.portal_catalog = self.getCatalogTool()
    self.createDefaultCategoryList()
    self.setSystemPreference()
103
    self.setSimulatedNotificationScript()
104

105
  def beforeTearDown(self):
Nicolas Delaby's avatar
Nicolas Delaby committed
106 107 108 109 110 111 112 113 114 115
    # cleanup modules
    module_id_list = """web_page_module
    document_module
    image_module
    external_source_module
    """.split()
    for module_id in module_id_list:
      module = self.portal[module_id]
      module.manage_delObjects([id for id in module.objectIds()])
    self.tic()
116 117 118 119 120 121 122
    activity_tool = self.portal.portal_activities
    activity_status = set(m.processing_node < -1
                          for m in activity_tool.getMessageList())
    if True in activity_status:
      activity_tool.manageClearActivities()
    else:
      assert not activity_status
123
    self.portal.portal_caches.clearAllCache()
Nicolas Delaby's avatar
Nicolas Delaby committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    # Cleanup portal_skins
    script_id_list = ('Document_getPropertyDictFromContent',
                      'Document_getPropertyDictFromInput',
                      'Document_getPropertyDictFromFilename',
                      'Document_getPropertyDictFromUserLogin',
                      'Document_finishIngestion',
                      'Document_getPreferredDocumentMetadataDiscoveryOrderList',
                      'Text_getPropertyDictFromContent',
                      'Text_getPropertyDictFromInput',
                      'Text_getPropertyDictFromFilename',
                      'Text_getPropertyDictFromUserLogin',
                      'Text_finishIngestion',
                      'Text_getPreferredDocumentMetadataDiscoveryOrderList',)
    skin_tool = self.portal.portal_skins
    for script_id in script_id_list:
      if script_id in skin_tool.custom.objectIds():
        skin_tool.custom._delObject(script_id)
141
    self.commit()
142

143
  def setSystemPreference(self):
144
    default_pref = self.portal.portal_preferences.default_site_preference
Jérome Perrin's avatar
Jérome Perrin committed
145 146 147
    conversion_dict = _getConversionServerDict()
    default_pref.setPreferredOoodocServerAddress(conversion_dict['hostname'])
    default_pref.setPreferredOoodocServerPortNumber(conversion_dict['port'])
Nicolas Delaby's avatar
Nicolas Delaby committed
148
    default_pref.setPreferredDocumentFilenameRegularExpression(FILENAME_REGULAR_EXPRESSION)
149
    default_pref.setPreferredDocumentReferenceRegularExpression(REFERENCE_REGULAR_EXPRESSION)
150 151
    if default_pref.getPreferenceState() != 'global':
      default_pref.enable()
152

153 154 155 156 157 158 159
  def setSimulatedNotificationScript(self, sequence=None, sequence_list=None, **kw):
    """
      Create simulated (empty) email notification script
    """
    context = self.portal.portal_skins.custom
    script_id = 'Document_notifyByEmail'
    if not hasattr(context, script_id):
Nicolas Delaby's avatar
Nicolas Delaby committed
160 161 162

      createZODBPythonScript(context, script_id,
                            'email_to, event, doc, **kw', 'return')
163

164
  def createDefaultCategoryList(self):
165
    """
166 167 168 169 170 171
      Create some categories for testing. DMS security
      is based on group, site, function, publication_section
      and projects.

      NOTE (XXX): some parts of this method could be either
      moved to Category Tool or to ERP5 Test Case.
172 173 174 175 176 177
    """
    self.category_list = [
                         # Role categories
                          {'path' : 'role/internal'
                           ,'title': 'Internal'
                           }
178 179 180 181 182 183 184 185 186
                          ,{'path' : 'function/musician/wind/saxophone'
                           ,'title': 'Saxophone'
                           }
                          ,{'path' : 'group/medium'
                           ,'title': 'Medium'
                           }
                          ,{'path' : 'site/arctic/spitsbergen'
                           ,'title': 'Spitsbergen'
                           }
187 188 189
                          ,{'path' : 'group/anybody'
                           ,'title': 'Anybody'
                           }
190 191 192 193 194 195
                          ,{'path' : 'publication_section/cop'
                           ,'title': 'COPs'
                           }
                          ,{'path' : 'publication_section/cop/one'
                           ,'title': 'COP one'
                           }
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
                         ]

    # Create categories
    # Note : this code was taken from the CategoryTool_importCategoryFile python
    #        script (packaged in erp5_core).
    for category in self.category_list:
      keys = category.keys()
      if 'path' in keys:
        base_path_obj = self.portal_categories
        is_base_category = True
        for category_id in category['path'].split('/'):
          # The current category is not existing
          if category_id not in base_path_obj.contentIds():
            # Create the category
            if is_base_category:
              category_type = 'Base Category'
            else:
              category_type = 'Category'
            base_path_obj.newContent( portal_type       = category_type
                                    , id                = category_id
                                    )
          base_path_obj = base_path_obj[category_id]
          is_base_category = False
        new_category = base_path_obj

        # Set the category properties
        for key in keys:
          if key != 'path':
            method_id = "set" + convertToUpperCase(key)
            value = category[key]
            if value not in ('', None):
              if hasattr(new_category, method_id):
                method = getattr(new_category, method_id)
                method(value.encode('UTF-8'))
230
    self.tic()
231 232 233 234 235 236

  def getCategoryList(self, base_category=None):
    """
      Get a list of categories with same base categories.
    """
    categories = []
237
    if base_category is not None:
238 239 240 241 242
      for category in self.category_list:
        if category["path"].split('/')[0] == base_category:
          categories.append(category)
    return categories

Nicolas Delaby's avatar
Nicolas Delaby committed
243
  def newEmptyDocument(self, portal_type):
244
    """
245 246 247
      Create an empty document of given portal type
      and given ID. 

248
    """
249
    document_module = self.portal.getDefaultModule(portal_type)
Nicolas Delaby's avatar
Nicolas Delaby committed
250
    return document_module.newContent(portal_type=portal_type)
251

Nicolas Delaby's avatar
Nicolas Delaby committed
252
  def ingestFormatList(self, document, format_list):
253
    """
254 255 256 257 258 259 260 261 262
      Upload in document document_id all test files which match
      any of the formats in format_list.

      portal_type can be specified to force the use of
      the default module for a given portal type instead
      of the document module.

      For every file, this checks is the word "magic"
      is present in both SearchableText and asText.
263
    """
264
    for revision, format in enumerate(format_list):
Ivan Tyagov's avatar
Ivan Tyagov committed
265
      filename = 'TEST-en-002.%s' %format
266
      f = makeFileUpload(filename)
Ivan Tyagov's avatar
Ivan Tyagov committed
267
      document.edit(file=f)
268
      self.tic()
Ivan Tyagov's avatar
Ivan Tyagov committed
269
      self.failUnless(document.hasFile())
270 271 272
      if document.isSupportBaseDataConversion():
        # this is how we know if it was ok or not
        self.assertEquals(document.getExternalProcessingState(), 'converted')
Ivan Tyagov's avatar
Ivan Tyagov committed
273 274
        self.assert_('magic' in document.SearchableText())
        self.assert_('magic' in str(document.asText()))
275 276 277
      else:
        # check if SearchableText() does not raise any exception
        document.SearchableText()
278

Nicolas Delaby's avatar
Nicolas Delaby committed
279
  def checkDocumentExportList(self, document, format, asserted_target_list):
280
    """
281 282 283
      Upload document ID document_id with
      a test file of given format and assert that the document
      can be converted to any of the formats in asserted_target_list
284 285 286
    """
    filename = 'TEST-en-002.' + format
    f = makeFileUpload(filename)
Ivan Tyagov's avatar
Ivan Tyagov committed
287
    document.edit(file=f)
288
    self.tic()
289 290
    # We call clear cache to be sure that the target list is updated
    self.getPortal().portal_caches.clearCache()
Ivan Tyagov's avatar
Ivan Tyagov committed
291
    target_list = document.getTargetFormatList()
292
    for target in asserted_target_list:
Nicolas Delaby's avatar
Nicolas Delaby committed
293 294
      self.assertTrue(target in target_list, 'target:%r not in %r' % (target,
                                                                 target_list,))
295

Bartek Górny's avatar
Bartek Górny committed
296
  def contributeFileList(self, with_portal_type=False):
297
    """
298 299 300
      Tries to a create new content through portal_contributions
      for every possible file type. If with_portal_type is set
      to true, portal_type is specified when calling newContent
301 302
      on portal_contributions.
      http://framework.openoffice.org/documentation/mimetypes/mimetypes.html
303
    """
304 305 306 307
    created_documents = []
    extension_to_type = (('ppt', 'Presentation')
                        ,('doc', 'Text')
                        ,('sdc', 'Spreadsheet')
308
                        ,('sxc', 'Spreadsheet')
309 310 311 312
                        ,('pdf', 'PDF')
                        ,('jpg', 'Image')
                        ,('py', 'File')
                        )
313 314
    counter = 1
    old_portal_type = ''
315
    for extension, portal_type in extension_to_type:
Ivan Tyagov's avatar
Ivan Tyagov committed
316
      filename = 'TEST-en-002.%s' %extension
317
      file = makeFileUpload(filename)
318 319 320 321 322 323
      # if we change portal type we must change version because 
      # mergeRevision would fail
      if portal_type != old_portal_type:
        counter += 1
        old_portal_type = portal_type
      file.filename = 'TEST-en-00%d.%s' % (counter, extension)
324
      if with_portal_type:
Ivan Tyagov's avatar
Ivan Tyagov committed
325
        document = self.portal.portal_contributions.newContent(portal_type=portal_type, file=file)
326
      else:
Ivan Tyagov's avatar
Ivan Tyagov committed
327 328
        document = self.portal.portal_contributions.newContent(file=file)
      created_documents.append(document)
329
    self.tic()
330 331 332
    # inspect created objects
    count = 0
    for extension, portal_type in extension_to_type:
Ivan Tyagov's avatar
Ivan Tyagov committed
333
      document = created_documents[count]
334
      count+=1
Ivan Tyagov's avatar
Ivan Tyagov committed
335 336
      self.assertEquals(document.getPortalType(), portal_type)
      self.assertEquals(document.getReference(), 'TEST')
337
      if document.isSupportBaseDataConversion():
338 339
        # We check if conversion has succeeded by looking
        # at the external_processing workflow
Ivan Tyagov's avatar
Ivan Tyagov committed
340 341
        self.assertEquals(document.getExternalProcessingState(), 'converted')
        self.assert_('magic' in document.SearchableText())
342

Nicolas Delaby's avatar
Nicolas Delaby committed
343
  def newPythonScript(self, script_id, argument_list, code):
344 345 346 347
    """
      Creates a new python script with given argument_list
      and source code.
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
348 349 350 351
    context = self.portal.portal_skins.custom
    if context._getOb(script_id, None) is not None:
      context._delObject(script_id)
    createZODBPythonScript(context, script_id, argument_list, code)
352

Nicolas Delaby's avatar
Nicolas Delaby committed
353
  def setDiscoveryOrder(self, order):
354
    """
355 356
      Creates a script to define the metadata discovery order
      for Text documents.
357 358
    """
    script_code = "return %s" % str(order)
Nicolas Delaby's avatar
Nicolas Delaby committed
359 360 361 362
    self.newPythonScript('Text_getPreferredDocumentMetadataDiscoveryOrderList',
                         '', script_code)

  def discoverMetadata(self, document):
363 364 365 366
    """
      Sets input parameters and on the document ID document_id
      and discover metadata. For reindexing
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
367 368 369 370 371 372 373 374 375
    input_parameter_dict = dict(reference='INPUT', 
                                language='in',
                                version='004', 
                                short_title='from_input',
                                contributor='person_module/james')
    # pass to discovery filename and user_login
    document.discoverMetadata(filename=document.getFilename(),
                              user_login='john_doe',
                              input_parameter_dict=input_parameter_dict)
376
    self.tic()
Nicolas Delaby's avatar
Nicolas Delaby committed
377 378

  def checkMetadataOrder(self, document, expected_metadata):
379 380 381 382 383
    """
    Asserts that metadata of document ID document_id
    is the same as expected_metadata
    """
    for k, v in expected_metadata.items():
Ivan Tyagov's avatar
Ivan Tyagov committed
384
      self.assertEquals(document.getProperty(k), v)
385

386 387 388
  def receiveEmail(self, data,
                   portal_type='Document Ingestion Message',
                   container_path='document_ingestion_module',
Nicolas Delaby's avatar
Nicolas Delaby committed
389
                   filename='email.emx'):
390 391 392
    return self.portal.portal_contributions.newContent(data=data,
                                                       portal_type=portal_type,
                                                       container_path=container_path,
Nicolas Delaby's avatar
Nicolas Delaby committed
393
                                                       filename=filename)
394

395 396 397 398 399
  ##################################
  ##  Basic steps
  ##################################
  def stepCreatePerson(self, sequence=None, sequence_list=None, **kw):
    """
400
      Create a person with ID "john" if it does not exists already
401 402
    """
    portal_type = 'Person'
403
    person_id = 'john'
404
    reference = 'john_doe'
405
    person_module = self.portal.person_module
406 407 408 409 410 411
    if getattr(person_module, person_id, None) is not None:
      return
    person = person_module.newContent(portal_type='Person',
                                      id=person_id,
                                      reference=reference,
                                      first_name='John',
Ivan Tyagov's avatar
Ivan Tyagov committed
412 413
                                      last_name='Doe',
                                      default_email_text='john@doe.com')
414
    self.tic()
415 416 417

  def stepCreateTextDocument(self, sequence=None, sequence_list=None, **kw):
    """
418 419
      Create an empty Text document with ID 'one'
      This document will be used in most tests.
420
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
421 422
    document = self.newEmptyDocument('Text')
    sequence.edit(document_path=document.getPath())
423

424 425
  def stepCreateSpreadsheetDocument(self, sequence=None, sequence_list=None, **kw):
    """
426 427
      Create an empty Spreadsheet document with ID 'two'
      This document will be used in most tests.
428
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
429 430
    document = self.newEmptyDocument('Spreadsheet')
    sequence.edit(document_path=document.getPath())
431 432 433

  def stepCreatePresentationDocument(self, sequence=None, sequence_list=None, **kw):
    """
434 435
      Create an empty Presentation document with ID 'three'
      This document will be used in most tests.
436
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
437 438
    document = self.newEmptyDocument('Presentation')
    sequence.edit(document_path=document.getPath())
439 440 441

  def stepCreateDrawingDocument(self, sequence=None, sequence_list=None, **kw):
    """
442 443
      Create an empty Drawing document with ID 'four'
      This document will be used in most tests.
444
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
445 446
    document = self.newEmptyDocument('Presentation')
    sequence.edit(document_path=document.getPath())
447

448 449
  def stepCreatePDFDocument(self, sequence=None, sequence_list=None, **kw):
    """
450 451
      Create an empty PDF document with ID 'five'
      This document will be used in most tests.
452
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
453 454
    document = self.newEmptyDocument('PDF')
    sequence.edit(document_path=document.getPath())
455 456 457

  def stepCreateImageDocument(self, sequence=None, sequence_list=None, **kw):
    """
458 459
      Create an empty Image document with ID 'six'
      This document will be used in most tests.
460
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
461 462
    document = self.newEmptyDocument('Image')
    sequence.edit(document_path=document.getPath())
463

464 465 466 467 468
  def stepCreateFileDocument(self, sequence=None, sequence_list=None, **kw):
    """
      Create an empty File document with ID 'file'
      This document will be used in most tests.
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
469 470
    document = self.newEmptyDocument('File')
    sequence.edit(document_path=document.getPath())
471

472 473
  def stepCheckEmptyState(self, sequence=None, sequence_list=None, **kw):
    """
474 475
      Check if the document is in "empty" processing state
      (ie. no file upload has been done yet)
476
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
477
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
Ivan Tyagov's avatar
Ivan Tyagov committed
478
    return self.assertEquals(document.getExternalProcessingState(), 'empty')
479 480 481

  def stepCheckUploadedState(self, sequence=None, sequence_list=None, **kw):
    """
482 483
      Check if the document is in "uploaded" processing state
      (ie. a file upload has been done)
484
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
485
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
Ivan Tyagov's avatar
Ivan Tyagov committed
486
    return self.assertEquals(document.getExternalProcessingState(), 'uploaded')
487

488 489 490 491 492
  def stepCheckConvertingState(self, sequence=None, sequence_list=None, **kw):
    """
      Check if the document is in "converting" processing state
      (ie. a file upload has been done and the document is converting)
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
493
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
Ivan Tyagov's avatar
Ivan Tyagov committed
494
    return self.assertEquals(document.getExternalProcessingState(), 'converting')
495

496 497
  def stepCheckConvertedState(self, sequence=None, sequence_list=None, **kw):
    """
498
      Check if the document is in "converted" processing state
499
      (ie. a file conversion has been done and the document has
500
      been converted)
501
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
502
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
Ivan Tyagov's avatar
Ivan Tyagov committed
503
    return self.assertEquals(document.getExternalProcessingState(), 'converted')
504

505 506 507
  def stepStraightUpload(self, sequence=None, sequence_list=None, **kw):
    """
      Upload a file directly from the form
Nicolas Delaby's avatar
Nicolas Delaby committed
508
      check if it has the data and filename
509
    """
510
    filename = 'TEST-en-002.doc'
Nicolas Delaby's avatar
Nicolas Delaby committed
511
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
Julien Muchembled's avatar
Julien Muchembled committed
512 513
    # First revision is 1 (like web pages)
    self.assertEquals(document.getRevision(), '1')
514
    f = makeFileUpload(filename)
515 516
    document.edit(file=f)
    self.assert_(document.hasFile())
Nicolas Delaby's avatar
Nicolas Delaby committed
517
    self.assertEquals(document.getFilename(), filename) 
518
    # Revision is 1 after upload (revisions are strings)
Julien Muchembled's avatar
Julien Muchembled committed
519
    self.assertEquals(document.getRevision(), '2')
520
    document.reindexObject()
521
    self.commit()
Ivan Tyagov's avatar
Ivan Tyagov committed
522
    
523
  def stepUploadFromViewForm(self, sequence=None, sequence_list=None, **kw):
524
    """
525
      Upload a file from view form and make sure this increases the revision
526
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
527
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
528
    f = makeFileUpload('TEST-en-002.doc')
Ivan Tyagov's avatar
Ivan Tyagov committed
529 530 531 532
    revision = document.getRevision()
    document.edit(file=f)
    self.assertEquals(document.getRevision(), str(int(revision) + 1))
    document.reindexObject()
533
    self.commit()
Ivan Tyagov's avatar
Ivan Tyagov committed
534
    
535 536 537 538 539
  def stepUploadTextFromContributionTool(self, sequence=None, sequence_list=None, **kw):
    """
      Upload a file from contribution.
    """
    f = makeFileUpload('TEST-en-002.doc')
Nicolas Delaby's avatar
Nicolas Delaby committed
540 541
    document = self.portal.portal_contributions.newContent(file=f)
    sequence.edit(document_path=document.getPath())
542
    self.commit()
543 544 545 546 547 548

  def stepReuploadTextFromContributionTool(self, sequence=None, sequence_list=None, **kw):
    """
      Upload a file from contribution form and make sure this update existing
      document and don't make a new document.
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
549
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
Ivan Tyagov's avatar
Ivan Tyagov committed
550
    revision = document.getRevision()
551
    number_of_document = len(self.portal.document_module.objectIds())
Ivan Tyagov's avatar
Ivan Tyagov committed
552
    self.assert_('This document is modified.' not in document.asText())
553 554 555 556 557

    f = makeFileUpload('TEST-en-002-modified.doc')
    f.filename = 'TEST-en-002.doc'

    self.portal.portal_contributions.newContent(file=f)
558
    self.tic()
Ivan Tyagov's avatar
Ivan Tyagov committed
559 560
    self.assertEquals(document.getRevision(), str(int(revision) + 1))
    self.assert_('This document is modified.' in document.asText())
561 562
    self.assertEquals(len(self.portal.document_module.objectIds()),
                      number_of_document)
Ivan Tyagov's avatar
Ivan Tyagov committed
563
    document.reindexObject()
564
    self.commit()
565 566 567 568 569 570

  def stepUploadAnotherTextFromContributionTool(self, sequence=None, sequence_list=None, **kw):
    """
      Upload another file from contribution.
    """
    f = makeFileUpload('ANOTHE-en-001.doc')
Nicolas Delaby's avatar
Nicolas Delaby committed
571 572
    document = self.portal.portal_contributions.newContent(id='two', file=f)
    sequence.edit(document_path=document.getPath())
573
    self.tic()
Nicolas Delaby's avatar
Nicolas Delaby committed
574
    self.assertTrue('This is a another very interesting document.' in document.asText())
Ivan Tyagov's avatar
Ivan Tyagov committed
575 576 577
    self.assertEquals(document.getReference(), 'ANOTHE')
    self.assertEquals(document.getVersion(), '001')
    self.assertEquals(document.getLanguage(), 'en')
578 579 580

  def stepDiscoverFromFilename(self, sequence=None, sequence_list=None, **kw):
    """
581 582 583
      Upload a file using contribution tool. This should trigger metadata
      discovery and we should have basic coordinates immediately,
      from first stage.
584
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
585 586
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
    filename = 'TEST-en-002.doc'
587
    # First make sure the regular expressions work
Nicolas Delaby's avatar
Nicolas Delaby committed
588
    property_dict = document.getPropertyDictFromFilename(filename)
589 590 591 592 593
    self.assertEquals(property_dict['reference'], 'TEST')
    self.assertEquals(property_dict['language'], 'en')
    self.assertEquals(property_dict['version'], '002')
    # Then make sure content discover works
    # XXX - This part must be extended
Ivan Tyagov's avatar
Ivan Tyagov committed
594
    property_dict = document.getPropertyDictFromContent()
595 596 597 598
    self.assertEquals(property_dict['title'], 'title')
    self.assertEquals(property_dict['description'], 'comments')
    self.assertEquals(property_dict['subject_list'], ['keywords'])
    # Then make sure metadata discovery works
Nicolas Delaby's avatar
Nicolas Delaby committed
599
    f = makeFileUpload(filename)
Ivan Tyagov's avatar
Ivan Tyagov committed
600 601 602 603
    document.edit(file=f)
    self.assertEquals(document.getReference(), 'TEST')
    self.assertEquals(document.getLanguage(), 'en')
    self.assertEquals(document.getVersion(), '002')
Nicolas Delaby's avatar
Nicolas Delaby committed
604
    self.assertEquals(document.getFilename(), filename)
605

606 607
  def stepCheckConvertedContent(self, sequence=None, sequence_list=None, **kw):
    """
608 609 610
      Check that the input file was successfully converted
      and that its SearchableText and asText contain
      the word "magic"
611 612
    """
    self.tic()
Nicolas Delaby's avatar
Nicolas Delaby committed
613
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
Ivan Tyagov's avatar
Ivan Tyagov committed
614 615 616
    self.assert_(document.hasBaseData())
    self.assert_('magic' in document.SearchableText())
    self.assert_('magic' in str(document.asText()))
617

618
  def stepSetSimulatedDiscoveryScript(self, sequence=None, sequence_list=None, **kw):
619 620 621 622
    """
      Create Text_getPropertyDictFrom[source] scripts
      to simulate custom site's configuration
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
623
    self.newPythonScript('Text_getPropertyDictFromUserLogin',
624
                         'user_name=None', "return {'contributor':'person_module/john'}")
Nicolas Delaby's avatar
Nicolas Delaby committed
625
    self.newPythonScript('Text_getPropertyDictFromContent', '',
626
                         "return {'short_title':'short', 'title':'title', 'contributor':'person_module/john',}")
627 628 629 630 631 632 633

  def stepTestMetadataSetting(self, sequence=None, sequence_list=None, **kw):
    """
      Upload with custom getPropertyDict methods
      check that all metadata are correct
    """
    f = makeFileUpload('TEST-en-002.doc')
Nicolas Delaby's avatar
Nicolas Delaby committed
634
    document = self.portal.portal_contributions.newContent(file=f)
635
    self.tic()
636
    # Then make sure content discover works
Ivan Tyagov's avatar
Ivan Tyagov committed
637
    property_dict = document.getPropertyDictFromUserLogin()
638
    self.assertEquals(property_dict['contributor'], 'person_module/john')
639
    # reference from filename (the rest was checked some other place)
Ivan Tyagov's avatar
Ivan Tyagov committed
640
    self.assertEquals(document.getReference(), 'TEST')
641
    # short_title from content
Ivan Tyagov's avatar
Ivan Tyagov committed
642
    self.assertEquals(document.getShortTitle(), 'short')
643
    # title from metadata inside the document
Ivan Tyagov's avatar
Ivan Tyagov committed
644
    self.assertEquals(document.getTitle(),  'title')
645
    # contributors from user
Ivan Tyagov's avatar
Ivan Tyagov committed
646
    self.assertEquals(document.getContributor(), 'person_module/john')
647 648 649

  def stepEditMetadata(self, sequence=None, sequence_list=None, **kw):
    """
650
      we change metadata in a document which has ODF
651
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
652
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
653 654 655
    kw = dict(title='another title',
              subject='another subject',
              description='another description')
Ivan Tyagov's avatar
Ivan Tyagov committed
656
    document.edit(**kw)
657
    self.tic()
658 659 660 661 662 663 664 665

  def stepCheckChangedMetadata(self, sequence=None, sequence_list=None, **kw):
    """
      then we download it and check if it is changed
    """
    # XXX actually this is an example of how it should be
    # implemented in OOoDocument class - we don't really
    # need oood for getting/setting metadata...
Nicolas Delaby's avatar
Nicolas Delaby committed
666
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
Ivan Tyagov's avatar
Ivan Tyagov committed
667
    newcontent = document.getBaseData()
Nicolas Delaby's avatar
Nicolas Delaby committed
668 669 670 671 672
    builder = OOoBuilder(newcontent)
    xml_tree = etree.fromstring(builder.extract('meta.xml'))
    title = xml_tree.find('*/{%s}title' % xml_tree.nsmap['dc']).text
    self.assertEquals(title, 'another title')
    subject = xml_tree.find('*/{%s}keyword' % xml_tree.nsmap['meta']).text
673
    self.assertEquals(subject, u'another subject')
Nicolas Delaby's avatar
Nicolas Delaby committed
674
    description = xml_tree.find('*/{%s}description' % xml_tree.nsmap['dc']).text
675
    self.assertEquals(description, u'another description')
Nicolas Delaby's avatar
Nicolas Delaby committed
676

677 678 679 680 681
  def stepIngestTextFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported text formats
      make sure they are converted
    """
682
    format_list = ['rtf', 'doc', 'txt', 'sxw', 'sdw']
Nicolas Delaby's avatar
Nicolas Delaby committed
683 684
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
    self.ingestFormatList(document, format_list)
685

Nicolas Delaby's avatar
Nicolas Delaby committed
686 687
  def stepIngestSpreadsheetFormats(self, sequence=None, sequence_list=None,
                                   **kw):
688 689 690 691
    """
      ingest all supported spreadsheet formats
      make sure they are converted
    """
692
    format_list = ['xls', 'sxc', 'sdc']
Nicolas Delaby's avatar
Nicolas Delaby committed
693 694
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
    self.ingestFormatList(document, format_list)
695

Nicolas Delaby's avatar
Nicolas Delaby committed
696 697
  def stepIngestPresentationFormats(self, sequence=None, sequence_list=None,
                                    **kw):
698 699 700 701
    """
      ingest all supported presentation formats
      make sure they are converted
    """
702
    format_list = ['ppt', 'sxi', 'sdd']
Nicolas Delaby's avatar
Nicolas Delaby committed
703 704
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
    self.ingestFormatList(document, format_list)
705

706 707 708 709 710
  def stepIngestPDFFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported PDF formats
      make sure they are converted
    """
711
    format_list = ['pdf']
Nicolas Delaby's avatar
Nicolas Delaby committed
712 713
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
    self.ingestFormatList(document, format_list)
714

715 716 717 718 719
  def stepIngestDrawingFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported presentation formats
      make sure they are converted
    """
720
    format_list = ['sxd',]
Nicolas Delaby's avatar
Nicolas Delaby committed
721 722
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
    self.ingestFormatList(document, format_list)
723

724
  def stepIngestPDFFormats(self, sequence=None, sequence_list=None, **kw):
725
    """
726 727
      ingest all supported pdf formats
      make sure they are converted
728
    """
729
    format_list = ['pdf']
Nicolas Delaby's avatar
Nicolas Delaby committed
730 731
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
    self.ingestFormatList(document, format_list)
732 733 734 735 736

  def stepIngestImageFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported image formats
    """
737
    format_list = ['jpg', 'gif', 'bmp', 'png']
Nicolas Delaby's avatar
Nicolas Delaby committed
738 739
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
    self.ingestFormatList(document, format_list)
740

741 742 743 744 745
  def stepIngestFileFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported file formats
    """
    format_list = ['txt', 'rss', 'xml',]
Nicolas Delaby's avatar
Nicolas Delaby committed
746 747 748 749 750 751 752
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
    self.ingestFormatList(document, format_list)

  def stepCheckTextDocumentExportList(self, sequence=None, sequence_list=None,
                                      **kw):
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
    self.checkDocumentExportList(document, 'doc',
753 754 755 756
                                 ['pdf', 'doc', 'rtf', 'txt', 'odt'])
    # legacy format will be replaced
    expectedFailure(self.checkDocumentExportList)(document, 'doc',
                                                 ['writer.html'])
Nicolas Delaby's avatar
Nicolas Delaby committed
757 758 759 760

  def stepCheckSpreadsheetDocumentExportList(self, sequence=None,
                                             sequence_list=None, **kw):
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
761 762 763 764
    self.checkDocumentExportList(document, 'xls', ['csv', 'xls', 'ods', 'pdf'])
    # legacy format will be replaced
    expectedFailure(self.checkDocumentExportList)(document, 'xls',
                                 ['calc.html', 'calc.pdf'])
Nicolas Delaby's avatar
Nicolas Delaby committed
765 766 767 768

  def stepCheckPresentationDocumentExportList(self, sequence=None,
                                              sequence_list=None, **kw):
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
769 770 771 772
    self.checkDocumentExportList(document, 'ppt', ['ppt', 'odp', 'pdf'])
    # legacy format will be replaced
    expectedFailure(self.checkDocumentExportList)(document,
                                                 'ppt', ['impr.pdf'])
Nicolas Delaby's avatar
Nicolas Delaby committed
773 774 775 776

  def stepCheckDrawingDocumentExportList(self, sequence=None,
                                         sequence_list=None, **kw):
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
777 778 779 780
    self.checkDocumentExportList(document, 'sxd', ['jpg', 'svg', 'pdf', 'odg'])
    # legacy format will be replaced
    expectedFailure(self.checkDocumentExportList)(document,
                                                 'sxd', ['draw.pdf'])
781

782
  def stepExportPDF(self, sequence=None, sequence_list=None, **kw):
783
    """
784
      Try to export PDF to text and HTML
785
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
786
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
787
    f = makeFileUpload('TEST-en-002.pdf')
788
    document.edit(file=f)
789 790 791 792 793 794
    mime, text = document.convert('text')
    self.failUnless('magic' in text)
    self.failUnless(mime == 'text/plain')
    mime, html = document.convert('html')
    self.failUnless('magic' in html)
    self.failUnless(mime == 'text/html')
795 796

  def stepExportImage(self, sequence=None, sequence_list=None, **kw):
797
    """
798
      Check we are able to resize images
799
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
800
    image = self.portal.restrictedTraverse(sequence.get('document_path'))
801 802
    f = makeFileUpload('TEST-en-002.jpg')
    image.edit(file=f)
803
    self.tic()
804 805 806 807 808 809
    mime, data = image.convert(None)
    self.assertEquals(mime, 'image/jpeg')
    mime, small_data = image.convert(None, display='small')
    mime, large_data = image.convert(None, display='xlarge')
    # Check we are able to resize the image.
    self.assertTrue(len(small_data) < len(large_data))
810

811 812 813 814 815
  def stepCleanUp(self, sequence=None, sequence_list=None, **kw):
    """
        Clean up DMS system from old content.
    """
    portal = self.getPortal()
816
    for module in (portal.document_module, portal.image_module, portal.document_ingestion_module):
Nicolas Delaby's avatar
Nicolas Delaby committed
817
      module.manage_delObjects(list(module.objectIds()))
Nicolas Delaby's avatar
Nicolas Delaby committed
818

Bartek Górny's avatar
Bartek Górny committed
819
  def stepContributeFileListWithType(self, sequence=None, sequence_list=None, **kw):
820 821 822 823
    """
      Contribute all kinds of files giving portal type explicitly
      TODO: test situation whereby portal_type given explicitly is wrong
    """
Bartek Górny's avatar
Bartek Górny committed
824
    self.contributeFileList(with_portal_type=True)
825

Nicolas Delaby's avatar
Nicolas Delaby committed
826 827
  def stepContributeFileListWithNoType(self, sequence=None, sequence_list=None,
                                       **kw):
828 829 830 831
    """
      Contribute all kinds of files
      let the system figure out portal type by itself
    """
Bartek Górny's avatar
Bartek Górny committed
832
    self.contributeFileList(with_portal_type=False)
833

Nicolas Delaby's avatar
Nicolas Delaby committed
834 835
  def stepSetSimulatedDiscoveryScriptForOrdering(self, sequence=None,
                                                 sequence_list=None, **kw):
836 837 838 839 840 841 842 843 844 845
    """
      set scripts which are supposed to overwrite each other's metadata
      desing is the following:
                    File Name     User    Content        Input
      reference     TEST          USER    CONT           INPUT
      language      en            us                     in
      version       002                   003            004
      contributor                 john    jack           james
      short_title                         from_content   from_input
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
    input_dict = dict(reference='INPUT',
                 language='in',
                 version='004', 
                 short_title='from_input',
                 contributor='person_module/james')
    self.newPythonScript('Text_getPropertyDictFromInput',
                         'inputed_kw', "return %r" % (input_dict,))
    self.newPythonScript('Text_getPropertyDictFromUserLogin', 'user_name=None',
                         "return {'reference':'USER', 'language':'us',"\
                         " 'contributor':'person_module/john'}")
    self.newPythonScript('Text_getPropertyDictFromContent', '',
                         "return {'reference':'CONT', 'version':'003',"\
                         " 'contributor':'person_module/jack',"\
                         " 'short_title':'from_content'}")

  def stepCheckMetadataSettingOrderFICU(self, sequence=None,
                                        sequence_list=None, **kw):
863 864
    """
     This is the default
865
    """  
Nicolas Delaby's avatar
Nicolas Delaby committed
866 867 868 869 870 871 872
    expected_metadata = dict(reference='TEST', language='en', version='002',
                             short_title='from_input',
                             contributor='person_module/james')
    self.setDiscoveryOrder(['filename', 'input', 'content', 'user_login'])
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
    self.discoverMetadata(document)
    self.checkMetadataOrder(document, expected_metadata)
873

Nicolas Delaby's avatar
Nicolas Delaby committed
874 875
  def stepCheckMetadataSettingOrderCUFI(self, sequence=None,
                                        sequence_list=None, **kw):
876 877 878
    """
     Content - User - Filename - Input
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
879 880 881 882 883 884 885
    expected_metadata = dict(reference='CONT', language='us', version='003',
                             short_title='from_content',
                             contributor='person_module/jack')
    self.setDiscoveryOrder(['content', 'user_login', 'filename', 'input'])
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
    self.discoverMetadata(document)
    self.checkMetadataOrder(document, expected_metadata)
886

Nicolas Delaby's avatar
Nicolas Delaby committed
887 888
  def stepCheckMetadataSettingOrderUIFC(self, sequence=None,
                                        sequence_list=None, **kw):
889 890 891
    """
     User - Input - Filename - Content
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
892 893 894 895 896 897 898
    expected_metadata = dict(reference='USER', language='us', version='004',
                             short_title='from_input',
                             contributor='person_module/john')
    self.setDiscoveryOrder(['user_login', 'input', 'filename', 'content'])
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
    self.discoverMetadata(document)
    self.checkMetadataOrder(document, expected_metadata)
899

Nicolas Delaby's avatar
Nicolas Delaby committed
900 901
  def stepCheckMetadataSettingOrderICUF(self, sequence=None,
                                        sequence_list=None, **kw):
902 903 904
    """
     Input - Content - User - Filename
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
905 906 907 908 909 910 911
    expected_metadata = dict(reference='INPUT', language='in', version='004',
                             short_title='from_input',
                             contributor='person_module/james')
    self.setDiscoveryOrder(['input', 'content', 'user_login', 'filename'])
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
    self.discoverMetadata(document)
    self.checkMetadataOrder(document, expected_metadata)
912

Nicolas Delaby's avatar
Nicolas Delaby committed
913 914
  def stepCheckMetadataSettingOrderUFCI(self, sequence=None,
                                        sequence_list=None, **kw):
915 916 917
    """
     User - Filename - Content - Input
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
918 919 920 921 922 923 924
    expected_metadata = dict(reference='USER', language='us', version='002',
                             short_title='from_content',
                             contributor='person_module/john')
    self.setDiscoveryOrder(['user_login', 'filename', 'content', 'input'])
    document = self.portal.restrictedTraverse(sequence.get('document_path'))
    self.discoverMetadata(document)
    self.checkMetadataOrder(document, expected_metadata)
Ivan Tyagov's avatar
Ivan Tyagov committed
925 926
   
  def stepReceiveEmail(self, sequence=None, sequence_list=None, **kw):
927
    """
Ivan Tyagov's avatar
Ivan Tyagov committed
928
      Email was sent in by someone to ERP5.
929 930
    """
    f = open(makeFilePath('email_from.txt'))
931
    document = self.receiveEmail(f.read())
932
    self.tic()
933

Nicolas Delaby's avatar
Nicolas Delaby committed
934 935
  def stepReceiveMultipleAttachmentsEmail(self, sequence=None,
                                          sequence_list=None, **kw):
936 937 938 939 940
    """
      Email was sent in by someone to ERP5.
    """
    f = open(makeFilePath('email_multiple_attachments.eml'))
    document = self.receiveEmail(f.read())
941
    self.tic()
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957

  def stepVerifyEmailedMultipleDocumentsInitialContribution(self, sequence=None, sequence_list=None, **kw):
    """
      Verify contributed for initial time multiple document per email.
    """
    attachment_list, ingested_document = self.verifyEmailedMultipleDocuments()
    self.assertEquals('1', ingested_document.getRevision())
    
  def stepVerifyEmailedMultipleDocumentsMultipleContribution(self, sequence=None, sequence_list=None, **kw):
    """
      Verify contributed for initial time multiple document per email.
    """
    attachment_list, ingested_document = self.verifyEmailedMultipleDocuments()
    self.assertTrue(ingested_document.getRevision() > '1')

  def stepVerifyEmailedDocumentInitialContribution(self, sequence=None, sequence_list=None, **kw):
958
    """
959
      Verify contributed for initial time document per email.
960
    """
961
    attachment_list, ingested_document = self.verifyEmailedDocument()
962
    self.assertEquals('1', ingested_document.getRevision())
963

964
  def stepVerifyEmailedDocumentMultipleContribution(self, sequence=None, sequence_list=None, **kw):
965
    """
966
      Verify contributed for multiple times document per email.
967
    """
968
    attachment_list, ingested_document = self.verifyEmailedDocument()
969
    self.assertTrue(ingested_document.getRevision() > '1')
970

Nicolas Delaby's avatar
Nicolas Delaby committed
971
  def playSequence(self, step_list):
972 973 974
    sequence_list = SequenceList()
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
Nicolas Delaby's avatar
Nicolas Delaby committed
975
    sequence_list.play(self)
976

977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
  def verifyEmailedMultipleDocuments(self):
    """
      Basic checks for verifying a mailed-in multiple documents.
    """
    # First, check document ingestion message
    ingestion_message = self.portal_catalog.getResultValue(
                                 portal_type='Document Ingestion Message',
                                 title='Multiple Attachments',
                                 source_title='John Doe')
    self.assertTrue(ingestion_message is not None)
    # Second, check attachments to ingested message
    attachment_list = ingestion_message.getAggregateValueList()
    self.assertEqual(len(attachment_list), 5)
    extension_reference_portal_type_map = {'DOC': 'Text', 
                                           'JPG': 'Image',
                                           'ODT': 'Text', 
                                           'PDF': 'PDF',
                                           'PPT': 'Presentation'}
    for sub_reference, portal_type in extension_reference_portal_type_map.items():
      ingested_document = self.portal_catalog.getResultValue(
                               portal_type=portal_type,
                               reference='TEST%s' %sub_reference,
                               language='en',
                               version='002')
      self.assertNotEquals(None, ingested_document)
1002
      if ingested_document.isSupportBaseDataConversion():
1003 1004 1005 1006
        self.assertEquals('converted', ingested_document.getExternalProcessingState())
      # check aggregate between 'Document Ingestion Message' and ingested document
      self.assertTrue(ingested_document in attachment_list)
    return attachment_list, ingested_document
Nicolas Delaby's avatar
Nicolas Delaby committed
1007

1008
  def verifyEmailedDocument(self):
1009
    """
1010
      Basic checks for verifying a mailed-in document
1011 1012 1013 1014 1015 1016 1017
    """
    # First, check document ingestion message
    ingestion_message = self.portal_catalog.getResultValue(
                                 portal_type='Document Ingestion Message',
                                 title='A Test Mail',
                                 source_title='John Doe')
    self.assertTrue(ingestion_message is not None)
Nicolas Delaby's avatar
Nicolas Delaby committed
1018

1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
    # Second, check attachments to ingested message
    attachment_list = ingestion_message.getAggregateValueList()
    self.assertEqual(len(attachment_list), 1)

    # Third, check document is ingested properly
    ingested_document = self.portal_catalog.getResultValue(
                               portal_type='Text',
                               reference='MAIL',
                               language='en',
                               version='002')
Nicolas Delaby's avatar
Nicolas Delaby committed
1029
    self.assertEquals('MAIL-en-002.doc', ingested_document.getFilename())
1030 1031
    self.assertEquals('converted', ingested_document.getExternalProcessingState())
    self.assertTrue('magic' in ingested_document.asText())
Nicolas Delaby's avatar
Nicolas Delaby committed
1032

1033 1034 1035
    # check aggregate between 'Document Ingestion Message' and ingested document
    self.assertEquals(attachment_list[0], ingested_document)
    return attachment_list, ingested_document
Nicolas Delaby's avatar
Nicolas Delaby committed
1036

1037 1038 1039 1040
  ##################################
  ##  Tests
  ##################################

Nicolas Delaby's avatar
Nicolas Delaby committed
1041
  def test_01_PreferenceSetup(self):
1042 1043 1044 1045
    """
      Make sure that preferences are set up properly and accessible
    """
    preference_tool = self.portal.portal_preferences
Nicolas Delaby's avatar
Nicolas Delaby committed
1046 1047 1048
    conversion_dict = _getConversionServerDict()
    self.assertEquals(preference_tool.getPreferredOoodocServerAddress(), conversion_dict['hostname'])
    self.assertEquals(preference_tool.getPreferredOoodocServerPortNumber(), conversion_dict['port'])
Nicolas Delaby's avatar
Nicolas Delaby committed
1049
    self.assertEquals(preference_tool.getPreferredDocumentFilenameRegularExpression(), FILENAME_REGULAR_EXPRESSION)
1050
    self.assertEquals(preference_tool.getPreferredDocumentReferenceRegularExpression(), REFERENCE_REGULAR_EXPRESSION)
Nicolas Delaby's avatar
Nicolas Delaby committed
1051 1052

  def test_02_FileExtensionRegistry(self):
1053 1054 1055
    """
      check if we successfully imported registry
      and that it has all the entries we need
1056
    """
1057
    reg = self.portal.portal_contribution_registry
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
    correct_type_mapping = {
            'doc' : 'Text',
            'txt' : 'Text',
            'odt' : 'Text',
            'sxw' : 'Text',
            'rtf' : 'Text',
            'gif' : 'Image',
            'jpg' : 'Image',
            'png' : 'Image',
            'bmp' : 'Image',
            'pdf' : 'PDF',
            'xls' : 'Spreadsheet',
            'ods' : 'Spreadsheet',
            'sdc' : 'Spreadsheet',
            'ppt' : 'Presentation',
            'odp' : 'Presentation',
            'sxi' : 'Presentation',
1075
            'sxd' : 'Drawing',
1076 1077 1078
            'xxx' : 'File',
          }
    for type, portal_type in correct_type_mapping.items():
Nicolas Delaby's avatar
Nicolas Delaby committed
1079 1080
      filename = 'aaa.' + type
      self.assertEquals(reg.findPortalTypeName(filename=filename),
1081
                        portal_type)
1082

Nicolas Delaby's avatar
Nicolas Delaby committed
1083
  def test_03_TextDoc(self):
1084
    """
1085
      Test basic behaviour of a document:
1086
      - create empty document
1087 1088 1089 1090 1091
      - upload a file directly
      - upload a file using upload dialog
      - make sure revision was increased
      - check that it was properly converted
      - check if coordinates were extracted from file name
1092
    """
1093 1094
    step_list = ['stepCleanUp'
                 ,'stepCreateTextDocument'
1095
                 ,'stepCheckEmptyState'
1096
                 ,'stepStraightUpload'
1097 1098
                 ,'stepCheckConvertingState'
                 ,'stepTic'
1099
                 ,'stepCheckConvertedState'
1100 1101 1102
                 ,'stepUploadFromViewForm'
                 ,'stepCheckConvertingState'
                 ,'stepTic'
1103 1104
                 ,'stepCheckConvertedState'
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1105
    self.playSequence(step_list)
1106

Nicolas Delaby's avatar
Nicolas Delaby committed
1107
  def test_04_MetadataExtraction(self):
1108 1109
    """
      Test metadata extraction from various sources:
1110 1111 1112 1113 1114
      - from file name (doublecheck)
      - from user (by overwriting type-based method
                   and simulating the result)
      - from content (by overwriting type-based method
                      and simulating the result)
1115
      - from file metadata
1116 1117 1118 1119

      NOTE: metadata of document (title, subject, description)
      are no longer retrieved and set upon conversion
    """
1120
    step_list = [ 'stepCleanUp'
1121
                 ,'stepUploadTextFromContributionTool'
1122
                 ,'stepSetSimulatedDiscoveryScript'
1123
                 ,'stepTic'
1124 1125
                 ,'stepTestMetadataSetting'
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1126
    self.playSequence(step_list)
1127

Nicolas Delaby's avatar
Nicolas Delaby committed
1128
  def test_041_MetadataEditing(self):
1129 1130 1131 1132 1133
    """
      Check metadata in the object and in the ODF document
      Edit metadata on the object
      Download ODF, make sure it is changed
    """
1134 1135
    step_list = [ 'stepCleanUp'
                 ,'stepCreateTextDocument'
1136 1137 1138 1139
                 ,'stepUploadFromViewForm'
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
1140 1141
                 ,'stepEditMetadata'
                 ,'stepCheckChangedMetadata'
1142
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1143
    self.playSequence(step_list)
1144

1145 1146 1147 1148 1149 1150 1151 1152 1153
  #    Ingest various formats (xls, doc, sxi, ppt etc)
  #    Verify that they are successfully converted
  #    - have ODF data and contain magic word in SearchableText
  #    - or have text data and contain magic word in SearchableText
  #      TODO:
  #    - or were not moved in processing_status_workflow if the don't
  #      implement _convertToBase (e.g. Image)
  #    Verify that you can not upload file of the wrong format.

Nicolas Delaby's avatar
Nicolas Delaby committed
1154
  def test_05_FormatIngestionText(self):
1155 1156
    step_list = ['stepCleanUp'
                 ,'stepCreateTextDocument'
1157
                 ,'stepIngestTextFormats'
1158
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1159
    self.playSequence(step_list)
1160

Nicolas Delaby's avatar
Nicolas Delaby committed
1161
  def test_05_FormatIngestionSpreadSheet(self):
1162
    step_list = ['stepCleanUp'
1163 1164
                 ,'stepCreateSpreadsheetDocument'
                 ,'stepIngestSpreadsheetFormats'
1165
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1166
    self.playSequence(step_list)
1167

Nicolas Delaby's avatar
Nicolas Delaby committed
1168
  def test_05_FormatIngestionPresentation(self):
1169
    step_list = ['stepCleanUp'
1170 1171
                 ,'stepCreatePresentationDocument'
                 ,'stepIngestPresentationFormats'
1172
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1173
    self.playSequence(step_list)
1174

Nicolas Delaby's avatar
Nicolas Delaby committed
1175
  def test_05_FormatIngestionDrawing(self):
1176
    step_list = ['stepCleanUp'
1177 1178
                 ,'stepCreateDrawingDocument'
                 ,'stepIngestDrawingFormats'
1179
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1180
    self.playSequence(step_list)
1181

Nicolas Delaby's avatar
Nicolas Delaby committed
1182
  def test_05_FormatIngestionPDF(self):
1183
    step_list = ['stepCleanUp'
1184 1185
                 ,'stepCreatePDFDocument'
                 ,'stepIngestPDFFormats'
1186
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1187
    self.playSequence(step_list)
1188

Nicolas Delaby's avatar
Nicolas Delaby committed
1189
  def test_05_FormatIngestionImage(self):
1190
    step_list = ['stepCleanUp'
1191 1192
                 ,'stepCreateImageDocument'
                 ,'stepIngestImageFormats'
1193
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1194
    self.playSequence(step_list)
1195

Nicolas Delaby's avatar
Nicolas Delaby committed
1196
  def test_05_FormatIngestionFile(self):
1197 1198 1199 1200
    step_list = ['stepCleanUp'
                 ,'stepCreateFileDocument'
                 ,'stepIngestFileFormats'
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1201
    self.playSequence(step_list)
1202 1203 1204 1205 1206

  # Test generation of files in all possible formats
  # which means check if they have correct lists of available formats for export
  # actual generation is tested in oood tests
  # PDF and Image should be tested here
Nicolas Delaby's avatar
Nicolas Delaby committed
1207
  def test_06_FormatGenerationText(self):
1208 1209
    step_list = [ 'stepCleanUp'
                 ,'stepCreateTextDocument'
1210
                 ,'stepCheckTextDocumentExportList'
1211
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1212
    self.playSequence(step_list)
1213

Nicolas Delaby's avatar
Nicolas Delaby committed
1214
  def test_06_FormatGenerationSpreadsheet(self):
1215
    step_list = [ 'stepCleanUp'
1216 1217
                 ,'stepCreateSpreadsheetDocument'
                 ,'stepCheckSpreadsheetDocumentExportList'
1218
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1219
    self.playSequence(step_list)
1220

Nicolas Delaby's avatar
Nicolas Delaby committed
1221
  def test_06_FormatGenerationPresentation(self):
1222
    step_list = [ 'stepCleanUp'
1223 1224
                 ,'stepCreatePresentationDocument'
                 ,'stepCheckPresentationDocumentExportList'
1225
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1226
    self.playSequence(step_list)
1227

Nicolas Delaby's avatar
Nicolas Delaby committed
1228
  def test_06_FormatGenerationDrawing(self):
1229
    step_list = [ 'stepCleanUp'
1230 1231
                 ,'stepCreateDrawingDocument'
                 ,'stepCheckDrawingDocumentExportList'
1232
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1233
    self.playSequence(step_list)
1234

Nicolas Delaby's avatar
Nicolas Delaby committed
1235
  def test_06_FormatGenerationPdf(self):
1236
    step_list = [ 'stepCleanUp'
1237 1238
                 ,'stepCreatePDFDocument'
                 ,'stepExportPDF'
1239
                 ,'stepTic'
1240
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1241
    self.playSequence(step_list)
1242

Nicolas Delaby's avatar
Nicolas Delaby committed
1243
  def test_06_FormatGenerationImage(self):
1244
    step_list = [ 'stepCleanUp'
1245 1246
                 ,'stepCreateImageDocument'
                 ,'stepExportImage'
1247
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1248
    self.playSequence(step_list)
1249

Nicolas Delaby's avatar
Nicolas Delaby committed
1250
  def test_08_Cache(self):
1251
    """
1252
      I don't know how to verify how cache works
1253 1254
    """

Nicolas Delaby's avatar
Nicolas Delaby committed
1255
  def test_09_Contribute(self):
1256 1257 1258 1259 1260 1261 1262 1263 1264
    """
      Create content through portal_contributions
      - use newContent to ingest various types 
        also to test content_type_registry setup
      - verify that
        - appropriate portal_types were created
        - the files were converted
        - metadata was read
    """
1265 1266
    step_list = [ 'stepCleanUp'
                 ,'stepContributeFileListWithNoType'
1267
                 ,'stepCleanUp'
Bartek Górny's avatar
Bartek Górny committed
1268
                 ,'stepContributeFileListWithType'
1269
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1270
    self.playSequence(step_list)
1271

Nicolas Delaby's avatar
Nicolas Delaby committed
1272
  def test_10_MetadataSettingPreferenceOrder(self):
1273
    """
1274
      Set some metadata discovery scripts
1275
      Contribute a document, let it get metadata using default setup
1276 1277 1278
      (default is FUC)

      check that the right ones are there
1279 1280
      change preference order, check again
    """
1281 1282
    step_list = [ 'stepCleanUp' 
                 ,'stepCreateTextDocument'
1283
                 ,'stepStraightUpload'
1284 1285 1286
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
1287
                 ,'stepSetSimulatedDiscoveryScriptForOrdering'
Bartek Górny's avatar
Bartek Górny committed
1288
                 ,'stepCheckMetadataSettingOrderFICU'
1289 1290
                 ,'stepCreateTextDocument'
                 ,'stepStraightUpload'
1291 1292 1293
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
1294
                 ,'stepSetSimulatedDiscoveryScriptForOrdering'
1295 1296 1297
                 ,'stepCheckMetadataSettingOrderCUFI'
                 ,'stepCreateTextDocument'
                 ,'stepStraightUpload'
1298 1299 1300
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
1301
                 ,'stepSetSimulatedDiscoveryScriptForOrdering'
1302 1303 1304
                 ,'stepCheckMetadataSettingOrderUIFC'
                 ,'stepCreateTextDocument'
                 ,'stepStraightUpload'
1305 1306 1307
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
1308
                 ,'stepSetSimulatedDiscoveryScriptForOrdering'
1309 1310 1311
                 ,'stepCheckMetadataSettingOrderICUF'
                 ,'stepCreateTextDocument'
                 ,'stepStraightUpload'
1312 1313 1314
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
1315
                 ,'stepSetSimulatedDiscoveryScriptForOrdering'
1316 1317
                 ,'stepCheckMetadataSettingOrderUFCI'
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1318
    self.playSequence(step_list)
1319

Nicolas Delaby's avatar
Nicolas Delaby committed
1320
  def test_11_EmailIngestion(self):
1321 1322 1323 1324 1325
    """
      Simulate email piped to ERP5 by an MTA by uploading test email from file
      Check that document objects are created and appropriate data are set
      (owner, and anything discovered from user and mail body)
    """
1326
    step_list = [ 'stepCleanUp'
Ivan Tyagov's avatar
Ivan Tyagov committed
1327 1328 1329
                 # unknown sender
                 ,'stepReceiveEmail'
                 # create sender as Person object in ERP5
1330
                 ,'stepCreatePerson'
Ivan Tyagov's avatar
Ivan Tyagov committed
1331 1332
                 # now a known sender
                 ,'stepReceiveEmail'
1333
                 ,'stepVerifyEmailedDocumentInitialContribution'
1334 1335
                 # send one more time
                 ,'stepReceiveEmail'
1336 1337 1338 1339 1340 1341 1342
                 ,'stepVerifyEmailedDocumentMultipleContribution'
                 # send email with multiple attachments
                 ,'stepReceiveMultipleAttachmentsEmail'
                 ,'stepVerifyEmailedMultipleDocumentsInitialContribution'
                 # send email with multiple attachments one more time
                 ,'stepReceiveMultipleAttachmentsEmail'
                 ,'stepVerifyEmailedMultipleDocumentsMultipleContribution'
1343
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1344
    self.playSequence(step_list)
1345

Nicolas Delaby's avatar
Nicolas Delaby committed
1346
  def test_12_UploadTextFromContributionTool(self):
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
    """
      Make sure that when upload file from contribution tool, it creates a new
      document in document module. when reupload same filename file, then it
      does not create a new document and update existing document.
    """
    step_list = [ 'stepCleanUp'
                 ,'stepUploadTextFromContributionTool'
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
                 ,'stepDiscoverFromFilename'
                 ,'stepTic'
                 ,'stepReuploadTextFromContributionTool'
                 ,'stepUploadAnotherTextFromContributionTool'
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1362
    self.playSequence(step_list)
1363

Nicolas Delaby's avatar
Nicolas Delaby committed
1364
  def stepUploadTextFromContributionToolWithNonASCIIFilename(self,
1365 1366 1367 1368
                                 sequence=None, sequence_list=None, **kw):
    """
      Upload a file from contribution.
    """
1369
    f = makeFileUpload('TEST-en-002.doc', 'T&é@{T-en-002.doc')
1370
    document = self.portal.portal_contributions.newContent(file=f)
Nicolas Delaby's avatar
Nicolas Delaby committed
1371
    sequence.edit(document_path=document.getPath())
1372
    self.commit()
1373

Nicolas Delaby's avatar
Nicolas Delaby committed
1374
  def stepDiscoverFromFilenameWithNonASCIIFilename(self,
1375 1376 1377 1378 1379 1380
                                 sequence=None, sequence_list=None, **kw):
    """
      Upload a file using contribution tool. This should trigger metadata
      discovery and we should have basic coordinates immediately,
      from first stage.
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
1381 1382
    context = self.portal.restrictedTraverse(sequence.get('document_path'))
    filename = 'T&é@{T-en-002.doc'
1383
    # First make sure the regular expressions work
Nicolas Delaby's avatar
Nicolas Delaby committed
1384
    property_dict = context.getPropertyDictFromFilename(filename)
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
    self.assertEquals(property_dict['reference'], 'T&é@{T')
    self.assertEquals(property_dict['language'], 'en')
    self.assertEquals(property_dict['version'], '002')
    # Then make sure content discover works
    # XXX - This part must be extended
    property_dict = context.getPropertyDictFromContent()
    self.assertEquals(property_dict['title'], 'title')
    self.assertEquals(property_dict['description'], 'comments')
    self.assertEquals(property_dict['subject_list'], ['keywords'])
    # Then make sure metadata discovery works
    self.assertEquals(context.getReference(), 'T&é@{T')
    self.assertEquals(context.getLanguage(), 'en')
    self.assertEquals(context.getVersion(), '002')
Nicolas Delaby's avatar
Nicolas Delaby committed
1398
    self.assertEquals(context.getFilename(), filename)
1399

Nicolas Delaby's avatar
Nicolas Delaby committed
1400
  def test_13_UploadTextFromContributionToolWithNonASCIIFilename(self):
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
    """
      Make sure that when upload file from contribution tool, it creates a new
      document in document module. when reupload same filename file, then it
      does not create a new document and update existing document.
    """
    step_list = [ 'stepCleanUp'
                 ,'stepUploadTextFromContributionToolWithNonASCIIFilename'
                 ,'stepTic'
                 ,'stepDiscoverFromFilenameWithNonASCIIFilename'
                ]
Nicolas Delaby's avatar
Nicolas Delaby committed
1411
    self.playSequence(step_list)
1412

Nicolas Delaby's avatar
Nicolas Delaby committed
1413
  def test_14_ContributionToolIndexation(self):
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
    """
    Check that contribution tool is correctly indexed after business template
    installation.
    Check that contribution tool is correctly indexed by ERP5Site_reindexAll.
    """
    portal = self.portal

    contribution_tool = getToolByName(portal, 'portal_contributions')
    self.assertEquals(1,
        len(portal.portal_catalog(path=contribution_tool.getPath())))

    # Clear catalog
    portal_catalog = self.getCatalogTool()
    portal_catalog.manage_catalogClear()
    # Reindex all
    portal.ERP5Site_reindexAll()
1430
    self.tic()
1431 1432 1433
    self.assertEquals(1,
        len(portal.portal_catalog(path=contribution_tool.getPath())))

Nicolas Delaby's avatar
Nicolas Delaby committed
1434 1435
  def test_15_TestFilenameDiscovery(self):
    """Test that filename is well set in filename
1436 1437 1438 1439 1440 1441 1442
    - filename can we discovery from file
    - filename can be pass as argument by the user
    """
    portal = self.portal
    contribution_tool = getToolByName(portal, 'portal_contributions')
    file_object = makeFileUpload('TEST-en-002.doc')
    document = contribution_tool.newContent(file=file_object)
Nicolas Delaby's avatar
Nicolas Delaby committed
1443
    self.assertEquals(document.getFilename(), 'TEST-en-002.doc')
1444 1445
    my_filename = 'Something.doc'
    document = contribution_tool.newContent(file=file_object,
Nicolas Delaby's avatar
Nicolas Delaby committed
1446
                                            filename=my_filename)
1447
    self.tic()
Nicolas Delaby's avatar
Nicolas Delaby committed
1448
    self.assertEquals(document.getFilename(), my_filename)
1449

1450 1451 1452 1453 1454 1455 1456 1457
  def test_16_TestMetadataDiscoveryFromUserLogin(self):
    """
      Test that  user_login is used to discover meta data (group, function, etc.. from Assignment)
    """
    portal = self.portal
    contribution_tool = getToolByName(portal, 'portal_contributions')
    # create an user to simulate upload from him
    user = self.createUser(reference='contributor1')
1458 1459 1460 1461
    assignment = self.createUserAssignment(user, \
                                           dict(group='anybody',
                                                function='function/musician/wind/saxophone',
                                                site='site/arctic/spitsbergen'))
1462
    portal.document_module.manage_setLocalRoles('contributor1', ['Assignor',])
1463
    self.tic()
1464 1465
    file_object = makeFileUpload('TEST-en-002.doc')
    document = contribution_tool.newContent(file=file_object)
1466
    document.discoverMetadata(document.getSourceReference(), 'contributor1') 
1467
    self.tic()
1468 1469
    self.assertEquals(document.getSourceReference(), 'TEST-en-002.doc')
    self.assertEquals('function/musician/wind/saxophone', document.getFunction())
1470
    self.assertEquals('anybody', document.getGroup())
1471
    self.assertEquals('arctic/spitsbergen', document.getSite())
1472

Nicolas Delaby's avatar
Nicolas Delaby committed
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
  def test_IngestionConfigurationByTypeBasedMethod_usecase1(self):
    """How to configure meta data discovery so that each time a file
    with same URL is uploaded, a new document is created with same reference
    but increased version ?
    """
    input_script_id = 'Document_getPropertyDictFromContent'
    python_code = """from Products.CMFCore.utils import getToolByName
portal = context.getPortalObject()
information = context.getContentInformation()

result = {}
property_id_list = context.propertyIds()
for k, v in information.items():
  key = k.lower()
  if v:
    if isinstance(v, unicode):
      v = v.encode('utf-8')
    if key in property_id_list:
      if key == 'reference':
        pass # XXX - We can not trust reference on getContentInformation
      else:
        result[key] = v
    elif key == 'author':
      p = context.portal_catalog.getResultValue(title=v, portal_type='Person')
      if p is not None:
        result['contributor'] = p.getRelativeUrl()
    elif key == 'keywords':
      result['subject_list'] = v.split()

reference = context.asNormalisedURL()

result['reference'] = reference
id_group = ('dms_version_generator', reference)
result['version'] = '%.5d' % (portal.portal_ids.generateNewId(id_group=id_group, default=1))
return result
"""
    self.newPythonScript(input_script_id, '', python_code)
    document_to_ingest = self.portal.portal_contributions.newContent(
                                                          portal_type='File',
                                                          filename='toto.txt',
                                                          data='Hello World!')
    document_to_ingest.publish()
    self.tic()
    url = document_to_ingest.absolute_url() + '/getData'
    first_doc = self.portal.portal_contributions.newContent(url=url)
    self.tic()
    self.assertEquals(first_doc.getPortalType(), 'Text')
    self.assertEquals(first_doc.getContentType(), 'text/plain')
    self.assertEquals(first_doc.getReference(), first_doc.asNormalisedURL())
    self.assertEquals(first_doc.getVersion(), '00001')
    self.assertEquals(first_doc.asURL(), url)
    second_doc = self.portal.portal_contributions.newContent(url=url)
    self.tic()
    self.assertEquals(second_doc.getPortalType(), 'Text')
    self.assertEquals(second_doc.getContentType(), 'text/plain')
    self.assertEquals(second_doc.getReference(), second_doc.asNormalisedURL())
    self.assertEquals(second_doc.getVersion(), '00002')
    self.assertEquals(second_doc.asURL(), url)

    document_to_ingest2 = self.portal.portal_contributions.newContent(
                                                          portal_type='File',
                                                          filename='toto.txt',
                                                          data='Hello World!')
    document_to_ingest2.publish()
    self.tic()
    url2 = document_to_ingest2.absolute_url() + '/getData'
    first_doc = self.portal.portal_contributions.newContent(url=url2)
    self.tic()
    self.assertEquals(first_doc.getPortalType(), 'Text')
    self.assertEquals(first_doc.getContentType(), 'text/plain')
    self.assertEquals(first_doc.getReference(), first_doc.asNormalisedURL())
    self.assertEquals(first_doc.getVersion(), '00001')
    self.assertEquals(first_doc.asURL(), url2)
    second_doc = self.portal.portal_contributions.newContent(url=url2)
    self.tic()
    self.assertEquals(second_doc.getPortalType(), 'Text')
    self.assertEquals(second_doc.getContentType(), 'text/plain')
    self.assertEquals(second_doc.getReference(), second_doc.asNormalisedURL())
    self.assertEquals(second_doc.getVersion(), '00002')
    self.assertEquals(second_doc.asURL(), url2)

  def test_IngestionConfigurationByTypeBasedMethod_usecase2(self):
    """How to configure meta data discovery so that each time a file
    with same URL  is uploaded, a new document is created
    with same reference but same version ?
    """
    input_script_id = 'Document_getPropertyDictFromContent'
    python_code = """from Products.CMFCore.utils import getToolByName
portal = context.getPortalObject()
information = context.getContentInformation()

result = {}
property_id_list = context.propertyIds()
for k, v in information.items():
  key = k.lower()
  if v:
    if isinstance(v, unicode):
      v = v.encode('utf-8')
    if key in property_id_list:
      if key == 'reference':
        pass # XXX - We can not trust reference on getContentInformation
      else:
        result[key] = v
    elif key == 'author':
      p = context.portal_catalog.getResultValue(title=v, portal_type='Person')
      if p is not None:
        result['contributor'] = p.getRelativeUrl()
    elif key == 'keywords':
      result['subject_list'] = v.split()

reference = context.asNormalisedURL()
result['reference'] = reference
return result
"""
    self.newPythonScript(input_script_id, '', python_code)
    document_to_ingest = self.portal.portal_contributions.newContent(
                                                          portal_type='File',
                                                          filename='toto.txt',
                                                          data='Hello World!')
    document_to_ingest.publish()
    self.tic()
    url = document_to_ingest.absolute_url() + '/getData'
    first_doc = self.portal.portal_contributions.newContent(url=url)
    self.tic()
    self.assertEquals(first_doc.getPortalType(), 'Text')
    self.assertEquals(first_doc.getContentType(), 'text/plain')
    self.assertEquals(first_doc.getReference(), first_doc.asNormalisedURL())
    self.assertEquals(first_doc.getVersion(), '001')
    self.assertEquals(first_doc.asURL(), url)
    second_doc = self.portal.portal_contributions.newContent(url=url)
    self.tic()
    self.assertEquals(second_doc.getPortalType(), 'Text')
    self.assertEquals(second_doc.getContentType(), 'text/plain')
    self.assertEquals(second_doc.getReference(), second_doc.asNormalisedURL())
    self.assertEquals(second_doc.getVersion(), '001')
    self.assertEquals(second_doc.asURL(), url)

    document_to_ingest2 = self.portal.portal_contributions.newContent(
                                                          portal_type='File',
                                                          filename='toto.txt',
                                                          data='Hello World!')
    document_to_ingest2.publish()
    self.tic()
    url2 = document_to_ingest2.absolute_url() + '/getData'
    first_doc = self.portal.portal_contributions.newContent(url=url2)
    self.tic()
    self.assertEquals(first_doc.getPortalType(), 'Text')
    self.assertEquals(first_doc.getContentType(), 'text/plain')
    self.assertEquals(first_doc.getReference(), first_doc.asNormalisedURL())
    self.assertEquals(first_doc.getVersion(), '001')
    self.assertEquals(first_doc.asURL(), url2)
    second_doc = self.portal.portal_contributions.newContent(url=url2)
    self.tic()
    self.assertEquals(second_doc.getPortalType(), 'Text')
    self.assertEquals(second_doc.getContentType(), 'text/plain')
    self.assertEquals(second_doc.getReference(), second_doc.asNormalisedURL())
    self.assertEquals(second_doc.getVersion(), '001')
    self.assertEquals(second_doc.asURL(), url2)

  def test_IngestionConfigurationByTypeBasedMethod_usecase3(self):
    """How to discover metadata so that each new document
    has a new reference which is generated automatically
    as an increase sequence of numbers ?
    """
    input_script_id = 'Document_finishIngestion'
    python_code = """from Products.CMFCore.utils import getToolByName
portal = context.getPortalObject()
portal_ids = getToolByName(portal, 'portal_ids')
id_group = 'dms_reference_generator3'
reference = 'I CHOOSED THIS REFERENCE %s' % portal.portal_ids.generateNewId(id_group=id_group)
context.setReference(reference)
"""
    self.newPythonScript(input_script_id, '', python_code)
    document_to_ingest = self.portal.portal_contributions.newContent(
                                                          portal_type='File',
                                                          filename='toto.txt',
                                                          data='Hello World!')
    document_to_ingest.publish()
    self.tic()
    url = document_to_ingest.absolute_url() + '/getData'
    first_doc = self.portal.portal_contributions.newContent(url=url)
    self.tic()
    self.assertEquals(first_doc.getPortalType(), 'Text')
    self.assertEquals(first_doc.getContentType(), 'text/plain')
    self.assertEquals(first_doc.getReference(), 'I CHOOSED THIS REFERENCE 1')
    self.assertEquals(first_doc.getVersion(), '001')
    self.assertEquals(first_doc.asURL(), url)
    second_doc = self.portal.portal_contributions.newContent(url=url)
    self.tic()
    self.assertEquals(second_doc.getPortalType(), 'Text')
    self.assertEquals(second_doc.getContentType(), 'text/plain')
    self.assertEquals(second_doc.getReference(), 'I CHOOSED THIS REFERENCE 2')
    self.assertEquals(second_doc.getVersion(), '001')
    self.assertEquals(second_doc.asURL(), url)

    document_to_ingest2 = self.portal.portal_contributions.newContent(
                                                          portal_type='File',
                                                          filename='toto.txt',
                                                          data='Hello World!')
    document_to_ingest2.publish()
    self.tic()
    self.assertEquals(document_to_ingest2.getReference(),
                      'I CHOOSED THIS REFERENCE 3')

    url2 = document_to_ingest2.absolute_url() + '/getData'
    first_doc = self.portal.portal_contributions.newContent(url=url2)
    self.tic()
    self.assertEquals(first_doc.getPortalType(), 'Text')
    self.assertEquals(first_doc.getContentType(), 'text/plain')
    self.assertEquals(first_doc.getReference(), 'I CHOOSED THIS REFERENCE 4')
    self.assertEquals(first_doc.getVersion(), '001')
    self.assertEquals(first_doc.asURL(), url2)
    second_doc = self.portal.portal_contributions.newContent(url=url2)
    self.tic()
    self.assertEquals(second_doc.getPortalType(), 'Text')
    self.assertEquals(second_doc.getContentType(), 'text/plain')
    self.assertEquals(second_doc.getReference(), 'I CHOOSED THIS REFERENCE 5')
    self.assertEquals(second_doc.getVersion(), '001')
    self.assertEquals(second_doc.asURL(), url2)

  def test_IngestionConfigurationByTypeBasedMethod_usecase4(self):
    """How to configure meta data discovery so that each time a file
    with same URL is uploaded, a new document is created
    with same reference (generated automatically as an
    increase sequence of numbers) but increased version ?
    """
    input_script_id = 'Document_getPropertyDictFromContent'
    python_code = """from Products.CMFCore.utils import getToolByName
portal = context.getPortalObject()
information = context.getContentInformation()

result = {}
property_id_list = context.propertyIds()
for k, v in information.items():
  key = k.lower()
  if v:
    if isinstance(v, unicode):
      v = v.encode('utf-8')
    if key in property_id_list:
      if key == 'reference':
        pass # XXX - We can not trust reference on getContentInformation
      else:
        result[key] = v
    elif key == 'author':
      p = context.portal_catalog.getResultValue(title=v, portal_type='Person')
      if p is not None:
        result['contributor'] = p.getRelativeUrl()
    elif key == 'keywords':
      result['subject_list'] = v.split()

url = context.asNormalisedURL()
portal_url_registry = getToolByName(context.getPortalObject(),
                                    'portal_url_registry')
try:
  reference = portal_url_registry.getReferenceFromURL(url)
except KeyError:
  id_group = 'dms_reference_generator4'
  reference = 'I CHOOSED THIS REFERENCE %s' % portal.portal_ids.generateNewId(id_group=id_group)
result['reference'] = reference
id_group = ('dms_version_generator', reference)
result['version'] = '%.5d' % (portal.portal_ids.generateNewId(id_group=id_group, default=1))
return result
1735
"""
Nicolas Delaby's avatar
Nicolas Delaby committed
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
    self.newPythonScript(input_script_id, '', python_code)
    document_to_ingest = self.portal.portal_contributions.newContent(
                                                          portal_type='File',
                                                          filename='toto.txt',
                                                          data='Hello World!')
    document_to_ingest.publish()
    self.tic()
    url = document_to_ingest.absolute_url() + '/getData'
    first_doc = self.portal.portal_contributions.newContent(url=url)
    self.tic()
    self.assertEquals(first_doc.getPortalType(), 'Text')
    self.assertEquals(first_doc.getContentType(), 'text/plain')
    self.assertEquals(first_doc.getReference(), 'I CHOOSED THIS REFERENCE 1')
    self.assertEquals(first_doc.getVersion(), '00001')
    self.assertEquals(first_doc.asURL(), url)
    second_doc = self.portal.portal_contributions.newContent(url=url)
    self.tic()
    self.assertEquals(second_doc.getPortalType(), 'Text')
    self.assertEquals(second_doc.getContentType(), 'text/plain')
    self.assertEquals(second_doc.getReference(), 'I CHOOSED THIS REFERENCE 1')
    self.assertEquals(second_doc.getVersion(), '00002')
    self.assertEquals(second_doc.asURL(), url)

    document_to_ingest2 = self.portal.portal_contributions.newContent(
                                                          portal_type='File',
                                                          filename='toto.txt',
                                                          data='Hello World!')
    document_to_ingest2.publish()
    self.tic()
    self.assertEquals(document_to_ingest2.getReference(),
                      'I CHOOSED THIS REFERENCE 2')

    url2 = document_to_ingest2.absolute_url() + '/getData'
    first_doc = self.portal.portal_contributions.newContent(url=url2)
    self.tic()
    self.assertEquals(first_doc.getPortalType(), 'Text')
    self.assertEquals(first_doc.getContentType(), 'text/plain')
    self.assertEquals(first_doc.getReference(), 'I CHOOSED THIS REFERENCE 3')
    self.assertEquals(first_doc.getVersion(), '00001')
    self.assertEquals(first_doc.asURL(), url2)
    second_doc = self.portal.portal_contributions.newContent(url=url2)
    self.tic()
    self.assertEquals(second_doc.getPortalType(), 'Text')
    self.assertEquals(second_doc.getContentType(), 'text/plain')
    self.assertEquals(second_doc.getReference(), 'I CHOOSED THIS REFERENCE 3')
    self.assertEquals(second_doc.getVersion(), '00002')
    self.assertEquals(second_doc.asURL(), url2)

  def test_IngestionConfigurationByTypeBasedMethod_usecase5(self):
    """How to configure meta data discovery so that each time a file
    with same URL is uploaded, a new document is created
    with same reference (generated automatically as
    an increase sequence of numbers) but same version?
    """
    input_script_id = 'Document_getPropertyDictFromContent'
    python_code = """from Products.CMFCore.utils import getToolByName
portal = context.getPortalObject()
information = context.getContentInformation()

result = {}
property_id_list = context.propertyIds()
for k, v in information.items():
  key = k.lower()
  if v:
    if isinstance(v, unicode):
      v = v.encode('utf-8')
    if key in property_id_list:
      if key == 'reference':
        pass # XXX - We can not trust reference on getContentInformation
      else:
        result[key] = v
    elif key == 'author':
      p = context.portal_catalog.getResultValue(title=v, portal_type='Person')
      if p is not None:
        result['contributor'] = p.getRelativeUrl()
    elif key == 'keywords':
      result['subject_list'] = v.split()

url = context.asNormalisedURL()
portal_url_registry = getToolByName(context.getPortalObject(),
                                    'portal_url_registry')
try:
  reference = portal_url_registry.getReferenceFromURL(url)
except KeyError:
  id_group = 'dms_reference_generator5'
  reference = 'I CHOOSED THIS REFERENCE %s' % portal.portal_ids.generateNewId(id_group=id_group)
result['reference'] = reference
return result
1824
"""
Nicolas Delaby's avatar
Nicolas Delaby committed
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
    self.newPythonScript(input_script_id, '', python_code)
    document_to_ingest = self.portal.portal_contributions.newContent(
                                                          portal_type='File',
                                                          filename='toto.txt',
                                                          data='Hello World!')
    document_to_ingest.publish()
    self.tic()

    url = document_to_ingest.absolute_url() + '/getData'
    first_doc = self.portal.portal_contributions.newContent(url=url)
    self.tic()
    self.assertEquals(first_doc.getPortalType(), 'Text')
    self.assertEquals(first_doc.getContentType(), 'text/plain')
    self.assertEquals(first_doc.getReference(), 'I CHOOSED THIS REFERENCE 1')
    self.assertEquals(first_doc.getVersion(), '001')
    self.assertEquals(first_doc.asURL(), url)
    second_doc = self.portal.portal_contributions.newContent(url=url)
    self.tic()
    self.assertEquals(second_doc.getPortalType(), 'Text')
    self.assertEquals(second_doc.getContentType(), 'text/plain')
    self.assertEquals(second_doc.getReference(), 'I CHOOSED THIS REFERENCE 1')
    self.assertEquals(second_doc.getVersion(), '001')
    self.assertEquals(second_doc.asURL(), url)

    document_to_ingest2 = self.portal.portal_contributions.newContent(
                                                          portal_type='File',
                                                          filename='toto.txt',
                                                          data='Hello World!')
    document_to_ingest2.publish()
    self.tic()
    self.assertEquals(document_to_ingest2.getReference(),
                      'I CHOOSED THIS REFERENCE 2')

    url2 = document_to_ingest2.absolute_url() + '/getData'
    first_doc = self.portal.portal_contributions.newContent(url=url2)
    self.tic()
    self.assertEquals(first_doc.getPortalType(), 'Text')
    self.assertEquals(first_doc.getContentType(), 'text/plain')
    self.assertEquals(first_doc.getReference(), 'I CHOOSED THIS REFERENCE 3')
    self.assertEquals(first_doc.getVersion(), '001')
    self.assertEquals(first_doc.asURL(), url2)
    second_doc = self.portal.portal_contributions.newContent(url=url2)
    self.tic()
    self.assertEquals(second_doc.getPortalType(), 'Text')
    self.assertEquals(second_doc.getContentType(), 'text/plain')
    self.assertEquals(second_doc.getReference(), 'I CHOOSED THIS REFERENCE 3')
    self.assertEquals(second_doc.getVersion(), '001')
    self.assertEquals(second_doc.asURL(), url2)

  def test_IngestionConfigurationByTypeBasedMethod_usecase6(self):
    """How to configure meta data discovery so that a Spreadsheet
    as a application/octet-stream without explicit extension, become
    a Spreadsheet ?
    """
    path = makeFilePath('import_region_category.xls')
    data = open(path, 'r').read()

    document = self.portal.portal_contributions.newContent(filename='toto',
                                                  data=data,
                                                  reference='Custom.Reference')
    self.tic()# Discover metadata will delete first ingested document
    # then reingest new one with appropriate portal_type
    result_list = self.portal.portal_catalog(reference='Custom.Reference')
    self.assertEquals(len(result_list), 1)
    self.assertEquals(result_list[0].getPortalType(), 'Spreadsheet')

  def test_IngestionConfigurationByTypeBasedMethod_usecase7(self):
    """How to reingest a published document, by a user action ?
    If after a while the user decide to change the portal_type of a 
    published document , File => Text ?
    """
    module = self.portal.document_module
    document = module.newContent(portal_type='File',
                                 property_which_doesnot_exists='Foo',
                                 data='Hello World!',
                                 filename='toto.txt')
    document.publish()
    self.tic()
    document.edit(title='One title', reference='EFAA')
    self.tic()
    # Now change it to a Text portal_type
    new_doc = document.migratePortalType('Text')
    self.tic()
    self.assertEquals(new_doc.getPortalType(), 'Text')
    self.assertEquals(new_doc.getProperty('property_which_doesnot_exists'),
                                          'Foo')
    self.assertEquals(new_doc.getTitle(), 'One title')
    self.assertEquals(new_doc.getReference(), 'EFAA')
    self.assertEquals(new_doc.getValidationState(), 'published')
    self.assertEquals(new_doc.getData(), 'Hello World!')

    # Migrate a document with url property
    url = new_doc.absolute_url() + '/getData'
    document = self.portal.portal_contributions.newContent(url=url)
    document.submit()
    self.tic()
    self.assertEquals(document.getPortalType(), 'Text')
    # Change it to File
    new_doc = document.migratePortalType('File')
    self.assertEquals(new_doc.getPortalType(), 'File')
    self.assertEquals(new_doc.asURL(), url)
    self.assertEquals(new_doc.getData(), 'Hello World!')
    self.assertEquals(new_doc.getValidationState(), 'submitted')
Jérome Perrin's avatar
Jérome Perrin committed
1928

1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
  def test_User_Portal_Type_parameter_is_honoured(self):
    """Check that given portal_type is always honoured
    """
    path = makeFilePath('import_region_category.xls')
    data = open(path, 'r').read()

    document = self.portal.portal_contributions.newContent(
                                      filename='import_region_category.xls',
                                      data=data,
                                      content_type='application/vnd.ms-excel',
                                      reference='I.want.a.pdf',
                                      portal_type='PDF')
    self.tic()# Discover metadata will try change the portal_type
    # but user decision take precedence: PDF must be created
    result_list = self.portal.portal_catalog(reference='I.want.a.pdf')
    self.assertEquals(len(result_list), 1)
    self.assertEquals(result_list[0].getPortalType(), 'PDF')

1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
  def test_User_ID_parameter_is_honoured(self):
    """Check that given id is always honoured
    """
    path = makeFilePath('import_region_category.xls')
    data = open(path, 'r').read()

    document = self.portal.portal_contributions.newContent(
                                      id='this_id',
                                      filename='import_region_category.xls',
                                      data=data,
                                      content_type='application/vnd.ms-excel',
                                      reference='I.want.a.pdf',
                                      portal_type='PDF')
    self.tic()
    result_list = self.portal.portal_catalog(reference='I.want.a.pdf',
                                             id='this_id')
    self.assertEquals(len(result_list), 1)
    self.assertRaises(BadRequest,
                      self.portal.portal_contributions.newContent,
                      id='this_id',
                      filename='import_region_category.xls',
                      data=data,
                      content_type='application/vnd.ms-excel',
                      reference='I.want.a.pdf',
                      portal_type='PDF')

1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
  def test_newContent_trough_http(self):
    filename = 'import_region_category.xls'
    path = makeFilePath(filename)
    data = open(path, 'r').read()
    reference = 'ITISAREFERENCE'

    portal_url = self.portal.absolute_url()
    url_split = urlparse.urlsplit(portal_url)
    url_dict = dict(protocol=url_split[0],
                    hostname=url_split[1])
    uri = '%(protocol)s://%(hostname)s' % url_dict
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() 
    password_mgr.add_password(realm=None, uri=uri, user='ERP5TypeTestCase',
                              passwd='')
    opener = urllib2.build_opener(urllib2.HTTPDigestAuthHandler(password_mgr),
                                  urllib2.HTTPBasicAuthHandler(password_mgr))
    urllib2.install_opener(opener)

    push_url = '%s%s/newContent' % (uri, self.portal.portal_contributions.getPath(),)
    request = urllib2.Request(push_url, urllib.urlencode(
                                        {'data': data,
                                        'filename': filename,
                                        'reference': reference,
                                        'disable_cookie_login__': 1,
                                        }))
    # disable_cookie_login__ is required to force zope to raise Unauthorized (401)
    # then HTTPDigestAuthHandler can perform HTTP Authentication
    response = urllib2.urlopen(request)
    self.assertEquals(response.getcode(), httplib.OK)
    self.tic()
    document = self.portal.portal_catalog.getResultValue(portal_type='Spreadsheet',
                                                         reference=reference)
    self.assertTrue(document is not None)
    self.assertEquals(document.getData(), data)
2007

Jérome Perrin's avatar
Jérome Perrin committed
2008 2009 2010 2011
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestIngestion))
  return suite