testIngestion.py 54.2 KB
Newer Older
1
##############################################################################
2
# -*- coding: utf-8 -*-
3
#
4 5 6
# Copyright (c) 2007 Nexedi SA and Contributors. All Rights Reserved.
#                    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
34
from xml.dom.minidom import parseString
35
import transaction
36 37
from Testing import ZopeTestCase
from DateTime import DateTime
38
from AccessControl.SecurityManagement import newSecurityManager
39 40 41
from Products.ERP5Type.Utils import convertToUpperCase
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Type.tests.Sequence import SequenceList
42
from Products.ERP5Type.tests.utils import FileUpload
43
from Products.ERP5OOo.Document.OOoDocument import ConversionError
44
from Products.ERP5.Document.File import _unpackData
45
from zLOG import LOG, INFO, ERROR
46

47 48
# Define the conversion server host
conversion_server_host = ('127.0.0.1', 8008)
49

50
# test files' home
51
TEST_FILES_HOME = os.path.join(os.path.dirname(__file__), 'test_document')
52 53
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}))?"
54

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

65 66

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

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

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

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

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

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

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

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

116 117 118
  def beforeTearDown(self):
    self.portal.portal_caches.clearAllCache()

119
  def setSystemPreference(self):
120
    default_pref = self.portal.portal_preferences.default_site_preference
121 122
    default_pref.setPreferredOoodocServerAddress(conversion_server_host[0])
    default_pref.setPreferredOoodocServerPortNumber(conversion_server_host[1])
123 124
    default_pref.setPreferredDocumentFileNameRegularExpression(FILE_NAME_REGULAR_EXPRESSION)
    default_pref.setPreferredDocumentReferenceRegularExpression(REFERENCE_REGULAR_EXPRESSION)
125 126
    default_pref.enable()

127 128 129 130 131 132 133 134 135 136 137 138
  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')

139 140 141 142 143 144 145
  def setTools(self):
    # XXX FIX ME
    # XXX We should use business template to install these tools.(Yusei)
    if getattr(self.portal, 'mimetypes_registry', None) is None:
      self.portal.manage_addProduct['MimetypesRegistry'].manage_addTool(type='MimeTypes Registry')
    if getattr(self.portal, 'portal_transforms', None) is None:
      self.portal.manage_addProduct['PortalTransforms'].manage_addTool(type='Portal Transforms')
146 147 148 149 150 151 152 153 154

  ##################################
  ##  Useful methods
  ##################################

  def login(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
      Create a new manager user and login.
    """
155
    user_name = 'dms_user'
156
    user_folder = self.portal.acl_users
157 158 159 160
    user_folder._doAddUser(user_name, '', ['Manager', 'Owner', 'Assignor'], [])
    user = user_folder.getUserById(user_name).__of__(user_folder)
    newSecurityManager(None, user)

161
  def createDefaultCategoryList(self):
162
    """
163 164 165 166 167 168
      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.
169 170 171 172 173 174
    """
    self.category_list = [
                         # Role categories
                          {'path' : 'role/internal'
                           ,'title': 'Internal'
                           }
175 176 177 178 179 180 181 182 183
                          ,{'path' : 'function/musician/wind/saxophone'
                           ,'title': 'Saxophone'
                           }
                          ,{'path' : 'group/medium'
                           ,'title': 'Medium'
                           }
                          ,{'path' : 'site/arctic/spitsbergen'
                           ,'title': 'Spitsbergen'
                           }
184 185 186
                          ,{'path' : 'group/anybody'
                           ,'title': 'Anybody'
                           }
187 188 189 190 191 192
                          ,{'path' : 'publication_section/cop'
                           ,'title': 'COPs'
                           }
                          ,{'path' : 'publication_section/cop/one'
                           ,'title': 'COP one'
                           }
193 194 195 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
                         ]

    # 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
                                    , immediate_reindex = 1
                                    )
          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'))
228
    transaction.commit()
229
    self.tic()
230 231 232 233 234 235

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

242
  def getDocument(self, id):
243 244 245 246 247 248
    """
      Returns a document with given ID in the
      document module.
    """
    document_module = self.portal.document_module
    return getattr(document_module, id)
249

250
  def checkIsObjectCatalogged(self, portal_type, **kw):
251
    """
252 253 254 255 256
      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.
257
    """
258
    res = self.portal_catalog(portal_type=portal_type, **kw.copy())
259
    self.assertEquals(len(res), 1)
260 261
    for key, value in kw.items():
      self.assertEquals(res[0].getProperty(key), value)
262

263
  def newEmptyCataloggedDocument(self, portal_type, id):
264
    """
265 266 267 268 269 270
      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.
271
    """
272 273 274 275 276 277
    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)
    document.reindexObject()
278
    transaction.commit()
279 280 281 282
    self.tic()
    self.checkIsObjectCatalogged(portal_type, id=id, parent_uid=document_module.getUid())
    self.assert_(hasattr(document_module, id))
    return document
283

284
  def ingestFormatList(self, document_id, format_list, portal_type=None):
285
    """
286 287 288 289 290 291 292 293 294
      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.
295 296
    """
    if portal_type is None:
297
      document_module = self.portal.document_module
298
    else:
299 300 301
      document_module = self.portal.getDefaultModule(portal_type)
    context = getattr(document_module, document_id)
    for revision, format in enumerate(format_list):
302
      filename = 'TEST-en-002.' + format
303
      printAndLog('Ingesting file: ' + filename)
304 305
      f = makeFileUpload(filename)
      context.edit(file=f)
306
      context.convertToBaseFormat()
307
      context.reindexObject()
308
      transaction.commit()
309
      self.tic()
310
      self.failUnless(context.hasFile())
311
      if context.getPortalType() in ('Image', 'File', 'PDF'):
312
        # File and images do not support conversion to text in DMS
313
        # PDF has not implemented _convertToBaseFormat() so can not be converted
314 315 316 317
        self.assertEquals(context.getExternalProcessingState(), 'uploaded')
      else:
        self.assertEquals(context.getExternalProcessingState(), 'converted') # this is how we know if it was ok or not
        self.assert_('magic' in context.SearchableText())
318
        self.assert_('magic' in str(context.asText()))
319

320
  def checkDocumentExportList(self, document_id, format, asserted_target_list):
321
    """
322 323 324
      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
325
    """
326
    context = self.getDocument(document_id)
327 328 329
    filename = 'TEST-en-002.' + format
    f = makeFileUpload(filename)
    context.edit(file=f)
330
    context.convertToBaseFormat()
331
    context.reindexObject()
332
    transaction.commit()
333
    self.tic()
334 335
    # We call clear cache to be sure that the target list is updated
    self.getPortal().portal_caches.clearCache()
336 337
    target_list = context.getTargetFormatList()
    for target in asserted_target_list:
338 339
      self.assert_(target in target_list)

Bartek Górny's avatar
Bartek Górny committed
340
  def contributeFileList(self, with_portal_type=False):
341
    """
342 343 344
      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
345 346
      on portal_contributions.
      http://framework.openoffice.org/documentation/mimetypes/mimetypes.html
347
    """
348 349 350 351
    created_documents = []
    extension_to_type = (('ppt', 'Presentation')
                        ,('doc', 'Text')
                        ,('sdc', 'Spreadsheet')
352
                        ,('sxc', 'Spreadsheet')
353 354 355 356
                        ,('pdf', 'PDF')
                        ,('jpg', 'Image')
                        ,('py', 'File')
                        )
357 358
    counter = 1
    old_portal_type = ''
359 360
    for extension, portal_type in extension_to_type:
      filename = 'TEST-en-002.' + extension
361
      printAndLog(filename)
362
      file = makeFileUpload(filename)
363 364 365 366 367 368 369
      # 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)
      printAndLog(file.filename)
370
      if with_portal_type:
371
        ob = self.portal.portal_contributions.newContent(portal_type=portal_type, file=file)
372 373
      else:
        ob = self.portal.portal_contributions.newContent(file=file)
374
      # reindex
375 376
      ob.immediateReindexObject()
      created_documents.append(ob)
377
    transaction.commit()
378 379 380 381 382 383
    self.tic()
    # inspect created objects
    count = 0
    for extension, portal_type in extension_to_type:
      ob = created_documents[count]
      count+=1
384
      self.assertEquals(ob.getPortalType(), portal_type)
385
      self.assertEquals(ob.getReference(), 'TEST')
386 387
      if ob.getPortalType() in ('Image', 'File', 'PDF'):
        # Image, File and PDF are not converted to a base format
388 389
        self.assertEquals(ob.getExternalProcessingState(), 'uploaded')
      else:
390 391 392
        # We check if conversion has succeeded by looking
        # at the external_processing workflow
        self.assertEquals(ob.getExternalProcessingState(), 'converted')
393
        self.assert_('magic' in ob.SearchableText())
394 395 396 397 398 399

  def newPythonScript(self, object_id, script_id, argument_list, code):
    """
      Creates a new python script with given argument_list
      and source code.
    """
400 401 402 403
    context = self.getDocument(object_id)
    factory = context.manage_addProduct['PythonScripts'].manage_addPythonScript
    factory(id=script_id)
    script = getattr(context, script_id)
404
    script.ZPythonScript_edit(argument_list, code)
405

406
  def setDiscoveryOrder(self, order, id='one'):
407
    """
408 409
      Creates a script to define the metadata discovery order
      for Text documents.
410 411
    """
    script_code = "return %s" % str(order)
412
    self.newPythonScript(id, 'Text_getPreferredDocumentMetadataDiscoveryOrderList', '', script_code)
413
    
414 415 416 417 418 419
  def discoverMetadata(self, document_id='one'):
    """
      Sets input parameters and on the document ID document_id
      and discover metadata. For reindexing
    """
    context = self.getDocument(document_id)
420 421 422 423 424
    # simulate user input
    context._backup_input = dict(reference='INPUT', 
                                 language='in',
                                 version='004', 
                                 short_title='from_input',
425
                                 contributor='person_module/james')
426 427
    # pass to discovery file_name and user_login
    context.discoverMetadata(context.getSourceReference(), 'john_doe') 
428
    context.reindexObject()
429
    transaction.commit()
430
    self.tic()
431

432 433 434 435 436 437 438
  def checkMetadataOrder(self, expected_metadata, document_id='one'):
    """
    Asserts that metadata of document ID document_id
    is the same as expected_metadata
    """
    context = self.getDocument(document_id)
    for k, v in expected_metadata.items():
439
      self.assertEquals(context.getProperty(k), v)
440

441 442 443 444 445 446 447 448 449
  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)

450 451 452
  ##################################
  ##  Basic steps
  ##################################
453 454 455
 
  def stepTic(self, sequence=None, sequence_list=None, **kw):
    self.tic()
456 457 458

  def stepCreatePerson(self, sequence=None, sequence_list=None, **kw):
    """
459
      Create a person with ID "john" if it does not exists already
460 461
    """
    portal_type = 'Person'
462
    person_id = 'john'
463
    reference = 'john_doe'
464
    person_module = self.portal.person_module
465 466 467 468 469 470 471 472
    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',
                                      last_name='Doe'
                                      )
473
    person.setDefaultEmailText('john@doe.com')
474
    person.reindexObject()
475
    transaction.commit()
476
    self.tic()
477 478 479

  def stepCreateTextDocument(self, sequence=None, sequence_list=None, **kw):
    """
480 481
      Create an empty Text document with ID 'one'
      This document will be used in most tests.
482
    """
483
    self.newEmptyCataloggedDocument('Text', 'one')
484

485 486
  def stepCreateSpreadsheetDocument(self, sequence=None, sequence_list=None, **kw):
    """
487 488
      Create an empty Spreadsheet document with ID 'two'
      This document will be used in most tests.
489
    """
490
    self.newEmptyCataloggedDocument('Spreadsheet', 'two')
491 492 493

  def stepCreatePresentationDocument(self, sequence=None, sequence_list=None, **kw):
    """
494 495
      Create an empty Presentation document with ID 'three'
      This document will be used in most tests.
496
    """
497
    self.newEmptyCataloggedDocument('Presentation', 'three')
498 499 500

  def stepCreateDrawingDocument(self, sequence=None, sequence_list=None, **kw):
    """
501 502
      Create an empty Drawing document with ID 'four'
      This document will be used in most tests.
503
    """
504
    self.newEmptyCataloggedDocument('Drawing', 'four')
505

506 507
  def stepCreatePDFDocument(self, sequence=None, sequence_list=None, **kw):
    """
508 509
      Create an empty PDF document with ID 'five'
      This document will be used in most tests.
510
    """
511
    self.newEmptyCataloggedDocument('PDF', 'five')
512 513 514

  def stepCreateImageDocument(self, sequence=None, sequence_list=None, **kw):
    """
515 516
      Create an empty Image document with ID 'six'
      This document will be used in most tests.
517
    """
518
    self.newEmptyCataloggedDocument('Image', 'six')
519

520 521
  def stepCheckEmptyState(self, sequence=None, sequence_list=None, **kw):
    """
522 523
      Check if the document is in "empty" processing state
      (ie. no file upload has been done yet)
524
    """
525
    context = self.getDocument('one')
526 527 528 529
    return self.assertEquals(context.getExternalProcessingState(), 'empty')

  def stepCheckUploadedState(self, sequence=None, sequence_list=None, **kw):
    """
530 531
      Check if the document is in "uploaded" processing state
      (ie. a file upload has been done)
532
    """
533
    context = self.getDocument('one')
534 535
    return self.assertEquals(context.getExternalProcessingState(), 'uploaded')

536 537 538 539 540 541 542 543
  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)
    """
    context = self.getDocument('one')
    return self.assertEquals(context.getExternalProcessingState(), 'converting')

544 545
  def stepCheckConvertedState(self, sequence=None, sequence_list=None, **kw):
    """
546
      Check if the document is in "converted" processing state
547
      (ie. a file conversion has been done and the document has
548
      been converted)
549
    """
550
    context = self.getDocument('one')
551 552
    return self.assertEquals(context.getExternalProcessingState(), 'converted')

553 554 555 556 557
  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
    """
558
    filename = 'TEST-en-002.doc'
559 560 561
    document = self.getDocument('one')
    # Revision is 0 before upload (revisions are strings)
    self.assertEquals(document.getRevision(), '0')
562
    f = makeFileUpload(filename)
563
    document.edit(file=f)
564 565
    # set source
    document.setSourceReference(filename)
566
    self.assert_(document.hasFile())
567 568
    # source_reference set to file name ?
    self.assertEquals(document.getSourceReference(), filename) 
569 570 571
    # Revision is 1 after upload (revisions are strings)
    self.assertEquals(document.getRevision(), '1')
    document.reindexObject()
572
    transaction.commit()
573

574
  def stepUploadFromViewForm(self, sequence=None, sequence_list=None, **kw):
575
    """
576
      Upload a file from view form and make sure this increases the revision
577
    """
578
    context = self.getDocument('one')
579
    f = makeFileUpload('TEST-en-002.doc')
580
    revision = context.getRevision()
581 582 583
    context.edit(file=f)
    self.assertEquals(context.getRevision(), str(int(revision) + 1))
    context.reindexObject()
584
    transaction.commit()
585 586 587 588 589 590 591

  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)
592
    transaction.commit()
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607

  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.
    """
    context = self.getDocument('one')
    revision = context.getRevision()
    number_of_document = len(self.portal.document_module.objectIds())
    self.assert_('This document is modified.' not in context.asText())

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

    self.portal.portal_contributions.newContent(file=f)
608
    transaction.commit()
609
    self.tic()
610
    transaction.commit()
611
    self.assertEquals(context.getRevision(), str(int(revision) + 1))
612 613 614 615
    self.assert_('This document is modified.' in context.asText())
    self.assertEquals(len(self.portal.document_module.objectIds()),
                      number_of_document)

616
    context.reindexObject()
617
    transaction.commit()
618 619 620 621 622 623 624 625

  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)

626
    transaction.commit()
627
    self.tic()
628
    transaction.commit()
629 630 631 632 633 634

    context = self.getDocument('two')
    self.assert_('This is a another very interesting document.' in context.asText())
    self.assertEquals(context.getReference(), 'ANOTHE')
    self.assertEquals(context.getVersion(), '001')
    self.assertEquals(context.getLanguage(), 'en')
635 636 637

  def stepDiscoverFromFilename(self, sequence=None, sequence_list=None, **kw):
    """
638 639 640
      Upload a file using contribution tool. This should trigger metadata
      discovery and we should have basic coordinates immediately,
      from first stage.
641
    """
642
    context = self.getDocument('one')
643 644 645 646 647 648 649 650 651 652 653 654 655 656
    file_name = 'TEST-en-002.doc'
    # First make sure the regular expressions work
    property_dict = context.getPropertyDictFromFileName(file_name)
    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
    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
    f = makeFileUpload(file_name)
657
    context.edit(file=f)
658 659 660
    self.assertEquals(context.getReference(), 'TEST')
    self.assertEquals(context.getLanguage(), 'en')
    self.assertEquals(context.getVersion(), '002')
661
    self.assertEquals(context.getSourceReference(), file_name)
662

663 664
  def stepCheckConvertedContent(self, sequence=None, sequence_list=None, **kw):
    """
665 666 667
      Check that the input file was successfully converted
      and that its SearchableText and asText contain
      the word "magic"
668 669
    """
    self.tic()
670
    context = self.getDocument('one')
671
    self.assert_(context.hasBaseData())
672
    self.assert_('magic' in context.SearchableText())
673
    self.assert_('magic' in str(context.asText()))
674

675
  def stepSetSimulatedDiscoveryScript(self, sequence=None, sequence_list=None, **kw):
676 677 678 679
    """
      Create Text_getPropertyDictFrom[source] scripts
      to simulate custom site's configuration
    """
680 681 682
    self.newPythonScript('one', 'Text_getPropertyDictFromUserLogin',
                         'user_name=None', "return {'contributor':'person_module/john'}")
    self.newPythonScript('one', 'Text_getPropertyDictFromContent', '',
683
                         "return {'short_title':'short', 'title':'title', 'contributor':'person_module/john',}")
684 685 686 687 688 689

  def stepTestMetadataSetting(self, sequence=None, sequence_list=None, **kw):
    """
      Upload with custom getPropertyDict methods
      check that all metadata are correct
    """
690
    context = self.getDocument('one')
691
    f = makeFileUpload('TEST-en-002.doc')
692
    context.edit(file=f)
693
    transaction.commit()
694
    self.tic()
695 696 697
    # Then make sure content discover works
    property_dict = context.getPropertyDictFromUserLogin()
    self.assertEquals(property_dict['contributor'], 'person_module/john')
698 699 700 701
    # reference from filename (the rest was checked some other place)
    self.assertEquals(context.getReference(), 'TEST')
    # short_title from content
    self.assertEquals(context.getShortTitle(), 'short')
702
    # title from metadata inside the document
703
    self.assertEquals(context.getTitle(),  'title')
704 705 706 707 708
    # contributors from user
    self.assertEquals(context.getContributor(), 'person_module/john')

  def stepEditMetadata(self, sequence=None, sequence_list=None, **kw):
    """
709
      we change metadata in a document which has ODF
710
    """
711
    context = self.getDocument('one')
712 713 714
    kw = dict(title='another title',
              subject='another subject',
              description='another description')
715
    context.edit(**kw)
716
    context.reindexObject(); transaction.commit();
Bartek Górny's avatar
Bartek Górny committed
717
    self.tic();
718 719 720 721 722 723 724 725

  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...
726
    context = self.getDocument('one')
Bartek Górny's avatar
Bartek Górny committed
727
    newcontent = context.getBaseData()
728
    cs = cStringIO.StringIO()
729
    cs.write(_unpackData(newcontent))
730 731 732 733 734
    z = zipfile.ZipFile(cs)
    s = z.read('meta.xml')
    xmlob = parseString(s)
    title = xmlob.getElementsByTagName('dc:title')[0].childNodes[0].data
    self.assertEquals(title, u'another title')
735
    subject = xmlob.getElementsByTagName('meta:keyword')[0].childNodes[0].data
736 737 738 739 740 741 742 743 744
    self.assertEquals(subject, u'another subject')
    description = xmlob.getElementsByTagName('dc:description')[0].childNodes[0].data
    self.assertEquals(description, u'another description')
    
  def stepIngestTextFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported text formats
      make sure they are converted
    """
745 746
    format_list = ['rtf', 'doc', 'txt', 'sxw', 'sdw']
    self.ingestFormatList('one', format_list)
747 748 749 750 751 752

  def stepIngestSpreadsheetFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported spreadsheet formats
      make sure they are converted
    """
753 754
    format_list = ['xls', 'sxc', 'sdc']
    self.ingestFormatList('two', format_list)
755 756 757 758 759 760

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

764 765 766 767 768
  def stepIngestPDFFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported PDF formats
      make sure they are converted
    """
769 770
    format_list = ['pdf']
    self.ingestFormatList('five', format_list)
771

772 773 774 775 776
  def stepIngestDrawingFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported presentation formats
      make sure they are converted
    """
777
    format_list = ['sxd',]
778
    self.ingestFormatList('four', format_list)
779

780
  def stepIngestPDFFormats(self, sequence=None, sequence_list=None, **kw):
781
    """
782 783
      ingest all supported pdf formats
      make sure they are converted
784
    """
785 786
    format_list = ['pdf']
    self.ingestFormatList('five', format_list)
787 788 789 790 791

  def stepIngestImageFormats(self, sequence=None, sequence_list=None, **kw):
    """
      ingest all supported image formats
    """
792 793
    format_list = ['jpg', 'gif', 'bmp', 'png']
    self.ingestFormatList('six', format_list, 'Image')
794 795

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

  def stepCheckSpreadsheetDocumentExportList(self, sequence=None, sequence_list=None, **kw):
799
    self.checkDocumentExportList('two', 'xls', ['csv', 'calc.html', 'xls', 'calc.pdf'])
800 801 802 803 804 805 806

  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'])

807
  def stepExportPDF(self, sequence=None, sequence_list=None, **kw):
808
    """
809
      Try to export PDF to text and HTML
810
    """
811
    document = self.getDocument('five')
812
    f = makeFileUpload('TEST-en-002.pdf')
813
    document.edit(file=f)
814 815 816 817 818 819
    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')
820 821

  def stepExportImage(self, sequence=None, sequence_list=None, **kw):
822 823 824 825 826
    """
      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
    """
827
    printAndLog('stepExportImage not implemented')
828

829
  def stepCheckHasSnapshot(self, sequence=None, sequence_list=None, **kw):
830
    context = self.getDocument('one')
Bartek Górny's avatar
Bartek Górny committed
831
    self.failUnless(context.hasSnapshotData())
832 833

  def stepCheckHasNoSnapshot(self, sequence=None, sequence_list=None, **kw):
834
    context = self.getDocument('one')
Bartek Górny's avatar
Bartek Górny committed
835
    self.failIf(context.hasSnapshotData())
836 837

  def stepCreateSnapshot(self, sequence=None, sequence_list=None, **kw):
838
    context = self.getDocument('one')
839 840 841
    context.createSnapshot()

  def stepTryRecreateSnapshot(self, sequence=None, sequence_list=None, **kw):
842
    context = self.getDocument('one')
843 844 845 846
    # XXX this always fails, don't know why
    #self.assertRaises(ConversionError, context.createSnapshot)

  def stepDeleteSnapshot(self, sequence=None, sequence_list=None, **kw):
847
    context = self.getDocument('one')
848 849
    context.deleteSnapshot()

850 851 852 853 854
  def stepCleanUp(self, sequence=None, sequence_list=None, **kw):
    """
        Clean up DMS system from old content.
    """
    portal = self.getPortal()
855
    for module in (portal.document_module, portal.image_module, portal.document_ingestion_module):
856 857
      module.manage_delObjects(map(None, module.objectIds()))
    
Bartek Górny's avatar
Bartek Górny committed
858
  def stepContributeFileListWithType(self, sequence=None, sequence_list=None, **kw):
859 860 861 862
    """
      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
863
    self.contributeFileList(with_portal_type=True)
864

Bartek Górny's avatar
Bartek Górny committed
865
  def stepContributeFileListWithNoType(self, sequence=None, sequence_list=None, **kw):
866 867 868 869
    """
      Contribute all kinds of files
      let the system figure out portal type by itself
    """
Bartek Górny's avatar
Bartek Górny committed
870
    self.contributeFileList(with_portal_type=False)
871

872
  def stepSetSimulatedDiscoveryScriptForOrdering(self, sequence=None, sequence_list=None, **kw):
873 874 875 876 877 878 879 880 881 882
    """
      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
    """
883 884
    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'}")
885

Bartek Górny's avatar
Bartek Górny committed
886
  def stepCheckMetadataSettingOrderFICU(self, sequence=None, sequence_list=None, **kw):
887 888
    """
     This is the default
889
    """  
890
    expected_metadata = dict(reference='TEST', language='en', version='002', short_title='from_input', contributor='person_module/james')
891 892
    self.setDiscoveryOrder(['file_name', 'input', 'content', 'user_login'])
    self.discoverMetadata()
893
    self.checkMetadataOrder(expected_metadata)
894 895 896 897 898

  def stepCheckMetadataSettingOrderCUFI(self, sequence=None, sequence_list=None, **kw):
    """
     Content - User - Filename - Input
    """
899
    expected_metadata = dict(reference='CONT', language='us', version='003', short_title='from_content', contributor='person_module/jack')
900 901
    self.setDiscoveryOrder(['content', 'user_login', 'file_name', 'input'])
    self.discoverMetadata()
902
    self.checkMetadataOrder(expected_metadata)
903 904 905 906 907

  def stepCheckMetadataSettingOrderUIFC(self, sequence=None, sequence_list=None, **kw):
    """
     User - Input - Filename - Content
    """
908
    expected_metadata = dict(reference='USER', language='us', version='004', short_title='from_input', contributor='person_module/john')
909 910
    self.setDiscoveryOrder(['user_login', 'input', 'file_name', 'content'])
    self.discoverMetadata()
911
    self.checkMetadataOrder(expected_metadata)
912 913 914 915 916

  def stepCheckMetadataSettingOrderICUF(self, sequence=None, sequence_list=None, **kw):
    """
     Input - Content - User - Filename
    """
917
    expected_metadata = dict(reference='INPUT', language='in', version='004', short_title='from_input', contributor='person_module/james')
918 919
    self.setDiscoveryOrder(['input', 'content', 'user_login', 'file_name'])
    self.discoverMetadata()
920
    self.checkMetadataOrder(expected_metadata)
921 922 923 924 925

  def stepCheckMetadataSettingOrderUFCI(self, sequence=None, sequence_list=None, **kw):
    """
     User - Filename - Content - Input
    """
926
    expected_metadata = dict(reference='USER', language='us', version='002', short_title='from_content', contributor='person_module/john')
927 928
    self.setDiscoveryOrder(['user_login', 'file_name', 'content', 'input'])
    self.discoverMetadata()
929
    self.checkMetadataOrder(expected_metadata)
930

931
  def stepReceiveEmailFromUnknown(self, sequence=None, sequence_list=None, **kw):
932 933 934 935
    """
      email was sent in by someone who is not in the person_module
    """
    f = open(makeFilePath('email_from.txt'))
936
    document = self.receiveEmail(data=f.read())
937
    transaction.commit()
938
    self.tic()
939 940

  def stepReceiveEmailFromJohn(self, sequence=None, sequence_list=None, **kw):
941 942 943 944
    """
      email was sent in by someone who is in the person_module
    """
    f = open(makeFilePath('email_from.txt'))
945
    document = self.receiveEmail(f.read())
946
    transaction.commit()
947
    self.tic()
948 949

  def stepVerifyEmailedDocuments(self, sequence=None, sequence_list=None, **kw):
950 951 952 953
    """
      find the newly mailed-in document by its reference
      check its properties
    """
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
    # First, check document ingestion message
    result = self.portal_catalog(portal_type='Document Ingestion Message',
                                 title='A Test Mail',
                                 source_title='John Doe'
                                 )
    self.assertEqual(len(result), 1)
    ingestion_message = result[0].getObject()

    # Second, check attachments
    attachment_list = ingestion_message.getAggregateValueList()
    self.assertEqual(len(attachment_list), 1)

    # Third, check document
    result = self.portal_catalog(portal_type='Text')
    self.assertEqual(len(result), 1)
    document = result[0].getObject()
    self.assertEqual(document.getRelativeUrl(), result[0].getRelativeUrl())

972

973 974 975 976 977
  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)
978
  
979 980 981 982
  ##################################
  ##  Tests
  ##################################

983
  def test_01_PreferenceSetup(self, quiet=QUIET, run=RUN_ALL_TEST):
984 985 986
    """
      Make sure that preferences are set up properly and accessible
    """
987
    if not run: return
988 989 990 991
    if not quiet: printAndLog('test_01_PreferenceSetup')
    preference_tool = self.portal.portal_preferences
    self.assertEquals(preference_tool.getPreferredOoodocServerAddress(), conversion_server_host[0])
    self.assertEquals(preference_tool.getPreferredOoodocServerPortNumber(), conversion_server_host[1])
992 993 994
    self.assertEquals(preference_tool.getPreferredDocumentFileNameRegularExpression(), FILE_NAME_REGULAR_EXPRESSION)
    self.assertEquals(preference_tool.getPreferredDocumentReferenceRegularExpression(), REFERENCE_REGULAR_EXPRESSION)
    
995
  def test_02_FileExtensionRegistry(self, quiet=QUIET, run=RUN_ALL_TEST):
996 997 998
    """
      check if we successfully imported registry
      and that it has all the entries we need
999
    """
1000 1001
    if not run: return
    if not quiet: printAndLog('test_02_FileExtensionRegistry')
1002
    reg = self.portal.portal_contribution_registry
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    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',
1020
            'sxd' : 'Drawing',
1021 1022 1023 1024
            'xxx' : 'File',
          }
    for type, portal_type in correct_type_mapping.items():
      file_name = 'aaa.' + type
1025 1026
      self.assertEquals(reg.findPortalTypeName(file_name, None, None),
                        portal_type)
1027

1028
  def test_03_TextDoc(self, quiet=QUIET, run=RUN_ALL_TEST):
1029
    """
1030
      Test basic behaviour of a document:
1031
      - create empty document
1032 1033 1034 1035 1036
      - 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
1037 1038
    """
    if not run: return
1039
    if not quiet: printAndLog('test_03_TextDoc')
1040 1041
    step_list = ['stepCleanUp'
                 ,'stepCreateTextDocument'
1042
                 ,'stepCheckEmptyState'
1043
                 ,'stepStraightUpload'
1044 1045
                 ,'stepCheckConvertingState'
                 ,'stepTic'
1046
                 ,'stepCheckConvertedState'
1047 1048 1049
                 ,'stepUploadFromViewForm'
                 ,'stepCheckConvertingState'
                 ,'stepTic'
1050 1051
                 ,'stepCheckConvertedState'
                ]
1052
    self.playSequence(step_list, quiet)
1053

1054
  def test_04_MetadataExtraction(self, quiet=QUIET, run=RUN_ALL_TEST):
1055 1056
    """
      Test metadata extraction from various sources:
1057 1058 1059 1060 1061
      - 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)
1062
      - from file metadata
1063 1064 1065 1066

      NOTE: metadata of document (title, subject, description)
      are no longer retrieved and set upon conversion
    """
1067
    if not run: return
1068
    if not quiet: printAndLog('test_04_MetadataExtraction')
1069
    step_list = [ 'stepCleanUp'
1070
                 ,'stepUploadTextFromContributionTool'
1071
                 ,'stepSetSimulatedDiscoveryScript'
1072
                 ,'stepTic'
1073 1074
                 ,'stepTestMetadataSetting'
                ]
1075
    self.playSequence(step_list, quiet)
1076

1077
  def test_041_MetadataEditing(self, quiet=QUIET, run=RUN_ALL_TEST):
1078 1079 1080 1081 1082 1083
    """
      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
1084
    if not quiet: printAndLog('test_04_MetadataEditing')
1085 1086
    step_list = [ 'stepCleanUp'
                 ,'stepCreateTextDocument'
1087 1088 1089 1090
                 ,'stepUploadFromViewForm'
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
1091 1092
                 ,'stepEditMetadata'
                 ,'stepCheckChangedMetadata'
1093
                ]
1094
    self.playSequence(step_list, quiet)
1095

1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107


  #    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):
1108 1109
    step_list = ['stepCleanUp'
                 ,'stepCreateTextDocument'
1110
                 ,'stepIngestTextFormats'
1111 1112 1113 1114 1115 1116 1117
                ]
    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'
1118 1119
                 ,'stepCreateSpreadsheetDocument'
                 ,'stepIngestSpreadsheetFormats'
1120 1121 1122 1123 1124 1125 1126
                ]
    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'
1127 1128
                 ,'stepCreatePresentationDocument'
                 ,'stepIngestPresentationFormats'
1129 1130 1131 1132 1133 1134 1135
                ]
    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'
1136 1137
                 ,'stepCreateDrawingDocument'
                 ,'stepIngestDrawingFormats'
1138 1139 1140 1141 1142 1143 1144
                ]
    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'
1145 1146
                 ,'stepCreatePDFDocument'
                 ,'stepIngestPDFFormats'
1147 1148 1149 1150 1151 1152 1153
                ]
    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'
1154 1155
                 ,'stepCreateImageDocument'
                 ,'stepIngestImageFormats'
1156
                ]
1157
    self.playSequence(step_list, quiet)
1158

1159 1160 1161 1162 1163 1164

  # 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):
1165
    if not run: return
1166
    if not quiet: printAndLog('test_06_FormatGeneration')
1167 1168
    step_list = [ 'stepCleanUp'
                 ,'stepCreateTextDocument'
1169
                 ,'stepCheckTextDocumentExportList'
1170 1171 1172 1173 1174 1175 1176
                ]
    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'
1177 1178
                 ,'stepCreateSpreadsheetDocument'
                 ,'stepCheckSpreadsheetDocumentExportList'
1179 1180 1181 1182 1183 1184 1185
                ]
    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'
1186 1187
                 ,'stepCreatePresentationDocument'
                 ,'stepCheckPresentationDocumentExportList'
1188 1189 1190 1191 1192 1193 1194
                ]
    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'
1195 1196
                 ,'stepCreateDrawingDocument'
                 ,'stepCheckDrawingDocumentExportList'
1197 1198 1199 1200 1201 1202 1203
                ]
    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'
1204 1205
                 ,'stepCreatePDFDocument'
                 ,'stepExportPDF'
1206 1207 1208 1209 1210 1211 1212
                ]
    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'
1213 1214
                 ,'stepCreateImageDocument'
                 ,'stepExportImage'
1215
                ]
1216
    self.playSequence(step_list, quiet)
1217

1218

1219 1220 1221 1222 1223 1224 1225
  def test_07_SnapshotGeneration(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
      Generate snapshot, make sure it is there, 
      try to generate it again, remove and 
      generate once more
    """
    if not run: return
1226
    if not quiet: printAndLog('test_07_SnapshotGeneration')
1227 1228
    step_list = [ 'stepCleanUp'
                 ,'stepCreateTextDocument'
1229 1230 1231 1232
                 ,'stepUploadFromViewForm'
                 ,'stepCheckConvertingState'
                 ,'stepTic'
                 ,'stepCheckConvertedState'
1233 1234 1235 1236 1237 1238 1239 1240
                 ,'stepCheckHasNoSnapshot'
                 ,'stepCreateSnapshot'
                 ,'stepTryRecreateSnapshot'
                 ,'stepCheckHasSnapshot'
                 ,'stepDeleteSnapshot'
                 ,'stepCheckHasNoSnapshot'
                 ,'stepCreateSnapshot'
                ]
1241
    self.playSequence(step_list, quiet)
1242

1243 1244
  def test_08_Cache(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
1245
      I don't know how to verify how cache works
1246 1247
    """

1248
  def test_09_Contribute(self, quiet=QUIET, run=RUN_ALL_TEST):
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
    """
      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
1259
    if not quiet: printAndLog('test_09_Contribute')
1260 1261
    step_list = [ 'stepCleanUp'
                 ,'stepContributeFileListWithNoType'
1262
                 ,'stepCleanUp'
Bartek Górny's avatar
Bartek Górny committed
1263
                 ,'stepContributeFileListWithType'
1264
                ]
1265
    self.playSequence(step_list, quiet)
1266 1267 1268

  def test_10_MetadataSettingPreferenceOrder(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
1269
      Set some metadata discovery scripts
1270
      Contribute a document, let it get metadata using default setup
1271 1272 1273
      (default is FUC)

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

1317 1318 1319 1320 1321 1322 1323
  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
1324
    if not quiet: printAndLog('test_11_EmailIngestion')
1325 1326
    step_list = [ 'stepCleanUp'
                 ,'stepReceiveEmailFromUnknown'
1327 1328 1329 1330
                 ,'stepCreatePerson'
                 ,'stepReceiveEmailFromJohn'
                 ,'stepVerifyEmailedDocuments'
                ]
1331
    self.playSequence(step_list, quiet)
1332

1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
  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)
1352

1353 1354 1355 1356 1357
  def stepUploadTextFromContributionToolWithNonASCIIFilename(self, 
                                 sequence=None, sequence_list=None, **kw):
    """
      Upload a file from contribution.
    """
1358
    f = makeFileUpload('TEST-en-002.doc', 'T&é@{T-en-002.doc')
1359 1360
    document = self.portal.portal_contributions.newContent(file=f)
    sequence.edit(document_id=document.getId())
1361
    transaction.commit()
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405

  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)

1406 1407 1408 1409
# Missing tests
"""
    property_dict = context.getPropertyDictFromUserLogin()
    property_dict = context.getPropertyDictFromInput()
1410
"""
Jérome Perrin's avatar
Jérome Perrin committed
1411 1412 1413 1414 1415

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