testDms.py 38.8 KB
Newer Older
1
# -*- coding: utf-8 -*-
Bartek Górny's avatar
Bartek Górny committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
##############################################################################
#
# Copyright (c) 2004 Nexedi SARL and Contributors. All Rights Reserved.
#          Sebastien Robin <seb@nexedi.com>
#
# 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.
#
##############################################################################

30 31 32
"""
  A test suite for Document Management System functionality.
  This will test:
Bartek Górny's avatar
Bartek Górny committed
33
  - creating Text Document objects
34 35 36 37 38 39 40 41 42 43 44 45 46
  - setting properties of a document, assigning local roles
  - setting relations between documents (explicit and implicity)
  - searching in basic and advanced modes
  - document publication workflow settings
  - sourcing external content
  - (...)
  This will NOT test:
  - contributing files of various types
  - convertion between many formats
  - metadata extraction and editing
  - email ingestion
  These are subject to another suite "testIngestion".
"""
Bartek Górny's avatar
Bartek Górny committed
47

48
import unittest
49
import time
50 51
import StringIO
from cgi import FieldStorage
Bartek Górny's avatar
Bartek Górny committed
52

53
import ZPublisher.HTTPRequest
54
import transaction
Bartek Górny's avatar
Bartek Górny committed
55 56
from Testing import ZopeTestCase
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
57
from Products.ERP5Type.tests.utils import FileUpload
58
from Products.ERP5Type.tests.utils import DummyLocalizer
Jérome Perrin's avatar
Jérome Perrin committed
59
from AccessControl.SecurityManagement import newSecurityManager
Bartek Górny's avatar
Bartek Górny committed
60
from zLOG import LOG
61
from Products.ERP5.Document.Document import NotConvertedError
Bartek Górny's avatar
Bartek Górny committed
62 63
import os

Bartek Górny's avatar
Bartek Górny committed
64
QUIET = 0
65
RUN_ALL_TEST = 1
Bartek Górny's avatar
Bartek Górny committed
66 67 68 69

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

70
TEST_FILES_HOME = os.path.join(os.path.dirname(__file__), 'test_document')
71 72
FILE_NAME_REGULAR_EXPRESSION = "(?P<reference>[A-Z]{3,10})-(?P<language>[a-z]{2})-(?P<version>[0-9]{3})"
REFERENCE_REGULAR_EXPRESSION = "(?P<reference>[A-Z]{3,10})(-(?P<language>[a-z]{2}))?(-(?P<version>[0-9]{3}))?"
73

Bartek Górny's avatar
Bartek Górny committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87

def printAndLog(msg):
  """
  A utility function to print a message
  to the standard output and to the LOG
  at the same time
  """
  if not QUIET:
    msg = str(msg)
    ZopeTestCase._print('\n ' + msg)
    LOG('Testing... ', 0, msg)


def makeFilePath(name):
88
  return os.path.join(os.path.dirname(__file__), 'test_document', name)
Bartek Górny's avatar
Bartek Górny committed
89

90 91 92 93 94
def makeFileUpload(name, as_name=None):
  if as_name is None:
    as_name = name
  path = makeFilePath(name)
  return FileUpload(path, as_name)
Bartek Górny's avatar
Bartek Górny committed
95

96

97
class TestDocument(ERP5TypeTestCase, ZopeTestCase.Functional):
98 99 100
  """
    Test basic document - related operations
  """
Bartek Górny's avatar
Bartek Górny committed
101 102 103 104

  def getTitle(self):
    return "DMS"

105 106
  ## setup

107
  def setUpOnce(self):
108
    self.setSystemPreference()
109 110
    # set a dummy localizer (because normally it is cookie based)
    self.portal.Localizer = DummyLocalizer()
111 112 113 114
    # make sure every body can traverse document module
    self.portal.document_module.manage_permission('View', ['Anonymous'], 1)
    self.portal.document_module.manage_permission(
                           'Access contents information', ['Anonymous'], 1)
Bartek Górny's avatar
Bartek Górny committed
115

116
  def setSystemPreference(self):
Ivan Tyagov's avatar
Ivan Tyagov committed
117
    default_pref = self.portal.portal_preferences.newContent(portal_type='System Preference')
118
    default_pref.setPriority(1)
119 120 121 122
    default_pref.setPreferredOoodocServerAddress(conversion_server_host[0])
    default_pref.setPreferredOoodocServerPortNumber(conversion_server_host[1])
    default_pref.setPreferredDocumentFileNameRegularExpression(FILE_NAME_REGULAR_EXPRESSION)
    default_pref.setPreferredDocumentReferenceRegularExpression(REFERENCE_REGULAR_EXPRESSION)
123 124
    if default_pref.getPreferenceState() != 'global':
      default_pref.enable()
125
    transaction.commit()
Ivan Tyagov's avatar
Ivan Tyagov committed
126
    self.tic()
127

Bartek Górny's avatar
Bartek Górny committed
128 129 130 131
  def getDocumentModule(self):
    return getattr(self.getPortal(),'document_module')

  def getBusinessTemplateList(self):
132 133
    return ('erp5_base',
            'erp5_ingestion', 'erp5_ingestion_mysql_innodb_catalog',
134
            'erp5_web', 'erp5_dms')
Bartek Górny's avatar
Bartek Górny committed
135 136

  def getNeededCategoryList(self):
137
    return ()
Bartek Górny's avatar
Bartek Górny committed
138

139
  def beforeTearDown(self):
140 141 142 143
    """
      Do some stuff after each test:
      - clear document module
    """
144 145 146 147 148 149 150 151
    transaction.abort()
    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
152
    self.clearDocumentModule()
153

154
  def clearDocumentModule(self):
Bartek Górny's avatar
Bartek Górny committed
155
    """
156
      Remove everything after each run
Bartek Górny's avatar
Bartek Górny committed
157
    """
158
    doc_module = self.getDocumentModule()
159
    doc_module.manage_delObjects(list(doc_module.objectIds()))
160
    transaction.commit()
161 162 163
    self.tic()

  ## helper methods
Bartek Górny's avatar
Bartek Górny committed
164

165
  def createTestDocument(self, file_name=None, portal_type='Text', reference='TEST', version='002', language='en'):
Bartek Górny's avatar
Bartek Górny committed
166 167 168
    """
      Creates a text document
    """
169
    dm=self.getPortal().document_module
170
    doctext=dm.newContent(portal_type=portal_type)
Bartek Górny's avatar
Bartek Górny committed
171
    if file_name is not None:
172
      f = open(makeFilePath(file_name), 'rb')
Bartek Górny's avatar
Bartek Górny committed
173 174 175 176 177
      doctext.setTextContent(f.read())
      f.close()
    doctext.setReference(reference)
    doctext.setVersion(version)
    doctext.setLanguage(language)
178
    return doctext
Bartek Górny's avatar
Bartek Górny committed
179

Bartek Górny's avatar
Bartek Górny committed
180 181 182 183 184 185 186 187
  def getDocument(self, id):
    """
      Returns a document with given ID in the
      document module.
    """
    document_module = self.portal.document_module
    return getattr(document_module, id)

188 189 190
  def clearCache(self):
    self.portal.portal_caches.clearAllCache()

191 192
  ## tests

Bartek Górny's avatar
Bartek Górny committed
193 194 195 196
  def test_01_HasEverything(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
      Standard test to make sure we have everything we need - all the tools etc
    """
197
    if not run: return
Bartek Górny's avatar
Bartek Górny committed
198
    printAndLog('\nTest Has Everything ')
199 200 201 202 203 204
    self.assertNotEqual(self.getCategoryTool(), None)
    self.assertNotEqual(self.getSimulationTool(), None)
    self.assertNotEqual(self.getTypeTool(), None)
    self.assertNotEqual(self.getSQLConnection(), None)
    self.assertNotEqual(self.getCatalogTool(), None)
    self.assertNotEqual(self.getWorkflowTool(), None)
205

206
  def test_02_RevisionSystem(self,quiet=QUIET,run=RUN_ALL_TEST):
Bartek Górny's avatar
Bartek Górny committed
207 208 209 210 211 212
    """
      Test revision mechanism
    """
    if not run: return
    printAndLog('\nTest Revision System')
    # create a test document
213
    # revision should be 1
Bartek Górny's avatar
Bartek Górny committed
214
    # upload file (can be the same) into it
215
    # revision should now be 2
216 217
    # edit the document with any value or no values
    # revision should now be 3
Bartek Górny's avatar
Bartek Górny committed
218
    # contribute the same file through portal_contributions
219 220
    # the same document should now have revision 4 (because it should have done mergeRevision)
    # getRevisionList should return (1, 2, 3, 4)
221 222 223 224
    filename = 'TEST-en-002.doc'
    file = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=file)
    document.immediateReindexObject()
225
    transaction.commit()
226 227 228 229
    self.tic()
    document_url = document.getRelativeUrl()
    def getTestDocument():
      return self.portal.restrictedTraverse(document_url)
230
    self.assertEqual(getTestDocument().getRevision(), '1')
231
    getTestDocument().edit(file=file)
232
    transaction.commit()
233
    self.tic()
234
    self.assertEqual(getTestDocument().getRevision(), '2')
235
    getTestDocument().edit(title='Hey Joe')
236
    transaction.commit()
237
    self.tic()
238
    self.assertEqual(getTestDocument().getRevision(), '3')
239
    another_document = self.portal.portal_contributions.newContent(file=file)
240
    transaction.commit()
241
    self.tic()
242 243
    self.assertEqual(getTestDocument().getRevision(), '4')
    self.assertEqual(getTestDocument().getRevisionList(), ['1', '2', '3', '4'])
Bartek Górny's avatar
Bartek Górny committed
244 245 246 247 248 249 250

  def test_03_Versioning(self,quiet=QUIET,run=RUN_ALL_TEST):
    """
      Test versioning
    """
    if not run: return
    printAndLog('\nTest Versioning System')
251 252 253 254 255 256 257 258 259 260 261 262 263 264
    # create a document 1, set coordinates (reference=TEST, version=002, language=en)
    # create a document 2, set coordinates (reference=TEST, version=002, language=en)
    # create a document 3, set coordinates (reference=TEST, version=004, language=en)
    # run isVersionUnique on 1, 2, 3 (should return False, False, True)
    # change version of 2 to 003
    # run isVersionUnique on 1, 2, 3  (should return True)
    # run getLatestVersionValue on all (should return 3)
    # run getVersionValueList on 2 (should return [3, 2, 1])
    document_module = self.getDocumentModule()
    docs = {}
    docs[1] = self.createTestDocument(reference='TEST', version='002', language='en')
    docs[2] = self.createTestDocument(reference='TEST', version='002', language='en')
    docs[3] = self.createTestDocument(reference='TEST', version='004', language='en')
    docs[4] = self.createTestDocument(reference='ANOTHER', version='002', language='en')
265
    transaction.commit()
266 267 268 269 270
    self.tic()
    self.failIf(docs[1].isVersionUnique())
    self.failIf(docs[2].isVersionUnique())
    self.failUnless(docs[3].isVersionUnique())
    docs[2].setVersion('003')
271
    transaction.commit()
272 273 274 275 276 277 278 279 280
    self.tic()
    self.failUnless(docs[1].isVersionUnique())
    self.failUnless(docs[2].isVersionUnique())
    self.failUnless(docs[3].isVersionUnique())
    self.failUnless(docs[1].getLatestVersionValue() == docs[3])
    self.failUnless(docs[2].getLatestVersionValue() == docs[3])
    self.failUnless(docs[3].getLatestVersionValue() == docs[3])
    version_list = [br.getRelativeUrl() for br in docs[2].getVersionValueList()]
    self.failUnless(version_list == [docs[3].getRelativeUrl(), docs[2].getRelativeUrl(), docs[1].getRelativeUrl()])
Bartek Górny's avatar
Bartek Górny committed
281 282 283 284 285 286 287 288 289 290 291 292 293

  def test_04_VersioningWithLanguage(self,quiet=QUIET,run=RUN_ALL_TEST):
    """
      Test versioning with multi-language support
    """
    if not run: return
    printAndLog('\nTest Versioning With Language')
    # create empty test documents, set their coordinates as follows:
    # (1) TEST, 002, en
    # (2) TEST, 002, fr
    # (3) TEST, 002, pl
    # (4) TEST, 003, en
    # (5) TEST, 003, sp
294
    # the following calls (on any doc) should produce the following output:
Bartek Górny's avatar
Bartek Górny committed
295 296 297 298 299 300 301
    # getOriginalLanguage() = 'en'
    # getLanguageList = ('en', 'fr', 'pl', 'sp')
    # getLatestVersionValue() = 4
    # getLatestVersionValue('en') = 4
    # getLatestVersionValue('fr') = 2
    # getLatestVersionValue('pl') = 3
    # getLatestVersionValue('ru') = None
302
    # change user language into 'sp'
Bartek Górny's avatar
Bartek Górny committed
303
    # getLatestVersionValue() = 5
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    # add documents:
    # (6) TEST, 004, pl
    # (7) TEST, 004, en
    # getLatestVersionValue() = 7
    localizer = self.portal.Localizer
    document_module = self.getDocumentModule()
    docs = {}
    docs[1] = self.createTestDocument(reference='TEST', version='002', language='en')
    time.sleep(1) # time span here because catalog records only full seconds
    docs[2] = self.createTestDocument(reference='TEST', version='002', language='fr')
    time.sleep(1)
    docs[3] = self.createTestDocument(reference='TEST', version='002', language='pl')
    time.sleep(1)
    docs[4] = self.createTestDocument(reference='TEST', version='003', language='en')
    time.sleep(1)
    docs[5] = self.createTestDocument(reference='TEST', version='003', language='sp')
    time.sleep(1)
321
    transaction.commit()
322 323 324 325 326 327 328 329 330 331 332 333 334
    self.tic()
    doc = docs[2] # can be any
    self.failUnless(doc.getOriginalLanguage() == 'en')
    self.failUnless(doc.getLanguageList() == ['en', 'fr', 'pl', 'sp'])
    self.failUnless(doc.getLatestVersionValue() == docs[4]) # there are two latest - it chooses the one in user language
    self.failUnless(doc.getLatestVersionValue('en') == docs[4])
    self.failUnless(doc.getLatestVersionValue('fr') == docs[2])
    self.failUnless(doc.getLatestVersionValue('pl') == docs[3])
    self.failUnless(doc.getLatestVersionValue('ru') == None)
    localizer.changeLanguage('sp') # change user language
    self.failUnless(doc.getLatestVersionValue() == docs[5]) # there are two latest - it chooses the one in user language
    docs[6] = document_module.newContent(reference='TEST', version='004', language='pl')
    docs[7] = document_module.newContent(reference='TEST', version='004', language='en')
335
    transaction.commit()
336 337
    self.tic()
    self.failUnless(doc.getLatestVersionValue() == docs[7]) # there are two latest, neither in user language - it chooses the one in original language
Bartek Górny's avatar
Bartek Górny committed
338

339
  def test_06_testExplicitRelations(self,quiet=QUIET,run=RUN_ALL_TEST):
Bartek Górny's avatar
Bartek Górny committed
340 341 342 343 344 345
    """
      Test explicit relations.
      Explicit relations are just like any other relation, so no need to test them here
      except for similarity cloud which we test.
    """
    if not run: return
346
    
Bartek Górny's avatar
Bartek Górny committed
347 348 349 350 351 352 353 354
    printAndLog('\nTest Explicit Relations')
    # create test documents:
    # (1) TEST, 002, en
    # (2) TEST, 003, en
    # (3) ONE, 001, en
    # (4) TWO, 001, en
    # (5) THREE, 001, en
    # set 3 similar to 1, 4 to 3, 5 to 4
Romain Courteaud's avatar
Romain Courteaud committed
355
    # getSimilarCloudValueList on 4 should return 1, 3 and 5
Bartek Górny's avatar
Bartek Górny committed
356
    # getSimilarCloudValueList(depth=1) on 4 should return 3 and 5
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    
    # create documents for test version and language
    # reference, version, language
    kw = {'portal_type': 'Drawing'}
    document1 = self.portal.document_module.newContent(**kw)
    document2 = self.portal.document_module.newContent(**kw)
    document3 = self.portal.document_module.newContent(**kw)
    document4 = self.portal.document_module.newContent(**kw)
    document5 = self.portal.document_module.newContent(**kw)
    
    document6 = self.portal.document_module.newContent(reference='SIX', version='001', 
                                                                                    language='en',  **kw)
    document7 = self.portal.document_module.newContent(reference='SEVEN', version='001', 
                                                                                    language='en',  **kw)
    document8 = self.portal.document_module.newContent(reference='SEVEN', version='001', 
                                                                                    language='fr',  **kw)
    document9 = self.portal.document_module.newContent(reference='EIGHT', version='001', 
                                                                                    language='en',  **kw)
    document10 = self.portal.document_module.newContent(reference='EIGHT', version='002', 
                                                                                      language='en',  **kw)
    document11 = self.portal.document_module.newContent(reference='TEN', version='001', 
                                                                                      language='en',  **kw)
    document12 = self.portal.document_module.newContent(reference='TEN', version='001', 
                                                                                      language='fr',  **kw)
    document13 = self.portal.document_module.newContent(reference='TEN', version='002', 
                                                                                      language='en',  **kw)
Romain Courteaud's avatar
Romain Courteaud committed
383 384 385 386

    document3.setSimilarValue(document1)
    document4.setSimilarValue(document3)
    document5.setSimilarValue(document4)
387 388 389 390
    
    document6.setSimilarValueList([document8,  document13])
    document7.setSimilarValue([document9])
    document11.setSimilarValue(document7)
Romain Courteaud's avatar
Romain Courteaud committed
391

392
    transaction.commit()
Romain Courteaud's avatar
Romain Courteaud committed
393
    self.tic()
394 395 396
    
    #if user language is 'en'
    self.portal.Localizer.changeLanguage('en')
Romain Courteaud's avatar
Romain Courteaud committed
397

398
    # 4 is similar to 3 and 5, 3 similar to 1, last version are the same
Romain Courteaud's avatar
Romain Courteaud committed
399 400 401 402
    self.assertSameSet([document1, document3, document5],
                       document4.getSimilarCloudValueList())
    self.assertSameSet([document3, document5],
                       document4.getSimilarCloudValueList(depth=1))
Bartek Górny's avatar
Bartek Górny committed
403

404 405 406 407 408 409 410 411 412 413 414 415 416 417
    self.assertSameSet([document7, document13], 
                       document6.getSimilarCloudValueList())
    self.assertSameSet([document10, document13], 
                       document7.getSimilarCloudValueList())
    self.assertSameSet([document7, document13], 
                       document9.getSimilarCloudValueList())
    self.assertSameSet([], 
                       document10.getSimilarCloudValueList())
    # 11 similar to 7, last version of 7 (en) is 7, similar of 7 is 9, last version of 9 (en) is 10
    self.assertSameSet([document7, document10], 
                       document11.getSimilarCloudValueList())
    self.assertSameSet([document6, document7], 
                       document13.getSimilarCloudValueList())

418
    transaction.commit()
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
    
    # if user language is 'fr', test that latest documents are prefferable returned in user_language (if available)
    self.portal.Localizer.changeLanguage('fr')
   
    self.assertSameSet([document8, document13], 
                       document6.getSimilarCloudValueList())
    self.assertSameSet([document6, document13], 
                       document8.getSimilarCloudValueList())
    self.assertSameSet([document8, document10], 
                       document11.getSimilarCloudValueList())
    self.assertSameSet([], 
                       document12.getSimilarCloudValueList())
    self.assertSameSet([document6, document8], 
                       document13.getSimilarCloudValueList())
    
434
    transaction.commit()
435 436 437 438 439 440
    
    # if user language is "bg"
    self.portal.Localizer.changeLanguage('bg')
    self.assertSameSet([document8, document13], 
                       document6.getSimilarCloudValueList())

441
  def test_07_testImplicitRelations(self,quiet=QUIET,run=RUN_ALL_TEST):
Bartek Górny's avatar
Bartek Górny committed
442 443 444 445 446
    """
      Test implicit (wiki-like) relations.
    """
    # XXX this test should be extended to check more elaborate language selection
    if not run: return
447 448 449 450

    def sqlresult_to_document_list(result):
      return [i.getObject() for i in result]

Bartek Górny's avatar
Bartek Górny committed
451 452 453
    printAndLog('\nTest Implicit Relations')
    # create docs to be referenced:
    # (1) TEST, 002, en
454 455 456 457
    filename = 'TEST-en-002.odt'
    file = makeFileUpload(filename)
    document1 = self.portal.portal_contributions.newContent(file=file)

Bartek Górny's avatar
Bartek Górny committed
458
    # (2) TEST, 002, fr
459 460
    as_name = 'TEST-fr-002.odt'
    file = makeFileUpload(filename, as_name)
461 462
    document2 = self.portal.portal_contributions.newContent(file=file)

Bartek Górny's avatar
Bartek Górny committed
463
    # (3) TEST, 003, en
464 465
    as_name = 'TEST-en-003.odt'
    file = makeFileUpload(filename, as_name)
466 467
    document3 = self.portal.portal_contributions.newContent(file=file)

Bartek Górny's avatar
Bartek Górny committed
468 469
    # create docs to contain references in text_content:
    # REF, 001, en; "I use reference to look up TEST"
470 471 472 473
    filename = 'REF-en-001.odt'
    file = makeFileUpload(filename)
    document4 = self.portal.portal_contributions.newContent(file=file)

Bartek Górny's avatar
Bartek Górny committed
474
    # REF, 002, en; "I use reference to look up TEST"
475 476 477 478
    filename = 'REF-en-002.odt'
    file = makeFileUpload(filename)
    document5 = self.portal.portal_contributions.newContent(file=file)

Bartek Górny's avatar
Bartek Górny committed
479
    # REFLANG, 001, en: "I use reference and language to look up TEST-fr"
480 481 482 483
    filename = 'REFLANG-en-001.odt'
    file = makeFileUpload(filename)
    document6 = self.portal.portal_contributions.newContent(file=file)

Bartek Górny's avatar
Bartek Górny committed
484
    # REFVER, 001, en: "I use reference and version to look up TEST-002"
485 486 487 488
    filename = 'REFVER-en-001.odt'
    file = makeFileUpload(filename)
    document7 = self.portal.portal_contributions.newContent(file=file)

Bartek Górny's avatar
Bartek Górny committed
489
    # REFVERLANG, 001, en: "I use reference, version and language to look up TEST-002-en"
490 491 492 493
    filename = 'REFVERLANG-en-001.odt'
    file = makeFileUpload(filename)
    document8 = self.portal.portal_contributions.newContent(file=file)

494
    transaction.commit()
495
    self.tic()
Bartek Górny's avatar
Bartek Górny committed
496
    printAndLog('\nTesting Implicit Predecessors')
497 498
    # the implicit predecessor will find documents by reference.
    # version and language are not used.
Bartek Górny's avatar
Bartek Górny committed
499
    # the implicit predecessors should be:
500 501 502 503 504 505 506 507 508

    # for (1): REF-002, REFLANG, REFVER, REFVERLANG
    # document1's reference is TEST. getImplicitPredecessorValueList will
    # return latest version of documents which contains string "TEST".
    self.assertSameSet(
      [document5, document6, document7, document8],
      sqlresult_to_document_list(document1.getImplicitPredecessorValueList()))

    # clear transactional variable cache
509
    transaction.commit()
510

Bartek Górny's avatar
Bartek Górny committed
511
    printAndLog('\nTesting Implicit Successors')
512 513 514 515 516 517 518 519 520 521 522
    # the implicit successors should be return document with appropriate
    # language.

    # if user language is 'en'.
    self.portal.Localizer.changeLanguage('en')

    self.assertSameSet(
      [document3],
      sqlresult_to_document_list(document5.getImplicitSuccessorValueList()))

    # clear transactional variable cache
523
    transaction.commit()
524 525 526 527 528 529 530 531

    # if user language is 'fr'.
    self.portal.Localizer.changeLanguage('fr')
    self.assertSameSet(
      [document2],
      sqlresult_to_document_list(document5.getImplicitSuccessorValueList()))

    # clear transactional variable cache
532
    transaction.commit()
533 534 535 536 537 538

    # if user language is 'ja'.
    self.portal.Localizer.changeLanguage('ja')
    self.assertSameSet(
      [document3],
      sqlresult_to_document_list(document5.getImplicitSuccessorValueList()))
Bartek Górny's avatar
Bartek Górny committed
539

540 541 542 543 544 545 546 547 548 549 550 551 552 553
  def testOOoDocument_get_size(self):
    # test get_size on OOoDocument
    doc = self.portal.document_module.newContent(portal_type='Spreadsheet')
    doc.edit(file=makeFileUpload('import_data_list.ods'))
    self.assertEquals(len(makeFileUpload('import_data_list.ods').read()),
                      doc.get_size())

  def testTempOOoDocument_get_size(self):
    # test get_size on temporary OOoDocument
    from Products.ERP5Type.Document import newTempOOoDocument
    doc = newTempOOoDocument(self.portal, 'tmp')
    doc.edit(base_data='OOo')
    self.assertEquals(len('OOo'), doc.get_size())

554 555 556 557 558 559 560 561 562 563 564 565 566 567
  def testOOoDocument_hasData(self):
    # test hasData on OOoDocument
    doc = self.portal.document_module.newContent(portal_type='Spreadsheet')
    self.failIf(doc.hasData())
    doc.edit(file=makeFileUpload('import_data_list.ods'))
    self.failUnless(doc.hasData())

  def testTempOOoDocument_hasData(self):
    # test hasData on TempOOoDocument
    from Products.ERP5Type.Document import newTempOOoDocument
    doc = newTempOOoDocument(self.portal, 'tmp')
    self.failIf(doc.hasData())
    doc.edit(file=makeFileUpload('import_data_list.ods'))
    self.failUnless(doc.hasData())
568

569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
  def test_Owner_Base_download(self):
    # tests that owners can download OOo documents, and all headers (including
    # filenames) are set correctly
    doc = self.portal.document_module.newContent(
                                  source_reference='test.ods',
                                  portal_type='Spreadsheet')
    doc.edit(file=makeFileUpload('import_data_list.ods'))

    uf = self.portal.acl_users
    uf._doAddUser('member_user1', 'secret', ['Member', 'Owner'], [])
    user = uf.getUserById('member_user1').__of__(uf)
    newSecurityManager(None, user)

    response = self.publish('%s/Base_download' % doc.getPath(),
                            basic='member_user1:secret')
    self.assertEquals(makeFileUpload('import_data_list.ods').read(),
                      response.body)
    self.assertEquals('application/vnd.oasis.opendocument.spreadsheet',
                      response.headers['content-type'])
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
588
    self.assertEquals('attachment; filename="import_data_list.ods"',
589
                      response.headers['content-disposition'])
590
    self.tic()
591 592 593 594 595 596 597 598 599

  def test_Member_download_pdf_format(self):
    # tests that members can download OOo documents in pdf format (at least in
    # published state), and all headers (including filenames) are set correctly
    doc = self.portal.document_module.newContent(
                                  source_reference='test.ods',
                                  portal_type='Spreadsheet')
    doc.edit(file=makeFileUpload('import_data_list.ods'))
    doc.publish()
600
    transaction.commit()
601
    self.tic()
602
    transaction.commit()
603 604 605 606 607 608 609 610 611

    uf = self.portal.acl_users
    uf._doAddUser('member_user2', 'secret', ['Member'], [])
    user = uf.getUserById('member_user2').__of__(uf)
    newSecurityManager(None, user)

    response = self.publish('%s/Document_convert?format=pdf' % doc.getPath(),
                            basic='member_user2:secret')
    self.assertEquals('application/pdf', response.headers['content-type'])
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
612
    self.assertEquals('attachment; filename="import_data_list.pdf"',
613 614
                      response.headers['content-disposition'])

615 616 617 618 619 620 621
    # test Print icon works on OOoDocument
    response = self.publish('%s/OOoDocument_print' % doc.getPath())
    self.assertEquals('application/pdf',
                      response.headers['content-type'])
    self.assertEquals('attachment; filename="import_data_list.pdf"',
                      response.headers['content-disposition'])

622
  def test_05_getCreationDate(self):
623 624 625 626 627 628 629 630 631 632 633 634 635
    """
    Check getCreationDate on all document type, as those documents 
    are not associated to edit_workflow.
    """
    portal = self.getPortalObject()
    for document_type in portal.getPortalDocumentTypeList():
      module = portal.getDefaultModule(document_type)
      obj = module.newContent(portal_type=document_type)
      self.assertNotEquals(obj.getCreationDate(),
                           module.getCreationDate())
      self.assertNotEquals(obj.getCreationDate(),
                           portal.CreationDate())

636 637
  def test_Base_getConversionFormatItemList(self):
    # tests Base_getConversionFormatItemList script (requires oood)
638
    self.assertTrue(('Microsoft Excel 97/2000/XP', 'xls') in
639 640 641 642 643
        self.portal.Base_getConversionFormatItemList(base_content_type=
                  'application/vnd.oasis.opendocument.spreadsheet'))
    self.assertTrue(('DocBook', 'docbook.xml') in
        self.portal.Base_getConversionFormatItemList(base_content_type=
                  'application/vnd.oasis.opendocument.text'))
644

645 646 647 648 649 650 651 652 653 654 655 656
  def test_06_ProcessingStateOfAClonedDocument(self,quiet=QUIET,run=RUN_ALL_TEST):
    """
    Check that the processing state of a cloned document
    is not draft
    """
    if not run: return
    printAndLog('\nProcessing State of a Cloned Document')
    filename = 'TEST-en-002.doc'
    file = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=file)

    self.assertEquals('converting', document.getExternalProcessingState())
657
    transaction.commit()
658
    self.assertEquals('converting', document.getExternalProcessingState())
659 660 661 662 663 664 665 666

    # Clone a uploaded document
    container = document.getParentValue()
    clipboard = container.manage_copyObjects(ids=[document.getId()])
    paste_result = container.manage_pasteObjects(cb_copy_data=clipboard)
    new_document = container[paste_result[0]['new_id']]

    self.assertEquals('converting', new_document.getExternalProcessingState())
667
    transaction.commit()
668 669 670
    self.assertEquals('converting', new_document.getExternalProcessingState())

    # Change workflow state to converted
671 672
    self.tic()
    self.assertEquals('converted', document.getExternalProcessingState())
673
    self.assertEquals('converted', new_document.getExternalProcessingState())
674

675
    # Clone a converted document
676 677 678 679 680
    container = document.getParentValue()
    clipboard = container.manage_copyObjects(ids=[document.getId()])
    paste_result = container.manage_pasteObjects(cb_copy_data=clipboard)
    new_document = container[paste_result[0]['new_id']]

681
    self.assertEquals('converted', new_document.getExternalProcessingState())
682
    transaction.commit()
683
    self.assertEquals('converted', new_document.getExternalProcessingState())
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
    self.tic()
    self.assertEquals('converted', new_document.getExternalProcessingState())

  def test_07_EmbeddedDocumentOfAClonedDocument(self,quiet=QUIET,run=RUN_ALL_TEST):
    """
    Check the validation state of embedded document when its container is
    cloned
    """
    if not run: return
    printAndLog('\nValidation State of a Cloned Document')
    filename = 'TEST-en-002.doc'
    file = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=file)

    sub_document = document.newContent(portal_type='Image')
    self.assertEquals('embedded', sub_document.getValidationState())
700
    transaction.commit()
701 702 703 704 705 706 707 708 709 710 711 712 713 714
    self.tic()
    self.assertEquals('embedded', sub_document.getValidationState())

    # Clone document
    container = document.getParentValue()
    clipboard = container.manage_copyObjects(ids=[document.getId()])

    paste_result = container.manage_pasteObjects(cb_copy_data=clipboard)
    new_document = container[paste_result[0]['new_id']]

    new_sub_document_list = new_document.contentValues(portal_type='Image')
    self.assertEquals(1, len(new_sub_document_list))
    new_sub_document = new_sub_document_list[0]
    self.assertEquals('embedded', new_sub_document.getValidationState())
715
    transaction.commit()
716 717 718
    self.tic()
    self.assertEquals('embedded', new_sub_document.getValidationState())

719 720 721 722 723 724 725 726 727 728
  def test_08_EmbeddedDocumentState(self,quiet=QUIET,run=RUN_ALL_TEST):
    """
    Check the validation state of an embedded document
    """
    if not run: return
    printAndLog('\nValidation State of an Embedded Document')
    filename = 'EmbeddedImage-en-002.odt'
    file = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=file)

729
    transaction.commit()
730 731 732 733 734
    self.tic()

    self.assertEquals(0, len(document.contentValues(portal_type='Image')))
    document.convert(format='html')
    image_list = document.contentValues(portal_type='Image')
735 736 737
    self.assertEquals(0, len(image_list))
#     image = image_list[0]
#     self.assertEquals('embedded', image.getValidationState())
738

739 740 741 742 743 744 745 746 747 748 749 750
  def test_09_ScriptableKeys(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
    Check the default DMS scriptale keys
    """
    if not run: return
    printAndLog('\nScriptable Keys')
    # Check that SQL generated is valid
    self.portal.portal_catalog(advanced_search_text='')
    self.portal.portal_catalog(advanced_search_text='a search text')
    self.portal.portal_catalog(portal_search_text='')
    self.portal.portal_catalog(portal_search_text='a search text')

751 752 753 754 755 756
    # Create a document.
    document_1 = self.portal.document_module.newContent(portal_type='File')
    document_1.setDescription('Hello. ScriptableKey is very useful if you want to make your own search syntax.')
    document_2 = self.portal.document_module.newContent(portal_type='File')
    document_2.setDescription('This test make sure that scriptable key feature on ZSQLCatalog works.')

757
    transaction.commit()
758 759 760 761 762 763 764
    self.tic()

    # Use scriptable key to search above documents.
    self.assertEqual(len(self.portal.portal_catalog(advanced_search_text='ScriptableKey')), 1)
    self.assertEqual(len(self.portal.portal_catalog(advanced_search_text='RelatedKey')), 0)
    self.assertEqual(len(self.portal.portal_catalog(advanced_search_text='make')), 2)

765 766 767 768 769 770 771
  def test_PDFTextContent(self):
    upload_file = makeFileUpload('REF-en-001.pdf')
    document = self.portal.portal_contributions.newContent(file=upload_file)
    self.assertEquals('PDF', document.getPortalType())
    self.assertEquals('I use reference to look up TEST\n',
                      document._convertToText())
    self.assert_('I use reference to look up TEST' in
772
                 document._convertToHTML().replace('&nbsp;', ' '))
773 774 775
    self.assert_('I use reference to look up TEST' in
                 document.SearchableText())

776 777 778 779 780 781 782 783 784 785
  def test_PDFToImage(self):
    upload_file = makeFileUpload('REF-en-001.pdf')
    document = self.portal.portal_contributions.newContent(file=upload_file)
    self.assertEquals('PDF', document.getPortalType())
    content_type, image_data = document.convert(format='png',
                                           frame=0,
                                           display='thumbnail')
    # it's a valid PNG
    self.assertEquals('PNG', image_data[1:4])
    
786 787 788 789 790 791 792 793
  def test_PDF_content_information(self):
    upload_file = makeFileUpload('REF-en-001.pdf')
    document = self.portal.portal_contributions.newContent(file=upload_file)
    self.assertEquals('PDF', document.getPortalType())
    content_information = document.getContentInformation()
    self.assertEquals('1', content_information['Pages'])
    self.assertEquals('subject', content_information['Subject'])
    self.assertEquals('title', content_information['Title'])
794
    self.assertEquals('application/pdf', document.getContentType())
795

796 797
  def test_PDF_content_content_type(self):
    upload_file = makeFileUpload('REF-en-001.pdf')
798 799 800 801 802 803 804 805
    document = self.portal.document_module.newContent(portal_type='PDF')
    # Here we use edit instead of setFile,
    # because only edit method set filename as source_reference.
    # This is a feature related to portal_contribution,
    # sometimes filename is replaced by value provided by
    # rewriteIngestionData type based method.
    # setFile should keep value provided by portal_contribution
    # instead of reading it from file itself.
Nicolas Delaby's avatar
typo  
Nicolas Delaby committed
806
    # See special parameter set_filename__ in ERP5.Tool.ContributionTool
807
    document.edit(file=upload_file)
808
    self.assertEquals('application/pdf', document.getContentType())
809

810 811 812 813 814 815 816
  def test_CMYKImageTextContent(self):
    upload_file = makeFileUpload('cmyk_sample.jpg')
    document = self.portal.portal_contributions.newContent(file=upload_file)
    self.assertEquals('Image', document.getPortalType())
    self.assertEquals('ERP5 is a free software.\n',
                      document.SearchableText())

817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
  def test_Base_showFoundText(self):
    # Create document with good content
    document = self.portal.document_module.newContent(portal_type='Drawing')
    self.assertEquals('empty', document.getExternalProcessingState())

    filename = 'TEST-en-002.odt'
    upload_file = makeFileUpload(filename)
    document.edit(file=upload_file)
    transaction.commit()
    self.tic()
    self.assertEquals('converted', document.getExternalProcessingState())

    # Upload different type of file inside
    upload_file = makeFileUpload('REF-en-001.pdf')
    document.edit(file=upload_file)
    self.assertEquals('application/pdf', document.getContentType())
    self.assertEquals('converting', document.getExternalProcessingState())
    # As document is not converted, text convertion is impossible
    # But document can still be retrive with portal catalog
    self.assertRaises(NotConvertedError, document.asText)
    self.assertRaises(NotConvertedError, document.getSearchableText)
    self.assertEquals('This document is not converted yet.', 
                      document.Base_showFoundText())

841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
  def test_Base_createNewFile(self):
    context = self.portal.person_module.newContent(portal_type='Person')
    ret = context.Base_createNewFile(portal_type=None,
                               title=None,
                               reference=None,
                               short_title=None,
                               language=None,
                               version=None,
                               description=None,
                               file=makeFileUpload('TEST-en-002.odt'))
    self.assertTrue(ret.endswith(
      '?portal_status_message=Text%20created%20successfully.'), ret)
    transaction.commit()
    self.tic()
    document_list = context.getFollowUpRelatedValueList()
    self.assertEquals(1, len(document_list))
    document = document_list[0]
    self.assertEquals('converted', document.getExternalProcessingState())
    self.assertEquals('Text', document.getPortalType())
    self.assertEquals('title', document.getTitle())

  def test_Base_createNewFile_empty(self):
    context = self.portal.person_module.newContent(portal_type='Person')
    empty_file_upload = ZPublisher.HTTPRequest.FileUpload(FieldStorage(
                            fp=StringIO.StringIO(),
                            environ=dict(REQUEST_METHOD='PUT'),
                            headers={"content-disposition":
                              "attachment; filename=empty;"}))

    ret = context.Base_createNewFile(portal_type=None,
                               title=None,
                               reference=None,
                               short_title=None,
                               language=None,
                               version=None,
                               description=None,
                               file=empty_file_upload)
    
    self.assertTrue(ret.endswith(
      '?portal_status_message=File%20created%20successfully.'), ret)
    transaction.commit()
    self.tic()
    document_list = context.getFollowUpRelatedValueList()
    self.assertEquals(1, len(document_list))
    document = document_list[0]
    self.assertEquals('empty', document.getExternalProcessingState())
    self.assertEquals('File', document.getPortalType())



891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
class TestDocumentWithSecurity(ERP5TypeTestCase):

  username = 'yusei'

  def getTitle(self):
    return "DMS with security"

  def afterSetUp(self):
    self.setSystemPreference()
    # set a dummy localizer (because normally it is cookie based)
    self.portal.Localizer = DummyLocalizer()
    # make sure every body can traverse document module
    self.portal.document_module.manage_permission('View', ['Anonymous'], 1)
    self.portal.document_module.manage_permission(
                           'Access contents information', ['Anonymous'], 1)
    self.login()

  def setSystemPreference(self):
    default_pref = self.portal.portal_preferences.default_site_preference
    default_pref.setPreferredOoodocServerAddress(conversion_server_host[0])
    default_pref.setPreferredOoodocServerPortNumber(conversion_server_host[1])
    default_pref.setPreferredDocumentFileNameRegularExpression(FILE_NAME_REGULAR_EXPRESSION)
    default_pref.setPreferredDocumentReferenceRegularExpression(REFERENCE_REGULAR_EXPRESSION)
914 915
    if default_pref.getPreferenceState() != 'global':
      default_pref.enable()
916
    transaction.commit()
917 918 919 920 921 922 923 924 925 926 927 928
    self.tic()

  def login(self):
    uf = self.getPortal().acl_users
    uf._doAddUser(self.username, '', ['Auditor', 'Author'], [])
    user = uf.getUserById(self.username).__of__(uf)
    newSecurityManager(None, user)

  def getDocumentModule(self):
    return getattr(self.getPortal(),'document_module')

  def getBusinessTemplateList(self):
929 930
    return ('erp5_base',
            'erp5_ingestion', 'erp5_ingestion_mysql_innodb_catalog',
931
            'erp5_web', 'erp5_dms')
932 933 934 935 936 937 938 939 940 941

  def test_ShowPreviewAfterSubmitted(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
    Make sure that uploader can preview document after submitted.
    """
    if not run: return
    filename = 'REF-en-001.odt'
    upload_file = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=upload_file)

942
    transaction.commit()
943 944 945 946 947 948
    self.tic()

    document.submit()

    preview_html = document.Document_getPreviewAsHTML().replace('\n', ' ')

949
    transaction.commit()
950 951 952 953 954
    self.tic()

    self.assert_('I use reference to look up TEST' in preview_html)


955 956 957
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestDocument))
958
  suite.addTest(unittest.makeSuite(TestDocumentWithSecurity))
959
  return suite
Bartek Górny's avatar
Bartek Górny committed
960 961 962


# vim: syntax=python shiftwidth=2