testIngestion.py 57.3 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
import transaction
36 37
from Testing import ZopeTestCase
from DateTime import DateTime
38
from AccessControl.SecurityManagement import newSecurityManager
39
from Products.ERP5Type.Utils import convertToUpperCase
Nicolas Delaby's avatar
Nicolas Delaby committed
40 41
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase,\
                                                       _getConversionServerDict
42
from Products.ERP5Type.tests.Sequence import SequenceList
43
from Products.ERP5Type.tests.utils import FileUpload
44
from Products.ERP5OOo.Document.OOoDocument import ConversionError
Nicolas Delaby's avatar
Nicolas Delaby committed
45
from Products.ERP5OOo.OOoUtils import OOoBuilder
46
from zLOG import LOG, INFO, ERROR
47
from Products.CMFCore.utils import getToolByName
48

49
# test files' home
50
TEST_FILES_HOME = os.path.join(os.path.dirname(__file__), 'test_document')
51 52
FILE_NAME_REGULAR_EXPRESSION = "(?P<reference>[A-Z&é@{]{3,7})-(?P<language>[a-z]{2})-(?P<version>[0-9]{3})"
REFERENCE_REGULAR_EXPRESSION = "(?P<reference>[A-Z&é@{]{3,7})(-(?P<language>[a-z]{2}))?(-(?P<version>[0-9]{3}))?"
53

54 55 56 57 58 59
def printAndLog(msg):
  """
  A utility function to print a message
  to the standard output and to the LOG
  at the same time
  """
60 61 62 63
  msg = str(msg)
  ZopeTestCase._print('\n ' + msg)
  LOG('Testing... ', 0, msg)

64 65

def makeFilePath(name):
66
  return os.path.join(TEST_FILES_HOME, name)
67

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

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

  # pseudo constants
80
  RUN_ALL_TEST = 1
81 82 83 84 85 86 87 88 89 90
  QUIET = 0

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

  def getTitle(self):
    """
      Return the title of the current test set.
    """
91
    return "ERP5 DMS - Ingestion"
92 93 94 95 96

  def getBusinessTemplateList(self):
    """
      Return the list of required business templates.
    """
97 98
    return ('erp5_base',
            'erp5_ingestion', 'erp5_ingestion_mysql_innodb_catalog',
99
            'erp5_web', 'erp5_crm', 'erp5_dms')
100 101 102 103 104 105

  def afterSetUp(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
      Initialize the ERP5 site.
    """
    self.login()
106 107
    self.datetime = DateTime()
    self.portal = self.getPortal()
108
    self.portal_categories = self.getCategoryTool()
109 110 111
    self.portal_catalog = self.getCatalogTool()
    self.createDefaultCategoryList()
    self.setSystemPreference()
112
    self.setSimulatedNotificationScript()
113

114
  def beforeTearDown(self):
115 116 117 118 119 120 121
    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
122 123
    self.portal.portal_caches.clearAllCache()

124
  def setSystemPreference(self):
125
    default_pref = self.portal.portal_preferences.default_site_preference
Nicolas Delaby's avatar
Nicolas Delaby committed
126 127 128
    conversion_dict = _getConversionServerDict()
    default_pref.setPreferredOoodocServerAddress(conversion_dict['hostname'])
    default_pref.setPreferredOoodocServerPortNumber(conversion_dict['port'])
129 130
    default_pref.setPreferredDocumentFileNameRegularExpression(FILE_NAME_REGULAR_EXPRESSION)
    default_pref.setPreferredDocumentReferenceRegularExpression(REFERENCE_REGULAR_EXPRESSION)
131 132
    if default_pref.getPreferenceState() != 'global':
      default_pref.enable()
133

134 135 136 137 138 139 140 141 142 143 144 145
  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):
      factory = context.manage_addProduct['PythonScripts'].manage_addPythonScript
      factory(id=script_id)
    script = getattr(context, script_id)
    script.ZPythonScript_edit('email_to, event, doc, **kw', 'return')

146
  def createDefaultCategoryList(self):
147
    """
148 149 150 151 152 153
      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.
154 155 156 157 158 159
    """
    self.category_list = [
                         # Role categories
                          {'path' : 'role/internal'
                           ,'title': 'Internal'
                           }
160 161 162 163 164 165 166 167 168
                          ,{'path' : 'function/musician/wind/saxophone'
                           ,'title': 'Saxophone'
                           }
                          ,{'path' : 'group/medium'
                           ,'title': 'Medium'
                           }
                          ,{'path' : 'site/arctic/spitsbergen'
                           ,'title': 'Spitsbergen'
                           }
169 170 171
                          ,{'path' : 'group/anybody'
                           ,'title': 'Anybody'
                           }
172 173 174 175 176 177
                          ,{'path' : 'publication_section/cop'
                           ,'title': 'COPs'
                           }
                          ,{'path' : 'publication_section/cop/one'
                           ,'title': 'COP one'
                           }
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
                         ]

    # 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'))
Ivan Tyagov's avatar
Ivan Tyagov committed
212
    self.stepTic()
213 214 215 216 217 218

  def getCategoryList(self, base_category=None):
    """
      Get a list of categories with same base categories.
    """
    categories = []
219
    if base_category is not None:
220 221 222 223 224
      for category in self.category_list:
        if category["path"].split('/')[0] == base_category:
          categories.append(category)
    return categories

225
  def getDocument(self, id):
226 227 228 229 230 231
    """
      Returns a document with given ID in the
      document module.
    """
    document_module = self.portal.document_module
    return getattr(document_module, id)
232

233
  def checkIsObjectCatalogged(self, portal_type, **kw):
234
    """
235 236 237 238 239
      Make sure that a document with given portal type
      and kw properties is already present in the catalog.

      Typical use of this method consists in providing
      an id or reference.
240
    """
241
    res = self.portal_catalog(portal_type=portal_type, **kw.copy())
242
    self.assertEquals(len(res), 1)
243 244
    for key, value in kw.items():
      self.assertEquals(res[0].getProperty(key), value)
245

246
  def newEmptyCataloggedDocument(self, portal_type, id):
247
    """
248 249 250 251 252 253
      Create an empty document of given portal type
      and given ID. 

      Documents are immediately catalogged and verified
      both form catalog point of view and from their
      presence in the document module.
254
    """
255 256 257 258 259
    document_module = self.portal.getDefaultModule(portal_type)
    document = getattr(document_module, id, None)
    if document is not None:
      document_module.manage_delObjects([id,])
    document = document_module.newContent(portal_type=portal_type, id=id)
Ivan Tyagov's avatar
Ivan Tyagov committed
260
    self.stepTic()
261 262 263
    self.checkIsObjectCatalogged(portal_type, id=id, parent_uid=document_module.getUid())
    self.assert_(hasattr(document_module, id))
    return document
264

265
  def ingestFormatList(self, document_id, format_list, portal_type=None):
266
    """
267 268 269 270 271 272 273 274 275
      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.
276 277
    """
    if portal_type is None:
278
      document_module = self.portal.document_module
279
    else:
280
      document_module = self.portal.getDefaultModule(portal_type)
Ivan Tyagov's avatar
Ivan Tyagov committed
281
    document = getattr(document_module, document_id)
282
    for revision, format in enumerate(format_list):
Ivan Tyagov's avatar
Ivan Tyagov committed
283
      filename = 'TEST-en-002.%s' %format
284
      f = makeFileUpload(filename)
Ivan Tyagov's avatar
Ivan Tyagov committed
285
      document.edit(file=f)
Ivan Tyagov's avatar
Ivan Tyagov committed
286
      self.stepTic()
Ivan Tyagov's avatar
Ivan Tyagov committed
287
      self.failUnless(document.hasFile())
288 289 290
      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
291 292
        self.assert_('magic' in document.SearchableText())
        self.assert_('magic' in str(document.asText()))
293

294
  def checkDocumentExportList(self, document_id, format, asserted_target_list):
295
    """
296 297 298
      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
299
    """
Ivan Tyagov's avatar
Ivan Tyagov committed
300
    document = self.getDocument(document_id)
301 302
    filename = 'TEST-en-002.' + format
    f = makeFileUpload(filename)
Ivan Tyagov's avatar
Ivan Tyagov committed
303
    document.edit(file=f)
Ivan Tyagov's avatar
Ivan Tyagov committed
304
    self.stepTic()
305 306
    # 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
307
    target_list = document.getTargetFormatList()
308
    for target in asserted_target_list:
309 310
      self.assert_(target in target_list)

Bartek Górny's avatar
Bartek Górny committed
311
  def contributeFileList(self, with_portal_type=False):
312
    """
313 314 315
      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
316 317
      on portal_contributions.
      http://framework.openoffice.org/documentation/mimetypes/mimetypes.html
318
    """
319 320 321 322
    created_documents = []
    extension_to_type = (('ppt', 'Presentation')
                        ,('doc', 'Text')
                        ,('sdc', 'Spreadsheet')
323
                        ,('sxc', 'Spreadsheet')
324 325 326 327
                        ,('pdf', 'PDF')
                        ,('jpg', 'Image')
                        ,('py', 'File')
                        )
328 329
    counter = 1
    old_portal_type = ''
330
    for extension, portal_type in extension_to_type:
Ivan Tyagov's avatar
Ivan Tyagov committed
331
      filename = 'TEST-en-002.%s' %extension
332
      file = makeFileUpload(filename)
333 334 335 336 337 338
      # 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)
339
      if with_portal_type:
Ivan Tyagov's avatar
Ivan Tyagov committed
340
        document = self.portal.portal_contributions.newContent(portal_type=portal_type, file=file)
341
      else:
Ivan Tyagov's avatar
Ivan Tyagov committed
342 343
        document = self.portal.portal_contributions.newContent(file=file)
      created_documents.append(document)
Ivan Tyagov's avatar
Ivan Tyagov committed
344
    self.stepTic()
345 346 347
    # inspect created objects
    count = 0
    for extension, portal_type in extension_to_type:
Ivan Tyagov's avatar
Ivan Tyagov committed
348
      document = created_documents[count]
349
      count+=1
Ivan Tyagov's avatar
Ivan Tyagov committed
350 351
      self.assertEquals(document.getPortalType(), portal_type)
      self.assertEquals(document.getReference(), 'TEST')
352
      if document.isSupportBaseDataConversion():
353 354
        # We check if conversion has succeeded by looking
        # at the external_processing workflow
Ivan Tyagov's avatar
Ivan Tyagov committed
355 356
        self.assertEquals(document.getExternalProcessingState(), 'converted')
        self.assert_('magic' in document.SearchableText())
357 358 359 360 361 362

  def newPythonScript(self, object_id, script_id, argument_list, code):
    """
      Creates a new python script with given argument_list
      and source code.
    """
363
    context = self.getDocument(object_id)
Ivan Tyagov's avatar
Ivan Tyagov committed
364
    context.manage_addProduct['PythonScripts'].manage_addPythonScript(id=script_id)
365
    script = getattr(context, script_id)
366
    script.ZPythonScript_edit(argument_list, code)
367

368
  def setDiscoveryOrder(self, order, id='one'):
369
    """
370 371
      Creates a script to define the metadata discovery order
      for Text documents.
372 373
    """
    script_code = "return %s" % str(order)
374
    self.newPythonScript(id, 'Text_getPreferredDocumentMetadataDiscoveryOrderList', '', script_code)
375
    
376 377 378 379 380
  def discoverMetadata(self, document_id='one'):
    """
      Sets input parameters and on the document ID document_id
      and discover metadata. For reindexing
    """
Ivan Tyagov's avatar
Ivan Tyagov committed
381
    document = self.getDocument(document_id)
382
    # simulate user input
Ivan Tyagov's avatar
Ivan Tyagov committed
383 384 385 386 387
    document._backup_input = dict(reference='INPUT', 
                                  language='in',
                                  version='004', 
                                  short_title='from_input',
                                  contributor='person_module/james')
388
    # pass to discovery file_name and user_login
Ivan Tyagov's avatar
Ivan Tyagov committed
389
    document.discoverMetadata(document.getSourceReference(), 'john_doe') 
Ivan Tyagov's avatar
Ivan Tyagov committed
390
    self.stepTic()
Ivan Tyagov's avatar
Ivan Tyagov committed
391
    
392 393 394 395 396
  def checkMetadataOrder(self, expected_metadata, document_id='one'):
    """
    Asserts that metadata of document ID document_id
    is the same as expected_metadata
    """
Ivan Tyagov's avatar
Ivan Tyagov committed
397
    document = self.getDocument(document_id)
398
    for k, v in expected_metadata.items():
Ivan Tyagov's avatar
Ivan Tyagov committed
399
      self.assertEquals(document.getProperty(k), v)
400

401 402 403 404 405 406 407 408 409
  def receiveEmail(self, data,
                   portal_type='Document Ingestion Message',
                   container_path='document_ingestion_module',
                   file_name='email.emx'):
    return self.portal.portal_contributions.newContent(data=data,
                                                       portal_type=portal_type,
                                                       container_path=container_path,
                                                       file_name=file_name)

410 411 412 413 414
  ##################################
  ##  Basic steps
  ##################################
  def stepCreatePerson(self, sequence=None, sequence_list=None, **kw):
    """
415
      Create a person with ID "john" if it does not exists already
416 417
    """
    portal_type = 'Person'
418
    person_id = 'john'
419
    reference = 'john_doe'
420
    person_module = self.portal.person_module
421 422 423 424 425 426
    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
427 428 429
                                      last_name='Doe',
                                      default_email_text='john@doe.com')
    self.stepTic()
430 431 432

  def stepCreateTextDocument(self, sequence=None, sequence_list=None, **kw):
    """
433 434
      Create an empty Text document with ID 'one'
      This document will be used in most tests.
435
    """
436
    self.newEmptyCataloggedDocument('Text', 'one')
437

438 439
  def stepCreateSpreadsheetDocument(self, sequence=None, sequence_list=None, **kw):
    """
440 441
      Create an empty Spreadsheet document with ID 'two'
      This document will be used in most tests.
442
    """
443
    self.newEmptyCataloggedDocument('Spreadsheet', 'two')
444 445 446

  def stepCreatePresentationDocument(self, sequence=None, sequence_list=None, **kw):
    """
447 448
      Create an empty Presentation document with ID 'three'
      This document will be used in most tests.
449
    """
450
    self.newEmptyCataloggedDocument('Presentation', 'three')
451 452 453

  def stepCreateDrawingDocument(self, sequence=None, sequence_list=None, **kw):
    """
454 455
      Create an empty Drawing document with ID 'four'
      This document will be used in most tests.
456
    """
457
    self.newEmptyCataloggedDocument('Drawing', 'four')
458

459 460
  def stepCreatePDFDocument(self, sequence=None, sequence_list=None, **kw):
    """
461 462
      Create an empty PDF document with ID 'five'
      This document will be used in most tests.
463
    """
464
    self.newEmptyCataloggedDocument('PDF', 'five')
465 466 467

  def stepCreateImageDocument(self, sequence=None, sequence_list=None, **kw):
    """
468 469
      Create an empty Image document with ID 'six'
      This document will be used in most tests.
470
    """
471
    self.newEmptyCataloggedDocument('Image', 'six')
472

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

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

489 490 491 492 493
  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)
    """
Ivan Tyagov's avatar
Ivan Tyagov committed
494 495
    document = self.getDocument('one')
    return self.assertEquals(document.getExternalProcessingState(), 'converting')
496

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

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

  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.
    """
Ivan Tyagov's avatar
Ivan Tyagov committed
550 551
    document = self.getDocument('one')
    revision = document.getRevision()
552
    number_of_document = len(self.portal.document_module.objectIds())
Ivan Tyagov's avatar
Ivan Tyagov committed
553
    self.assert_('This document is modified.' not in document.asText())
554 555 556 557 558

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

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

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

  def stepDiscoverFromFilename(self, sequence=None, sequence_list=None, **kw):
    """
582 583 584
      Upload a file using contribution tool. This should trigger metadata
      discovery and we should have basic coordinates immediately,
      from first stage.
585
    """
Ivan Tyagov's avatar
Ivan Tyagov committed
586
    document = self.getDocument('one')
587 588
    file_name = 'TEST-en-002.doc'
    # First make sure the regular expressions work
Ivan Tyagov's avatar
Ivan Tyagov committed
589
    property_dict = document.getPropertyDictFromFileName(file_name)
590 591 592 593 594
    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
595
    property_dict = document.getPropertyDictFromContent()
596 597 598 599 600
    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
    f = makeFileUpload(file_name)
Ivan Tyagov's avatar
Ivan Tyagov committed
601 602 603 604 605
    document.edit(file=f)
    self.assertEquals(document.getReference(), 'TEST')
    self.assertEquals(document.getLanguage(), 'en')
    self.assertEquals(document.getVersion(), '002')
    self.assertEquals(document.getSourceReference(), file_name)
606

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

619
  def stepSetSimulatedDiscoveryScript(self, sequence=None, sequence_list=None, **kw):
620 621 622 623
    """
      Create Text_getPropertyDictFrom[source] scripts
      to simulate custom site's configuration
    """
624 625 626
    self.newPythonScript('one', 'Text_getPropertyDictFromUserLogin',
                         'user_name=None', "return {'contributor':'person_module/john'}")
    self.newPythonScript('one', 'Text_getPropertyDictFromContent', '',
627
                         "return {'short_title':'short', 'title':'title', 'contributor':'person_module/john',}")
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
    """
Ivan Tyagov's avatar
Ivan Tyagov committed
634
    document = self.getDocument('one')
635
    f = makeFileUpload('TEST-en-002.doc')
Ivan Tyagov's avatar
Ivan Tyagov committed
636
    document.edit(file=f)
Ivan Tyagov's avatar
Ivan Tyagov committed
637
    self.stepTic()
638
    # Then make sure content discover works
Ivan Tyagov's avatar
Ivan Tyagov committed
639
    property_dict = document.getPropertyDictFromUserLogin()
640
    self.assertEquals(property_dict['contributor'], 'person_module/john')
641
    # reference from filename (the rest was checked some other place)
Ivan Tyagov's avatar
Ivan Tyagov committed
642
    self.assertEquals(document.getReference(), 'TEST')
643
    # short_title from content
Ivan Tyagov's avatar
Ivan Tyagov committed
644
    self.assertEquals(document.getShortTitle(), 'short')
645
    # title from metadata inside the document
Ivan Tyagov's avatar
Ivan Tyagov committed
646
    self.assertEquals(document.getTitle(),  'title')
647
    # contributors from user
Ivan Tyagov's avatar
Ivan Tyagov committed
648
    self.assertEquals(document.getContributor(), 'person_module/john')
649 650 651

  def stepEditMetadata(self, sequence=None, sequence_list=None, **kw):
    """
652
      we change metadata in a document which has ODF
653
    """
Ivan Tyagov's avatar
Ivan Tyagov committed
654
    document = self.getDocument('one')
655 656 657
    kw = dict(title='another title',
              subject='another subject',
              description='another description')
Ivan Tyagov's avatar
Ivan Tyagov committed
658
    document.edit(**kw)
Ivan Tyagov's avatar
Ivan Tyagov committed
659
    self.stepTic()
660 661 662 663 664 665 666 667

  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...
Ivan Tyagov's avatar
Ivan Tyagov committed
668 669
    document = self.getDocument('one')
    newcontent = document.getBaseData()
Nicolas Delaby's avatar
Nicolas Delaby committed
670 671 672 673 674
    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
675
    self.assertEquals(subject, u'another subject')
Nicolas Delaby's avatar
Nicolas Delaby committed
676
    description = xml_tree.find('*/{%s}description' % xml_tree.nsmap['dc']).text
677
    self.assertEquals(description, u'another description')
Nicolas Delaby's avatar
Nicolas Delaby committed
678

679 680 681 682 683
  def stepIngestTextFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported text formats
      make sure they are converted
    """
684 685
    format_list = ['rtf', 'doc', 'txt', 'sxw', 'sdw']
    self.ingestFormatList('one', format_list)
686 687 688 689 690 691

  def stepIngestSpreadsheetFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported spreadsheet formats
      make sure they are converted
    """
692 693
    format_list = ['xls', 'sxc', 'sdc']
    self.ingestFormatList('two', format_list)
694 695 696 697 698 699

  def stepIngestPresentationFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported presentation formats
      make sure they are converted
    """
700 701
    format_list = ['ppt', 'sxi', 'sdd']
    self.ingestFormatList('three', format_list)
702

703 704 705 706 707
  def stepIngestPDFFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported PDF formats
      make sure they are converted
    """
708 709
    format_list = ['pdf']
    self.ingestFormatList('five', format_list)
710

711 712 713 714 715
  def stepIngestDrawingFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported presentation formats
      make sure they are converted
    """
716
    format_list = ['sxd',]
717
    self.ingestFormatList('four', format_list)
718

719
  def stepIngestPDFFormats(self, sequence=None, sequence_list=None, **kw):
720
    """
721 722
      ingest all supported pdf formats
      make sure they are converted
723
    """
724 725
    format_list = ['pdf']
    self.ingestFormatList('five', format_list)
726 727 728 729 730

  def stepIngestImageFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported image formats
    """
731 732
    format_list = ['jpg', 'gif', 'bmp', 'png']
    self.ingestFormatList('six', format_list, 'Image')
733 734

  def stepCheckTextDocumentExportList(self, sequence=None, sequence_list=None, **kw):
735
    self.checkDocumentExportList('one', 'doc', ['pdf', 'doc', 'rtf', 'writer.html', 'txt'])
736 737

  def stepCheckSpreadsheetDocumentExportList(self, sequence=None, sequence_list=None, **kw):
738
    self.checkDocumentExportList('two', 'xls', ['csv', 'calc.html', 'xls', 'calc.pdf'])
739 740 741 742 743 744 745

  def stepCheckPresentationDocumentExportList(self, sequence=None, sequence_list=None, **kw):
    self.checkDocumentExportList('three', 'ppt', ['impr.pdf', 'ppt'])

  def stepCheckDrawingDocumentExportList(self, sequence=None, sequence_list=None, **kw):
    self.checkDocumentExportList('four', 'sxd', ['jpg', 'draw.pdf', 'svg'])

746
  def stepExportPDF(self, sequence=None, sequence_list=None, **kw):
747
    """
748
      Try to export PDF to text and HTML
749
    """
750
    document = self.getDocument('five')
751
    f = makeFileUpload('TEST-en-002.pdf')
752
    document.edit(file=f)
753 754 755 756 757 758
    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')
759 760

  def stepExportImage(self, sequence=None, sequence_list=None, **kw):
761 762 763 764 765
    """
      Don't see a way to test it here, Image.index_html makes heavy use 
      of REQUEST and RESPONSE, and the rest of the implementation is way down
      in Zope core
    """
766
    printAndLog('stepExportImage not implemented')
767

768 769 770 771 772
  def stepCleanUp(self, sequence=None, sequence_list=None, **kw):
    """
        Clean up DMS system from old content.
    """
    portal = self.getPortal()
773
    for module in (portal.document_module, portal.image_module, portal.document_ingestion_module):
774 775
      module.manage_delObjects(map(None, module.objectIds()))
    
Bartek Górny's avatar
Bartek Górny committed
776
  def stepContributeFileListWithType(self, sequence=None, sequence_list=None, **kw):
777 778 779 780
    """
      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
781
    self.contributeFileList(with_portal_type=True)
782

Bartek Górny's avatar
Bartek Górny committed
783
  def stepContributeFileListWithNoType(self, sequence=None, sequence_list=None, **kw):
784 785 786 787
    """
      Contribute all kinds of files
      let the system figure out portal type by itself
    """
Bartek Górny's avatar
Bartek Górny committed
788
    self.contributeFileList(with_portal_type=False)
789

790
  def stepSetSimulatedDiscoveryScriptForOrdering(self, sequence=None, sequence_list=None, **kw):
791 792 793 794 795 796 797 798 799 800
    """
      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
    """
801 802
    self.newPythonScript('one', 'Text_getPropertyDictFromUserLogin', 'user_name=None', "return {'reference':'USER', 'language':'us', 'contributor':'person_module/john'}")
    self.newPythonScript('one', 'Text_getPropertyDictFromContent', '', "return {'reference':'CONT', 'version':'003', 'contributor':'person_module/jack', 'short_title':'from_content'}")
803

Bartek Górny's avatar
Bartek Górny committed
804
  def stepCheckMetadataSettingOrderFICU(self, sequence=None, sequence_list=None, **kw):
805 806
    """
     This is the default
807
    """  
808
    expected_metadata = dict(reference='TEST', language='en', version='002', short_title='from_input', contributor='person_module/james')
809 810
    self.setDiscoveryOrder(['file_name', 'input', 'content', 'user_login'])
    self.discoverMetadata()
811
    self.checkMetadataOrder(expected_metadata)
812 813 814 815 816

  def stepCheckMetadataSettingOrderCUFI(self, sequence=None, sequence_list=None, **kw):
    """
     Content - User - Filename - Input
    """
817
    expected_metadata = dict(reference='CONT', language='us', version='003', short_title='from_content', contributor='person_module/jack')
818 819
    self.setDiscoveryOrder(['content', 'user_login', 'file_name', 'input'])
    self.discoverMetadata()
820
    self.checkMetadataOrder(expected_metadata)
821 822 823 824 825

  def stepCheckMetadataSettingOrderUIFC(self, sequence=None, sequence_list=None, **kw):
    """
     User - Input - Filename - Content
    """
826
    expected_metadata = dict(reference='USER', language='us', version='004', short_title='from_input', contributor='person_module/john')
827 828
    self.setDiscoveryOrder(['user_login', 'input', 'file_name', 'content'])
    self.discoverMetadata()
829
    self.checkMetadataOrder(expected_metadata)
830 831 832 833 834

  def stepCheckMetadataSettingOrderICUF(self, sequence=None, sequence_list=None, **kw):
    """
     Input - Content - User - Filename
    """
835
    expected_metadata = dict(reference='INPUT', language='in', version='004', short_title='from_input', contributor='person_module/james')
836 837
    self.setDiscoveryOrder(['input', 'content', 'user_login', 'file_name'])
    self.discoverMetadata()
838
    self.checkMetadataOrder(expected_metadata)
839 840 841 842 843

  def stepCheckMetadataSettingOrderUFCI(self, sequence=None, sequence_list=None, **kw):
    """
     User - Filename - Content - Input
    """
844
    expected_metadata = dict(reference='USER', language='us', version='002', short_title='from_content', contributor='person_module/john')
845 846
    self.setDiscoveryOrder(['user_login', 'file_name', 'content', 'input'])
    self.discoverMetadata()
847
    self.checkMetadataOrder(expected_metadata)
Ivan Tyagov's avatar
Ivan Tyagov committed
848 849
   
  def stepReceiveEmail(self, sequence=None, sequence_list=None, **kw):
850
    """
Ivan Tyagov's avatar
Ivan Tyagov committed
851
      Email was sent in by someone to ERP5.
852 853
    """
    f = open(makeFilePath('email_from.txt'))
854
    document = self.receiveEmail(f.read())
Ivan Tyagov's avatar
Ivan Tyagov committed
855
    self.stepTic()
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879

  def stepReceiveMultipleAttachmentsEmail(self, sequence=None, sequence_list=None, **kw):
    """
      Email was sent in by someone to ERP5.
    """
    f = open(makeFilePath('email_multiple_attachments.eml'))
    document = self.receiveEmail(f.read())
    self.stepTic()

  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):
880
    """
881
      Verify contributed for initial time document per email.
882
    """
883
    attachment_list, ingested_document = self.verifyEmailedDocument()
884
    self.assertEquals('1', ingested_document.getRevision())
885

886
  def stepVerifyEmailedDocumentMultipleContribution(self, sequence=None, sequence_list=None, **kw):
887
    """
888
      Verify contributed for multiple times document per email.
889
    """
890
    attachment_list, ingested_document = self.verifyEmailedDocument()
891
    self.assertTrue(ingested_document.getRevision() > '1')
892

893 894 895 896 897
  def playSequence(self, step_list, quiet):
    sequence_list = SequenceList()
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)
898

899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
  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)
924
      if ingested_document.isSupportBaseDataConversion():
925 926 927 928 929 930
        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
    
  def verifyEmailedDocument(self):
931
    """
932
      Basic checks for verifying a mailed-in document
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
    """
    # 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)
    
    # 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')
    self.assertEquals('MAIL-en-002.doc', ingested_document.getSourceReference())
    self.assertEquals('converted', ingested_document.getExternalProcessingState())
    self.assertTrue('magic' in ingested_document.asText())
    
    # check aggregate between 'Document Ingestion Message' and ingested document
    self.assertEquals(attachment_list[0], ingested_document)
    return attachment_list, ingested_document
    
959 960 961 962
  ##################################
  ##  Tests
  ##################################

963
  def test_01_PreferenceSetup(self, quiet=QUIET, run=RUN_ALL_TEST):
964 965 966
    """
      Make sure that preferences are set up properly and accessible
    """
967
    if not run: return
968 969
    if not quiet: printAndLog('test_01_PreferenceSetup')
    preference_tool = self.portal.portal_preferences
Nicolas Delaby's avatar
Nicolas Delaby committed
970 971 972
    conversion_dict = _getConversionServerDict()
    self.assertEquals(preference_tool.getPreferredOoodocServerAddress(), conversion_dict['hostname'])
    self.assertEquals(preference_tool.getPreferredOoodocServerPortNumber(), conversion_dict['port'])
973 974 975
    self.assertEquals(preference_tool.getPreferredDocumentFileNameRegularExpression(), FILE_NAME_REGULAR_EXPRESSION)
    self.assertEquals(preference_tool.getPreferredDocumentReferenceRegularExpression(), REFERENCE_REGULAR_EXPRESSION)
    
976
  def test_02_FileExtensionRegistry(self, quiet=QUIET, run=RUN_ALL_TEST):
977 978 979
    """
      check if we successfully imported registry
      and that it has all the entries we need
980
    """
981 982
    if not run: return
    if not quiet: printAndLog('test_02_FileExtensionRegistry')
983
    reg = self.portal.portal_contribution_registry
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
    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',
1001
            'sxd' : 'Drawing',
1002 1003 1004 1005
            'xxx' : 'File',
          }
    for type, portal_type in correct_type_mapping.items():
      file_name = 'aaa.' + type
1006 1007
      self.assertEquals(reg.findPortalTypeName(file_name, None, None),
                        portal_type)
1008

1009
  def test_03_TextDoc(self, quiet=QUIET, run=RUN_ALL_TEST):
1010
    """
1011
      Test basic behaviour of a document:
1012
      - create empty document
1013 1014 1015 1016 1017
      - 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
1018 1019
    """
    if not run: return
1020
    if not quiet: printAndLog('test_03_TextDoc')
1021 1022
    step_list = ['stepCleanUp'
                 ,'stepCreateTextDocument'
1023
                 ,'stepCheckEmptyState'
1024
                 ,'stepStraightUpload'
1025 1026
                 ,'stepCheckConvertingState'
                 ,'stepTic'
1027
                 ,'stepCheckConvertedState'
1028 1029 1030
                 ,'stepUploadFromViewForm'
                 ,'stepCheckConvertingState'
                 ,'stepTic'
1031 1032
                 ,'stepCheckConvertedState'
                ]
1033
    self.playSequence(step_list, quiet)
1034

1035
  def test_04_MetadataExtraction(self, quiet=QUIET, run=RUN_ALL_TEST):
1036 1037
    """
      Test metadata extraction from various sources:
1038 1039 1040 1041 1042
      - 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)
1043
      - from file metadata
1044 1045 1046 1047

      NOTE: metadata of document (title, subject, description)
      are no longer retrieved and set upon conversion
    """
1048
    if not run: return
1049
    if not quiet: printAndLog('test_04_MetadataExtraction')
1050
    step_list = [ 'stepCleanUp'
1051
                 ,'stepUploadTextFromContributionTool'
1052
                 ,'stepSetSimulatedDiscoveryScript'
1053
                 ,'stepTic'
1054 1055
                 ,'stepTestMetadataSetting'
                ]
1056
    self.playSequence(step_list, quiet)
1057

1058
  def test_041_MetadataEditing(self, quiet=QUIET, run=RUN_ALL_TEST):
1059 1060 1061 1062 1063 1064
    """
      Check metadata in the object and in the ODF document
      Edit metadata on the object
      Download ODF, make sure it is changed
    """
    if not run: return
1065
    if not quiet: printAndLog('test_04_MetadataEditing')
1066 1067
    step_list = [ 'stepCleanUp'
                 ,'stepCreateTextDocument'
1068 1069 1070 1071
                 ,'stepUploadFromViewForm'
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
1072 1073
                 ,'stepEditMetadata'
                 ,'stepCheckChangedMetadata'
1074
                ]
1075
    self.playSequence(step_list, quiet)
1076

1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
  #    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.

  def test_05_FormatIngestionText(self, quiet=QUIET, run=RUN_ALL_TEST):
1087 1088
    step_list = ['stepCleanUp'
                 ,'stepCreateTextDocument'
1089
                 ,'stepIngestTextFormats'
1090 1091 1092 1093 1094 1095 1096
                ]
    self.playSequence(step_list, quiet)

  def test_05_FormatIngestionSpreadSheet(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    if not quiet: printAndLog('test_05_FormatIngestion')
    step_list = ['stepCleanUp'
1097 1098
                 ,'stepCreateSpreadsheetDocument'
                 ,'stepIngestSpreadsheetFormats'
1099 1100 1101 1102 1103 1104 1105
                ]
    self.playSequence(step_list, quiet)

  def test_05_FormatIngestionPresentation(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    if not quiet: printAndLog('test_05_FormatIngestion')
    step_list = ['stepCleanUp'
1106 1107
                 ,'stepCreatePresentationDocument'
                 ,'stepIngestPresentationFormats'
1108 1109 1110 1111 1112 1113 1114
                ]
    self.playSequence(step_list, quiet)

  def test_05_FormatIngestionDrawing(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    if not quiet: printAndLog('test_05_FormatIngestion')
    step_list = ['stepCleanUp'
1115 1116
                 ,'stepCreateDrawingDocument'
                 ,'stepIngestDrawingFormats'
1117 1118 1119 1120 1121 1122 1123
                ]
    self.playSequence(step_list, quiet)

  def test_05_FormatIngestionPDF(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    if not quiet: printAndLog('test_05_FormatIngestion')
    step_list = ['stepCleanUp'
1124 1125
                 ,'stepCreatePDFDocument'
                 ,'stepIngestPDFFormats'
1126 1127 1128 1129 1130 1131 1132
                ]
    self.playSequence(step_list, quiet)

  def test_05_FormatIngestionImage(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    if not quiet: printAndLog('test_05_FormatIngestion')
    step_list = ['stepCleanUp'
1133 1134
                 ,'stepCreateImageDocument'
                 ,'stepIngestImageFormats'
1135
                ]
1136
    self.playSequence(step_list, quiet)
1137

1138 1139 1140 1141 1142 1143

  # 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
  def test_06_FormatGenerationText(self, quiet=QUIET, run=RUN_ALL_TEST):
1144
    if not run: return
1145
    if not quiet: printAndLog('test_06_FormatGeneration')
1146 1147
    step_list = [ 'stepCleanUp'
                 ,'stepCreateTextDocument'
1148
                 ,'stepCheckTextDocumentExportList'
1149 1150 1151 1152 1153 1154 1155
                ]
    self.playSequence(step_list, quiet)

  def test_06_FormatGenerationSpreadsheet(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    if not quiet: printAndLog('test_06_FormatGeneration')
    step_list = [ 'stepCleanUp'
1156 1157
                 ,'stepCreateSpreadsheetDocument'
                 ,'stepCheckSpreadsheetDocumentExportList'
1158 1159 1160 1161 1162 1163 1164
                ]
    self.playSequence(step_list, quiet)

  def test_06_FormatGenerationPresentation(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    if not quiet: printAndLog('test_06_FormatGeneration')
    step_list = [ 'stepCleanUp'
1165 1166
                 ,'stepCreatePresentationDocument'
                 ,'stepCheckPresentationDocumentExportList'
1167 1168 1169 1170 1171 1172 1173
                ]
    self.playSequence(step_list, quiet)

  def test_06_FormatGenerationDrawing(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    if not quiet: printAndLog('test_06_FormatGeneration')
    step_list = [ 'stepCleanUp'
1174 1175
                 ,'stepCreateDrawingDocument'
                 ,'stepCheckDrawingDocumentExportList'
1176 1177 1178 1179 1180 1181 1182
                ]
    self.playSequence(step_list, quiet)

  def test_06_FormatGenerationPdf(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    if not quiet: printAndLog('test_06_FormatGeneration')
    step_list = [ 'stepCleanUp'
1183 1184
                 ,'stepCreatePDFDocument'
                 ,'stepExportPDF'
1185
                 ,'stepTic'
1186 1187 1188 1189 1190 1191 1192
                ]
    self.playSequence(step_list, quiet)

  def test_06_FormatGenerationImage(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    if not quiet: printAndLog('test_06_FormatGeneration')
    step_list = [ 'stepCleanUp'
1193 1194
                 ,'stepCreateImageDocument'
                 ,'stepExportImage'
1195
                ]
1196
    self.playSequence(step_list, quiet)
1197 1198 1199

  def test_08_Cache(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
1200
      I don't know how to verify how cache works
1201 1202
    """

1203
  def test_09_Contribute(self, quiet=QUIET, run=RUN_ALL_TEST):
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
    """
      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
    """
    if not run: return
1214
    if not quiet: printAndLog('test_09_Contribute')
1215 1216
    step_list = [ 'stepCleanUp'
                 ,'stepContributeFileListWithNoType'
1217
                 ,'stepCleanUp'
Bartek Górny's avatar
Bartek Górny committed
1218
                 ,'stepContributeFileListWithType'
1219
                ]
1220
    self.playSequence(step_list, quiet)
1221 1222 1223

  def test_10_MetadataSettingPreferenceOrder(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
1224
      Set some metadata discovery scripts
1225
      Contribute a document, let it get metadata using default setup
1226 1227 1228
      (default is FUC)

      check that the right ones are there
1229 1230
      change preference order, check again
    """
1231
    if not run: return
1232
    if not quiet: printAndLog('test_10_MetadataSettingPreferenceOrder')
1233 1234
    step_list = [ 'stepCleanUp' 
                 ,'stepCreateTextDocument'
1235
                 ,'stepStraightUpload'
1236 1237 1238
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
1239
                 ,'stepSetSimulatedDiscoveryScriptForOrdering'
Bartek Górny's avatar
Bartek Górny committed
1240
                 ,'stepCheckMetadataSettingOrderFICU'
1241 1242
                 ,'stepCreateTextDocument'
                 ,'stepStraightUpload'
1243 1244 1245
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
1246
                 ,'stepSetSimulatedDiscoveryScriptForOrdering'
1247 1248 1249
                 ,'stepCheckMetadataSettingOrderCUFI'
                 ,'stepCreateTextDocument'
                 ,'stepStraightUpload'
1250 1251 1252
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
1253
                 ,'stepSetSimulatedDiscoveryScriptForOrdering'
1254 1255 1256
                 ,'stepCheckMetadataSettingOrderUIFC'
                 ,'stepCreateTextDocument'
                 ,'stepStraightUpload'
1257 1258 1259
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
1260
                 ,'stepSetSimulatedDiscoveryScriptForOrdering'
1261 1262 1263
                 ,'stepCheckMetadataSettingOrderICUF'
                 ,'stepCreateTextDocument'
                 ,'stepStraightUpload'
1264 1265 1266
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
1267
                 ,'stepSetSimulatedDiscoveryScriptForOrdering'
1268 1269
                 ,'stepCheckMetadataSettingOrderUFCI'
                ]
1270
    self.playSequence(step_list, quiet)
1271

1272 1273 1274 1275 1276 1277 1278
  def test_11_EmailIngestion(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
      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)
    """
    if not run: return
1279
    if not quiet: printAndLog('test_11_EmailIngestion')
1280
    step_list = [ 'stepCleanUp'
Ivan Tyagov's avatar
Ivan Tyagov committed
1281 1282 1283
                 # unknown sender
                 ,'stepReceiveEmail'
                 # create sender as Person object in ERP5
1284
                 ,'stepCreatePerson'
Ivan Tyagov's avatar
Ivan Tyagov committed
1285 1286
                 # now a known sender
                 ,'stepReceiveEmail'
1287
                 ,'stepVerifyEmailedDocumentInitialContribution'
1288 1289
                 # send one more time
                 ,'stepReceiveEmail'
1290 1291 1292 1293 1294 1295 1296
                 ,'stepVerifyEmailedDocumentMultipleContribution'
                 # send email with multiple attachments
                 ,'stepReceiveMultipleAttachmentsEmail'
                 ,'stepVerifyEmailedMultipleDocumentsInitialContribution'
                 # send email with multiple attachments one more time
                 ,'stepReceiveMultipleAttachmentsEmail'
                 ,'stepVerifyEmailedMultipleDocumentsMultipleContribution'
1297
                ]
1298
    self.playSequence(step_list, quiet)
1299

1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
  def test_12_UploadTextFromContributionTool(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
      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.
    """
    if not run: return
    if not quiet: printAndLog('test_12_ReUploadSameFilenameFile')
    step_list = [ 'stepCleanUp'
                 ,'stepUploadTextFromContributionTool'
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
                 ,'stepDiscoverFromFilename'
                 ,'stepTic'
                 ,'stepReuploadTextFromContributionTool'
                 ,'stepUploadAnotherTextFromContributionTool'
                ]
    self.playSequence(step_list, quiet)
1319

1320 1321 1322 1323 1324
  def stepUploadTextFromContributionToolWithNonASCIIFilename(self, 
                                 sequence=None, sequence_list=None, **kw):
    """
      Upload a file from contribution.
    """
1325
    f = makeFileUpload('TEST-en-002.doc', 'T&é@{T-en-002.doc')
1326 1327
    document = self.portal.portal_contributions.newContent(file=f)
    sequence.edit(document_id=document.getId())
1328
    transaction.commit()
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372

  def stepDiscoverFromFilenameWithNonASCIIFilename(self, 
                                 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.
    """
    context = self.getDocument(sequence.get('document_id'))
    file_name = 'T&é@{T-en-002.doc'
    # First make sure the regular expressions work
    property_dict = context.getPropertyDictFromFileName(file_name)
    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')
    self.assertEquals(context.getSourceReference(), file_name)

  def test_13_UploadTextFromContributionToolWithNonASCIIFilename(self, 
                                           quiet=QUIET, run=RUN_ALL_TEST):
    """
      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.
    """
    if not run: return
    if not quiet:
      printAndLog('test_13_UploadTextFromContributionToolWithNonASCIIFilename')
    step_list = [ 'stepCleanUp'
                 ,'stepUploadTextFromContributionToolWithNonASCIIFilename'
                 ,'stepTic'
                 ,'stepDiscoverFromFilenameWithNonASCIIFilename'
                ]
    self.playSequence(step_list, quiet)

1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
  def test_14_ContributionToolIndexation(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
    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()
Ivan Tyagov's avatar
Ivan Tyagov committed
1390
    self.stepTic()
1391 1392 1393
    self.assertEquals(1,
        len(portal.portal_catalog(path=contribution_tool.getPath())))

1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
  def test_15_TestFileNameDiscovery(self):
    """Test that filename is well set in source_reference
    - 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)
    self.assertEquals(document.getSourceReference(), 'TEST-en-002.doc')
    my_filename = 'Something.doc'
    document = contribution_tool.newContent(file=file_object,
                                            file_name=my_filename)
Ivan Tyagov's avatar
Ivan Tyagov committed
1407
    self.stepTic()
1408 1409
    self.assertEquals(document.getSourceReference(), my_filename)

1410 1411 1412 1413 1414 1415 1416 1417
  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')
1418 1419 1420 1421
    organisation = self.portal.organisation_module.newContent(**dict(group='anybody',
                                                                     site='site/arctic/spitsbergen'))
         
    user.setSubordinationValue(organisation)
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
    portal.document_module.manage_setLocalRoles('contributor1', ['Assignor',])
    self.stepTic()
    file_object = makeFileUpload('TEST-en-002.doc')
    document = contribution_tool.newContent(file=file_object)
    document.discoverMetadata(document.getSourceReference(), 'contributor1') 
    self.stepTic()
    self.assertEquals(document.getSourceReference(), 'TEST-en-002.doc')
    self.assertEquals('anybody', document.getGroup())
    self.assertEquals('site/arctic/spitsbergen', document.getSite())

1432 1433 1434
# Missing tests
"""
    property_dict = context.getPropertyDictFromInput()
1435
"""
Jérome Perrin's avatar
Jérome Perrin committed
1436 1437 1438 1439 1440

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