testDms.py 70.7 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
59
from Products.ERP5OOo.OOoUtils import OOoBuilder
Jérome Perrin's avatar
Jérome Perrin committed
60
from AccessControl.SecurityManagement import newSecurityManager
Bartek Górny's avatar
Bartek Górny committed
61
from zLOG import LOG
62
from Products.ERP5.Document.Document import NotConvertedError
63
from Products.ERP5Type.tests.backportUnittest import expectedFailure
Bartek Górny's avatar
Bartek Górny committed
64 65
import os

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

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

72
TEST_FILES_HOME = os.path.join(os.path.dirname(__file__), 'test_document')
73 74
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}))?"
75

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

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):
90
  return os.path.join(os.path.dirname(__file__), 'test_document', name)
Bartek Górny's avatar
Bartek Górny committed
91

92 93 94 95 96
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
97

98

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

  def getTitle(self):
    return "DMS"

107 108
  ## setup

109
  def setUpOnce(self):
110
    self.setSystemPreference()
111 112
    # set a dummy localizer (because normally it is cookie based)
    self.portal.Localizer = DummyLocalizer()
113 114 115 116
    # 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
117

118
  def setSystemPreference(self):
Ivan Tyagov's avatar
Ivan Tyagov committed
119
    default_pref = self.portal.portal_preferences.newContent(portal_type='System Preference')
120
    default_pref.setPriority(1)
121 122 123 124
    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)
125 126
    if default_pref.getPreferenceState() != 'global':
      default_pref.enable()
127
    return default_pref
128

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

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

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

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

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

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

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

Bartek Górny's avatar
Bartek Górny committed
181 182 183 184 185 186 187 188
  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)

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

192 193
  ## tests

Bartek Górny's avatar
Bartek Górny committed
194 195 196 197
  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
    """
198
    if not run: return
Bartek Górny's avatar
Bartek Górny committed
199
    printAndLog('\nTest Has Everything ')
200 201 202 203 204 205
    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)
206

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

  def test_03_Versioning(self,quiet=QUIET,run=RUN_ALL_TEST):
    """
      Test versioning
    """
    if not run: return
    printAndLog('\nTest Versioning System')
252 253 254 255 256 257 258 259 260 261 262 263 264 265
    # 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')
266
    transaction.commit()
267 268 269 270 271
    self.tic()
    self.failIf(docs[1].isVersionUnique())
    self.failIf(docs[2].isVersionUnique())
    self.failUnless(docs[3].isVersionUnique())
    docs[2].setVersion('003')
272
    transaction.commit()
273 274 275 276 277 278 279 280 281
    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
282 283 284 285 286 287 288 289 290 291 292 293 294

  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
295
    # the following calls (on any doc) should produce the following output:
Bartek Górny's avatar
Bartek Górny committed
296 297 298 299 300 301 302
    # getOriginalLanguage() = 'en'
    # getLanguageList = ('en', 'fr', 'pl', 'sp')
    # getLatestVersionValue() = 4
    # getLatestVersionValue('en') = 4
    # getLatestVersionValue('fr') = 2
    # getLatestVersionValue('pl') = 3
    # getLatestVersionValue('ru') = None
303
    # change user language into 'sp'
Bartek Górny's avatar
Bartek Górny committed
304
    # getLatestVersionValue() = 5
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    # 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)
322
    transaction.commit()
323 324 325 326 327 328 329 330 331 332 333 334 335
    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')
336
    transaction.commit()
337 338
    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
339

340
  def test_06_testExplicitRelations(self,quiet=QUIET,run=RUN_ALL_TEST):
Bartek Górny's avatar
Bartek Górny committed
341 342 343 344 345 346
    """
      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
Fabien Morin's avatar
Fabien Morin committed
347

Bartek Górny's avatar
Bartek Górny committed
348 349 350 351 352 353 354 355
    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
356
    # getSimilarCloudValueList on 4 should return 1, 3 and 5
Bartek Górny's avatar
Bartek Górny committed
357
    # getSimilarCloudValueList(depth=1) on 4 should return 3 and 5
Fabien Morin's avatar
Fabien Morin committed
358

359 360 361 362 363 364 365 366
    # 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)
Fabien Morin's avatar
Fabien Morin committed
367 368

    document6 = self.portal.document_module.newContent(reference='SIX', version='001',
369
                                                                                    language='en',  **kw)
Fabien Morin's avatar
Fabien Morin committed
370
    document7 = self.portal.document_module.newContent(reference='SEVEN', version='001',
371
                                                                                    language='en',  **kw)
Fabien Morin's avatar
Fabien Morin committed
372
    document8 = self.portal.document_module.newContent(reference='SEVEN', version='001',
373
                                                                                    language='fr',  **kw)
Fabien Morin's avatar
Fabien Morin committed
374
    document9 = self.portal.document_module.newContent(reference='EIGHT', version='001',
375
                                                                                    language='en',  **kw)
Fabien Morin's avatar
Fabien Morin committed
376
    document10 = self.portal.document_module.newContent(reference='EIGHT', version='002',
377
                                                                                      language='en',  **kw)
Fabien Morin's avatar
Fabien Morin committed
378
    document11 = self.portal.document_module.newContent(reference='TEN', version='001',
379
                                                                                      language='en',  **kw)
Fabien Morin's avatar
Fabien Morin committed
380
    document12 = self.portal.document_module.newContent(reference='TEN', version='001',
381
                                                                                      language='fr',  **kw)
Fabien Morin's avatar
Fabien Morin committed
382
    document13 = self.portal.document_module.newContent(reference='TEN', version='002',
383
                                                                                      language='en',  **kw)
Romain Courteaud's avatar
Romain Courteaud committed
384 385 386 387

    document3.setSimilarValue(document1)
    document4.setSimilarValue(document3)
    document5.setSimilarValue(document4)
Fabien Morin's avatar
Fabien Morin committed
388

389 390 391
    document6.setSimilarValueList([document8,  document13])
    document7.setSimilarValue([document9])
    document11.setSimilarValue(document7)
Romain Courteaud's avatar
Romain Courteaud committed
392

393
    transaction.commit()
Romain Courteaud's avatar
Romain Courteaud committed
394
    self.tic()
Fabien Morin's avatar
Fabien Morin committed
395

396 397
    #if user language is 'en'
    self.portal.Localizer.changeLanguage('en')
Romain Courteaud's avatar
Romain Courteaud committed
398

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

Fabien Morin's avatar
Fabien Morin committed
405
    self.assertSameSet([document7, document13],
406
                       document6.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
407
    self.assertSameSet([document10, document13],
408
                       document7.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
409
    self.assertSameSet([document7, document13],
410
                       document9.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
411
    self.assertSameSet([],
412 413
                       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
Fabien Morin's avatar
Fabien Morin committed
414
    self.assertSameSet([document7, document10],
415
                       document11.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
416
    self.assertSameSet([document6, document7],
417 418
                       document13.getSimilarCloudValueList())

419
    transaction.commit()
Fabien Morin's avatar
Fabien Morin committed
420

421 422
    # if user language is 'fr', test that latest documents are prefferable returned in user_language (if available)
    self.portal.Localizer.changeLanguage('fr')
Fabien Morin's avatar
Fabien Morin committed
423 424

    self.assertSameSet([document8, document13],
425
                       document6.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
426
    self.assertSameSet([document6, document13],
427
                       document8.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
428
    self.assertSameSet([document8, document10],
429
                       document11.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
430
    self.assertSameSet([],
431
                       document12.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
432
    self.assertSameSet([document6, document8],
433
                       document13.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
434

435
    transaction.commit()
Fabien Morin's avatar
Fabien Morin committed
436

437 438
    # if user language is "bg"
    self.portal.Localizer.changeLanguage('bg')
Fabien Morin's avatar
Fabien Morin committed
439
    self.assertSameSet([document8, document13],
440 441
                       document6.getSimilarCloudValueList())

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

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

Bartek Górny's avatar
Bartek Górny committed
452 453 454
    printAndLog('\nTest Implicit Relations')
    # create docs to be referenced:
    # (1) TEST, 002, en
455 456 457 458
    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
459
    # (2) TEST, 002, fr
460 461
    as_name = 'TEST-fr-002.odt'
    file = makeFileUpload(filename, as_name)
462 463
    document2 = self.portal.portal_contributions.newContent(file=file)

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

Bartek Górny's avatar
Bartek Górny committed
469 470
    # create docs to contain references in text_content:
    # REF, 001, en; "I use reference to look up TEST"
471 472 473 474
    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
475
    # REF, 002, en; "I use reference to look up TEST"
476 477 478 479
    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
480
    # REFLANG, 001, en: "I use reference and language to look up TEST-fr"
481 482 483 484
    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
485
    # REFVER, 001, en: "I use reference and version to look up TEST-002"
486 487 488 489
    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
490
    # REFVERLANG, 001, en: "I use reference, version and language to look up TEST-002-en"
491 492 493 494
    filename = 'REFVERLANG-en-001.odt'
    file = makeFileUpload(filename)
    document8 = self.portal.portal_contributions.newContent(file=file)

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

    # 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
510
    transaction.commit()
511

Bartek Górny's avatar
Bartek Górny committed
512
    printAndLog('\nTesting Implicit Successors')
513 514 515 516 517 518 519 520 521 522 523
    # 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
524
    transaction.commit()
525 526 527 528 529 530 531 532

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

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

    # 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
540

541 542 543 544 545 546 547 548 549 550 551 552 553 554
  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())

555 556 557 558 559 560 561 562 563 564 565 566 567 568
  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())
569

570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
  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
589
    self.assertEquals('attachment; filename="import_data_list.ods"',
590
                      response.headers['content-disposition'])
591
    self.tic()
592 593 594 595 596 597 598

  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')
599
    doc.edit(file=makeFileUpload('import.file.with.dot.in.filename.ods'))
600
    doc.publish()
601
    transaction.commit()
602
    self.tic()
603
    transaction.commit()
604 605 606 607 608 609 610 611 612

    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'])
613
    self.assertEquals('attachment; filename="import.file.with.dot.in.filename.pdf"',
614 615
                      response.headers['content-disposition'])

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

623
  def test_05_getCreationDate(self):
624
    """
Fabien Morin's avatar
Fabien Morin committed
625
    Check getCreationDate on all document type, as those documents
626 627 628 629 630 631 632 633 634 635 636
    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())

637 638
  def test_Base_getConversionFormatItemList(self):
    # tests Base_getConversionFormatItemList script (requires oood)
639
    self.assertTrue(('Microsoft Excel 97/2000/XP', 'xls') in
640 641 642 643 644
        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'))
645

646 647 648 649 650 651 652 653 654 655 656 657
  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())
658
    transaction.commit()
659
    self.assertEquals('converting', document.getExternalProcessingState())
660 661 662 663 664 665 666 667

    # 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())
668
    transaction.commit()
669 670 671
    self.assertEquals('converting', new_document.getExternalProcessingState())

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

676
    # Clone a converted document
677 678 679 680 681
    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']]

682
    self.assertEquals('converted', new_document.getExternalProcessingState())
683
    transaction.commit()
684
    self.assertEquals('converted', new_document.getExternalProcessingState())
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
    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())
701
    transaction.commit()
702 703 704 705 706 707 708 709 710 711 712 713 714 715
    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())
716
    transaction.commit()
717 718 719
    self.tic()
    self.assertEquals('embedded', new_sub_document.getValidationState())

720 721 722 723 724 725 726 727 728 729
  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)

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

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

740
  def test_09_SearchableText(self, quiet=QUIET, run=RUN_ALL_TEST):
741
    """
742
    Check DMS SearchableText capabilities.
743 744
    """
    if not run: return
Ivan Tyagov's avatar
Ivan Tyagov committed
745
    portal = self.portal
746

747
    # Create a document.
Ivan Tyagov's avatar
Ivan Tyagov committed
748 749 750 751 752 753 754 755 756 757
    document_1 = self.portal.document_module.newContent(
                        portal_type = 'File',
                        description = 'Hello. ScriptableKey is very useful if you want to make your own search syntax.',
                        language = 'en',
                        version = '001')
    document_2 = self.portal.document_module.newContent(
                        portal_type='File',
                        description = 'This test make sure that scriptable key feature on ZSQLCatalog works.',
                        language='fr',
                        version = '002')
Ivan Tyagov's avatar
Ivan Tyagov committed
758 759 760 761 762 763
    document_3 = portal.document_module.newContent(
                   portal_type = 'Presentation',
                   title = "Complete set of tested reports with a long title.",
                   version = '003',
                   language = 'bg',
                   reference = 'tio-test-doc-3')
Ivan Tyagov's avatar
Ivan Tyagov committed
764 765 766 767 768
    person = portal.person_module.newContent(portal_type = 'Person', \
                                             reference= "john",
                                             title='John Doe Great')
    web_page = portal.web_page_module.newContent(portal_type = 'Web Page',
                                                 reference = "page_great_site",
Ivan Tyagov's avatar
Ivan Tyagov committed
769 770 771
                                                 text_content = 'Great website',
                                                 language='en',
                                                 version = '003')
Ivan Tyagov's avatar
Ivan Tyagov committed
772 773 774 775 776 777
    organisation = portal.organisation_module.newContent( \
                            portal_type = 'Organisation', \
                            reference = 'organisation-1',
                            title='Super nova organisation')
    self.stepTic()
    
778 779 780 781
    def getAdvancedSearchTextResultList(searchable_text, portal_type=None):
      kw = {'SearchableText': searchable_text}
      if portal_type is not None:
        kw['portal_type'] = portal_type
Ivan Tyagov's avatar
Ivan Tyagov committed
782 783 784 785 786 787 788 789 790 791
      return [x.getObject() for x in portal.portal_catalog(**kw)]
    
    # full text search
    self.assertSameSet([document_1], \
      getAdvancedSearchTextResultList('ScriptableKey'))
    self.assertEqual(len(getAdvancedSearchTextResultList('RelatedKey')), 0)
    self.assertSameSet([document_1, document_2], \
      getAdvancedSearchTextResultList('make'))    
    self.assertSameSet([web_page, person], \
      getAdvancedSearchTextResultList("Great"))
Ivan Tyagov's avatar
Ivan Tyagov committed
792 793 794 795 796 797 798
    # full text search with whole title of a document
    self.assertSameSet([document_3], \
      getAdvancedSearchTextResultList(document_3.getTitle()))
    # full text search with reference part of searchable_text 
    # (i.e. not specified with 'reference:' - simply part of search text)
    self.assertSameSet([document_3], \
      getAdvancedSearchTextResultList(document_3.getReference()))
Ivan Tyagov's avatar
Ivan Tyagov committed
799 800 801 802 803 804 805 806 807

   # full text search with reference
    self.assertSameSet([web_page], \
      getAdvancedSearchTextResultList("reference:%s Great" %web_page.getReference()))
    self.assertSameSet([person],
          getAdvancedSearchTextResultList('reference:%s' %person.getReference()))

    # full text search with portal_type
    self.assertSameSet([person], \
Ivan Tyagov's avatar
Ivan Tyagov committed
808 809
      getAdvancedSearchTextResultList('%s portal_type:%s' %(person.getTitle(), person.getPortalType())))

Ivan Tyagov's avatar
Ivan Tyagov committed
810
    self.assertSameSet([organisation], \
Ivan Tyagov's avatar
Ivan Tyagov committed
811 812 813
      getAdvancedSearchTextResultList('%s portal_type:%s' \
                                       %(organisation.getTitle(),
                                         organisation.getPortalType())))
814 815 816 817 818 819 820 821 822

    # full text search with portal_type passed outside searchable_text
    self.assertSameSet([web_page, person],
                       getAdvancedSearchTextResultList('Great'))
    self.assertSameSet([web_page], \
                       getAdvancedSearchTextResultList('Great', web_page.getPortalType()))
    self.assertSameSet([person], \
                       getAdvancedSearchTextResultList('Great', person.getPortalType()))
    
Ivan Tyagov's avatar
Ivan Tyagov committed
823 824
    # full text search with portal_type & reference
    self.assertSameSet([person], \
Ivan Tyagov's avatar
Ivan Tyagov committed
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
      getAdvancedSearchTextResultList('reference:%s portal_type:%s' \
                                        %(person.getReference(), person.getPortalType())))
    # full text search with language
    self.assertSameSet([document_1, web_page], \
      getAdvancedSearchTextResultList('language:en'))
    self.assertSameSet([document_1], \
      getAdvancedSearchTextResultList('Hello language:en'))
    self.assertSameSet([document_2], \
      getAdvancedSearchTextResultList('language:fr'))
    self.assertSameSet([web_page], \
      getAdvancedSearchTextResultList('%s reference:%s language:%s' \
                                       %(web_page.getTextContent(),
                                         web_page.getReference(),
                                         web_page.getLanguage())))
    # full text search with version
    self.assertSameSet([web_page], \
      getAdvancedSearchTextResultList('%s reference:%s language:%s version:%s' \
                                       %(web_page.getTextContent(),
                                         web_page.getReference(),
                                         web_page.getLanguage(),
                                         web_page.getVersion())))
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 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
  def test_10_SearchString(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
    Test search string search generation and parsing.
    """
    if not run: return

    portal = self.portal
    assemble = portal.Base_assembleSearchString
    parse = portal.Base_parseSearchString
    
    # directly pasing searchable string
    self.assertEquals('searchable text',
                      assemble(**{'searchabletext': 'searchable text'}))
    kw = {'searchabletext_any': 'searchabletext_any',
          'searchabletext_phrase': 'searchabletext_phrase1 searchabletext_phrase1'}
    # exact phrase
    search_string = assemble(**kw)
    self.assertEquals('%s "%s"' %(kw['searchabletext_any'], kw['searchabletext_phrase']), \
                      search_string)
    parsed_string = parse(search_string)
    self.assertEquals(['searchabletext'], parsed_string.keys())

    
    # search "with all of the words"
    kw["searchabletext_all"] = "searchabletext_all1 searchabletext_all2"
    search_string = assemble(**kw)
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2', \
                      search_string)
    parsed_string = parse(search_string)
    self.assertEquals(['searchabletext'], parsed_string.keys())
    
    # search without these words 
    kw["searchabletext_without"] = "searchabletext_without1 searchabletext_without2"
    search_string = assemble(**kw)
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2', \
                      search_string)
    parsed_string = parse(search_string)
    self.assertEquals(['searchabletext'], parsed_string.keys())
    
    # search limited to a certain date range
    kw['created_within'] = '1w'
    search_string = assemble(**kw)
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w', \
                      search_string)
    parsed_string = parse(search_string)
    self.assertSameSet(['searchabletext', 'creation_from'], parsed_string.keys())
    
    # search with portal_type
    kw['search_portal_type'] = 'Document'
    search_string = assemble(**kw)
    parsed_string = parse(search_string)
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w type:"Document"', \
                      search_string)
    self.assertSameSet(['searchabletext', 'creation_from', 'portal_type'], \
                        parsed_string.keys())
    self.assertEquals(kw['search_portal_type'], parsed_string['portal_type'])
    
    # search by reference
    kw['reference'] = 'Nxd-test'
    search_string = assemble(**kw)
    parsed_string = parse(search_string)
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w type:"Document" reference:Nxd-test', \
                      search_string)
    self.assertSameSet(['searchabletext', 'creation_from', 'portal_type', 'reference'], \
                        parsed_string.keys())
    self.assertEquals(kw['search_portal_type'], parsed_string['portal_type'])
    self.assertEquals(kw['reference'], parsed_string['reference'])
    
    # search by version
    kw['version'] = '001'
    search_string = assemble(**kw)
    parsed_string = parse(search_string)
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w type:"Document" reference:Nxd-test version:001', \
                      search_string)
    self.assertSameSet(['searchabletext', 'creation_from', 'portal_type', 'reference', 'version'], \
                        parsed_string.keys())
    self.assertEquals(kw['search_portal_type'], parsed_string['portal_type'])
    self.assertEquals(kw['reference'], parsed_string['reference'])
    self.assertEquals(kw['version'], parsed_string['version'])
    
    # search by language
    kw['language'] = 'en'
    search_string = assemble(**kw)
    parsed_string = parse(search_string)
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w type:"Document" reference:Nxd-test version:001 language:en', \
                      search_string)
    self.assertSameSet(['searchabletext', 'creation_from', 'portal_type', 'reference', \
                        'version', 'language'], \
                        parsed_string.keys())
    self.assertEquals(kw['search_portal_type'], parsed_string['portal_type'])
    self.assertEquals(kw['reference'], parsed_string['reference'])
    self.assertEquals(kw['version'], parsed_string['version'])
    self.assertEquals(kw['language'], parsed_string['language'])
    
    # contributor title search
    kw['contributor_title'] = 'John'
    search_string = assemble(**kw)
    parsed_string = parse(search_string)
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w type:"Document" reference:Nxd-test version:001 language:en contributor_title:John', \
                      search_string)
    self.assertSameSet(['searchabletext', 'creation_from', 'portal_type', 'reference', \
                        'version', 'language', 'contributor_title'], \
                        parsed_string.keys())
    self.assertEquals(kw['search_portal_type'], parsed_string['portal_type'])
    self.assertEquals(kw['reference'], parsed_string['reference'])
    self.assertEquals(kw['version'], parsed_string['version'])
    self.assertEquals(kw['language'], parsed_string['language'])
    
    # only my docs
    kw['mine'] = 'yes'
    search_string = assemble(**kw)
    parsed_string = parse(search_string)
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w type:"Document" reference:Nxd-test version:001 language:en contributor_title:John mine:yes', \
                      search_string)
    self.assertSameSet(['searchabletext', 'creation_from', 'portal_type', 'reference', \
                        'version', 'language', 'contributor_title', 'mine'], \
                        parsed_string.keys())
    self.assertEquals(kw['search_portal_type'], parsed_string['portal_type'])
    self.assertEquals(kw['reference'], parsed_string['reference'])
    self.assertEquals(kw['version'], parsed_string['version'])
    self.assertEquals(kw['language'], parsed_string['language'])
    self.assertEquals(kw['mine'], parsed_string['mine'])
    
    # only newest versions 
    kw['newest'] = 'yes'
    search_string = assemble(**kw)
    parsed_string = parse(search_string)
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w type:"Document" reference:Nxd-test version:001 language:en contributor_title:John mine:yes newest:yes', \
                      search_string)
    self.assertSameSet(['searchabletext', 'creation_from', 'portal_type', 'reference', \
                        'version', 'language', 'contributor_title', 'mine', 'newest'], \
                        parsed_string.keys())
    self.assertEquals(kw['search_portal_type'], parsed_string['portal_type'])
    self.assertEquals(kw['reference'], parsed_string['reference'])
    self.assertEquals(kw['version'], parsed_string['version'])
    self.assertEquals(kw['language'], parsed_string['language'])
    self.assertEquals(kw['mine'], parsed_string['mine'])
    self.assertEquals(kw['newest'], parsed_string['newest'])
    
    # search mode 
    kw['search_mode'] = 'in_boolean_mode'
    search_string = assemble(**kw)
    parsed_string = parse(search_string)
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w type:"Document" reference:Nxd-test version:001 language:en contributor_title:John mine:yes newest:yes mode:boolean', \
                      search_string)
    self.assertSameSet(['searchabletext', 'creation_from', 'portal_type', 'reference', \
                        'version', 'language', 'contributor_title', 'mine', 'newest', 'mode'], \
                        parsed_string.keys())
    self.assertEquals(kw['search_portal_type'], parsed_string['portal_type'])
    self.assertEquals(kw['reference'], parsed_string['reference'])
    self.assertEquals(kw['version'], parsed_string['version'])
    self.assertEquals(kw['language'], parsed_string['language'])
    self.assertEquals(kw['mine'], parsed_string['mine'])
    self.assertEquals(kw['newest'], parsed_string['newest'])
    self.assertEquals('boolean', parsed_string['mode'])
1002

1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
  def test_11_SearchStringSearchCapability(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
    Test search string search search capabilities.
    """
    if not run: return

    portal = self.portal
    assemble = portal.Base_assembleSearchString
    search = portal.Base_getAdvancedSearchResultList

    def getAdvancedSearchStringResultList(**kw):
      search_string = assemble(**kw)
      return [x.getObject() for x in search(search_string)]
1016

1017 1018 1019 1020 1021 1022 1023 1024 1025
    # create some objects
    document_1 = portal.document_module.newContent(
                   portal_type = 'File',
                   description = 'standalone software linux python free',
                   version = '001',
                   language = 'en',
                   reference = 'nxd-test-doc-1')
    document_2 = portal.document_module.newContent(
                   portal_type = 'Presentation',
1026
                   description = 'standalone free python linux knowledge system management different',
1027 1028 1029 1030 1031 1032 1033 1034 1035
                   version = '002',
                   language = 'fr',
                   reference = 'nxd-test-doc-2')
    document_3 = portal.document_module.newContent(
                   portal_type = 'Presentation',
                   description = 'just a copy',
                   version = '003',
                   language = 'en',
                   reference = 'nxd-test-doc-2')
1036
    # multiple revisions of a Web Page
1037 1038
    web_page_1 = portal.web_page_module.newContent(
                   portal_type = 'Web Page',
1039
                   text_content = 'software based solutions document management product standalone owner different',
1040 1041 1042
                   version = '003',
                   language = 'jp',
                   reference = 'nxd-test-web-page-3')
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
    web_page_2 = portal.web_page_module.newContent(
                   portal_type = 'Web Page',
                   text_content = 'new revision (004) of nxd-test-web-page-3',
                   version = '004',
                   language = 'jp',
                   reference = 'nxd-test-web-page-3')
    web_page_3 = portal.web_page_module.newContent(
                   portal_type = 'Web Page',
                   text_content = 'new revision (005) of nxd-test-web-page-3',
                   version = '005',
                   language = 'jp',
                   reference = 'nxd-test-web-page-3')
    # publish documents so we can test searching within owned documents for an user
    for document in (document_1, document_2, document_3, web_page_1, web_page_2, web_page_3):
      document.publish()
    # create test Person objects and add pseudo local security
    person1 =  self.createUser(reference='user1')
    person1.setTitle('Another Contributor')
    portal.document_module.manage_setLocalRoles('user1', ['Assignor',])
    self.stepTic()

    # login as another user
    ERP5TypeTestCase.login(self, 'user1')
    document_4 = portal.document_module.newContent(
                   portal_type = 'Presentation',
                   description = 'owner different user contributing document',
                   version = '003',
                   language = 'bg',
                   reference = 'tlv-test-doc-1')
    contributor_list = document_4.getContributorValueList()
    contributor_list.append(person1)
    document_4.setContributorValueList(contributor_list)
    document_4.publish()
1076
    self.stepTic()
1077
    self.login()
1078 1079 1080 1081 1082 1083

    # search arbitrary word
    kw = {'searchabletext_any': 'software'}
    self.assertSameSet([document_1,web_page_1], getAdvancedSearchStringResultList(**kw))
    
    # exact word search
1084
    kw = {'searchabletext_phrase': 'linux python'}
1085
    self.assertSameSet([document_1], getAdvancedSearchStringResultList(**kw))
1086
    kw = {'searchabletext_phrase': 'python linux'}
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
    self.assertSameSet([document_2], getAdvancedSearchStringResultList(**kw))
    kw = {'searchabletext_any': '',
          'searchabletext_phrase': 'python linux knowledge system'}
    self.assertSameSet([document_2], getAdvancedSearchStringResultList(**kw))
    
    # search "with all of the words" - each word prefixed by "+"
    kw = {'searchabletext_any': 'standalone',
          'searchabletext_all': 'python'}
    self.assertSameSet([document_1, document_2], getAdvancedSearchStringResultList(**kw))
    
    # search without these words - every word prefixed by "-"
    kw = {'searchabletext_any': 'standalone',
          'searchabletext_without': 'python'}
    self.assertSameSet([web_page_1], getAdvancedSearchStringResultList(**kw))
   
    # only given portal_types - add "type:Type" or type:(Type1,Type2...)
    kw = {'searchabletext_any': 'python',
          'search_portal_type': 'Presentation'}
    self.assertSameSet([document_2], getAdvancedSearchStringResultList(**kw))
1106 1107 1108 1109 1110 1111
    kw = {'searchabletext_any': 'python',
          'search_portal_type': 'File'}
    self.assertSameSet([document_1], getAdvancedSearchStringResultList(**kw))
    kw = {'searchabletext_any': 'management',
          'search_portal_type': 'File'}
    self.assertSameSet([], getAdvancedSearchStringResultList(**kw))
1112 1113
   
    # search by reference
1114
    kw = {'reference': document_2.getReference()}
1115 1116 1117 1118
    self.assertSameSet([document_2, document_3], getAdvancedSearchStringResultList(**kw))
    kw = {'searchabletext_any': 'copy',
          'reference': document_2.getReference()}
    self.assertSameSet([document_3], getAdvancedSearchStringResultList(**kw))
1119 1120 1121 1122
    kw = {'searchabletext_any': 'copy',
          'reference': document_2.getReference(),
	  'search_portal_type': 'File'}
    self.assertSameSet([], getAdvancedSearchStringResultList(**kw))
1123 1124
  
    # search by version
1125
    kw = {'reference': document_2.getReference(),
1126
          'version': document_2.getVersion()}
1127
    self.assertSameSet([document_2], getAdvancedSearchStringResultList(**kw))
1128
    kw = {'reference': document_2.getReference(),
1129 1130 1131
          'version': document_2.getVersion(),
          'search_portal_type': 'File'}
    self.assertSameSet([], getAdvancedSearchStringResultList(**kw))
1132 1133
   
    # search by language
1134
    kw = {'reference': document_2.getReference(),
1135 1136
          'language': document_2.getLanguage()}
    self.assertSameSet([document_2], getAdvancedSearchStringResultList(**kw))
1137
    kw = {'reference': document_2.getReference(),
1138 1139
          'language': document_3.getLanguage()}
    self.assertSameSet([document_3], getAdvancedSearchStringResultList(**kw))
1140
    kw = {'reference': document_2.getReference(),
1141
          'language': document_3.getLanguage(),
1142
          'search_portal_type': 'File'}
1143
    self.assertSameSet([], getAdvancedSearchStringResultList(**kw))
1144
  
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
    # only my docs
    ERP5TypeTestCase.login(self, 'user1')
    kw = {'searchabletext_any': 'owner'}
    # should return all documents matching a word no matter if we're owner or not
    self.assertSameSet([web_page_1, document_4], getAdvancedSearchStringResultList(**kw))
    kw = {'searchabletext_any': 'owner',
          'mine': 'yes'}
    # should return ONLY our own documents matching a word
    self.assertSameSet([document_4], getAdvancedSearchStringResultList(**kw))
    self.login()
    
    # only newest versions
    # should return ALL documents for a reference
    kw = {'reference': web_page_1.getReference()}
    self.assertSameSet([web_page_1, web_page_2, web_page_3], getAdvancedSearchStringResultList(**kw))
    # should return ONLY newest document for a reference
    kw = {'reference': web_page_1.getReference(),
          'newest': 'yes'}
    self.assertSameSet([web_page_3], getAdvancedSearchStringResultList(**kw))

    # contributor title search
    kw = {'searchabletext_any': 'owner'}
    # should return all documents matching a word no matter of contributor
    self.assertSameSet([web_page_1, document_4], getAdvancedSearchStringResultList(**kw))
    kw = {'searchabletext_any': 'owner',
          'contributor_title': '%Contributor%'}
    self.assertSameSet([document_4], getAdvancedSearchStringResultList(**kw))
1172
    # XXX: search limited to a certain date range
1173 1174
    # XXX: search mode

1175

1176 1177 1178 1179 1180 1181 1182
  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
1183
                 document._convertToHTML().replace('&nbsp;', ' '))
1184 1185 1186
    self.assert_('I use reference to look up TEST' in
                 document.SearchableText())

1187 1188 1189 1190 1191 1192 1193 1194 1195
  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])
Fabien Morin's avatar
Fabien Morin committed
1196

1197 1198 1199 1200 1201 1202 1203 1204
  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'])
1205
    self.assertEquals('application/pdf', document.getContentType())
1206

1207 1208 1209 1210 1211 1212 1213 1214 1215
  def test_PDF_content_information_extra_metadata(self):
    # Extra metadata, such as those stored by pdftk update_info are also
    # available in document.getContentInformation()
    upload_file = makeFileUpload('metadata.pdf')
    document = self.portal.portal_contributions.newContent(file=upload_file)
    self.assertEquals('PDF', document.getPortalType())
    content_information = document.getContentInformation()
    self.assertEquals('the value', content_information['NonStandardMetadata'])

1216 1217
  def test_PDF_content_content_type(self):
    upload_file = makeFileUpload('REF-en-001.pdf')
1218 1219 1220 1221
    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.
    document.edit(file=upload_file)
1222
    self.assertEquals('application/pdf', document.getContentType())
1223

1224 1225 1226 1227 1228 1229 1230
  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())

1231 1232 1233 1234 1235
  def test_Base_showFoundText(self):
    # Create document with good content
    document = self.portal.document_module.newContent(portal_type='Drawing')
    self.assertEquals('empty', document.getExternalProcessingState())

1236
    upload_file = makeFileUpload('TEST-en-002.odt')
1237
    document.edit(file=upload_file)
1238
    self.stepTic()
1239 1240
    self.assertEquals('converted', document.getExternalProcessingState())

1241
    # Upload different type of file inside which can not be converted to base format
1242 1243
    upload_file = makeFileUpload('REF-en-001.pdf')
    document.edit(file=upload_file)
1244
    self.stepTic()
1245
    self.assertEquals('application/pdf', document.getContentType())
1246
    self.assertEquals('conversion_failed', document.getExternalProcessingState())
1247 1248 1249 1250
    # 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)
Fabien Morin's avatar
Fabien Morin committed
1251
    self.assertEquals('This document is not converted yet.',
1252
                      document.Base_showFoundText())
1253 1254 1255 1256 1257 1258
    
    # upload again good content
    upload_file = makeFileUpload('TEST-en-002.odt')
    document.edit(file=upload_file)
    self.stepTic()
    self.assertEquals('converted', document.getExternalProcessingState())
1259

1260
  def test_Base_createNewFile(self):
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
    """
      Test contributing a file and attaching it to context.
    """
    person = self.portal.person_module.newContent(portal_type='Person')
    contributed_document = person.Base_contribute(
                                     portal_type=None,
                                     title=None,
                                     reference=None,
                                     short_title=None,
                                     language=None,
                                     version=None,
                                     description=None,
                                     attach_document_to_context=True,
                                     file=makeFileUpload('TEST-en-002.odt'))
    self.assertEquals('Text', contributed_document.getPortalType())
    self.stepTic()
    document_list = person.getFollowUpRelatedValueList()
1278 1279 1280 1281 1282
    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())
1283
    self.assertEquals(contributed_document, document)
1284 1285

  def test_Base_createNewFile_empty(self):
Ivan Tyagov's avatar
Typo.  
Ivan Tyagov committed
1286
    """
1287 1288 1289
      Test contributing an empty file and attaching it to context.
    """
    person = self.portal.person_module.newContent(portal_type='Person')
1290 1291 1292 1293 1294 1295
    empty_file_upload = ZPublisher.HTTPRequest.FileUpload(FieldStorage(
                            fp=StringIO.StringIO(),
                            environ=dict(REQUEST_METHOD='PUT'),
                            headers={"content-disposition":
                              "attachment; filename=empty;"}))

1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
    contributed_document = person.Base_contribute(
                                    portal_type=None,
                                    title=None,
                                    reference=None,
                                    short_title=None,
                                    language=None,
                                    version=None,
                                    description=None,
                                    attach_document_to_context=True,
                                    file=empty_file_upload)
    self.stepTic()
    document_list = person.getFollowUpRelatedValueList()
1308 1309 1310 1311
    self.assertEquals(1, len(document_list))
    document = document_list[0]
    self.assertEquals('empty', document.getExternalProcessingState())
    self.assertEquals('File', document.getPortalType())
1312
    self.assertEquals(contributed_document, document)
1313

1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
  def test_HTML_to_ODT_conversion_keep_enconding(self):
    """This test perform an PDF conversion of HTML content
    then to plain text.
    Check that encoding remains.
    """
    web_page_portal_type = 'Web Page'
    string_to_test = 'éààéôù'
    web_page = self.portal.getDefaultModule(web_page_portal_type)\
          .newContent(portal_type=web_page_portal_type)
    html_content = '<p>%s</p>' % string_to_test
    web_page.edit(text_content=html_content)
    mime_type, pdf_data = web_page.convert('pdf')
    text_content = self.portal.portal_transforms.\
                                      convertToData('text/plain',
                                          str(pdf_data),
                                          object=web_page, context=web_page,
                                          filename='test.pdf')
    self.assertTrue(string_to_test in text_content)
1332

1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
  def test_HTML_to_ODT_conversion_keep_related_image_list(self):
    """This test create a Web Page and an Image.
    HTML content of Web Page referred to that Image with it's reference.
    Check that ODT conversion of Web Page embed image data.
    """
    # create web page
    web_page_portal_type = 'Web Page'
    web_page = self.portal.getDefaultModule(web_page_portal_type)\
          .newContent(portal_type=web_page_portal_type)
    image_reference = 'MY-TESTED-IMAGE'
    # Target image with it reference only
    html_content = '<p><img src="%s"/></p>' % image_reference
    web_page.edit(text_content=html_content)

    # Create image
    image_portal_type = 'Image'
    image = self.portal.getDefaultModule(image_portal_type)\
          .newContent(portal_type=image_portal_type)

1352
    # edit content and publish it
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
    upload_file = makeFileUpload('cmyk_sample.jpg')
    image.edit(reference=image_reference,
               version='001',
               language='en',
               file=upload_file)
    image.publish()

    transaction.commit()
    self.tic()

    # convert web_page into odt
    mime_type, odt_archive = web_page.convert('odt')
    builder = OOoBuilder(odt_archive)
    image_count = builder._image_count
1367 1368
    failure_message = 'Expected image not found in ODF zipped archive'
    # fetch image from zipped archive content then compare with ERP5 Image
1369 1370
    self.assertEquals(builder.extract('Pictures/%s.jpeg' % image_count),
                      image.getData(), failure_message)
1371

1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
    # Continue the test with image resizing support
    image_display = 'large'
    # Add url parameters
    html_content = '<p><img src="%s?display=%s&quality=75"/></p>' % \
                                              (image_reference, image_display)
    web_page.edit(text_content=html_content)
    mime_type, odt_archive = web_page.convert('odt')
    builder = OOoBuilder(odt_archive)
    image_count = builder._image_count
    # compute resized image for comparison
    mime, converted_image = image.convert(format='jpeg', display=image_display)
    # fetch image from zipped archive content
    # then compare with resized ERP5 Image
    self.assertEquals(builder.extract('Pictures/%s.jpeg' % image_count),
                      converted_image, failure_message)

1388 1389 1390 1391 1392 1393 1394 1395
  def test_addContributorToDocument(self):
    """
      Test if current authenticated user is added to contributor list of document
      (only if authenticated user is an ERP5 Person object)
    """
    portal = self.portal
    document_module = portal.document_module

1396
    # create Person objects and add pseudo local security
1397 1398 1399 1400
    person1 =  self.createUser(reference='contributor1')
    document_module.manage_setLocalRoles('contributor1', ['Assignor',])
    person2 =  self.createUser(reference='contributor2')
    document_module.manage_setLocalRoles('contributor2', ['Assignor',])
1401 1402 1403
    self.stepTic()

    # login as first one
1404
    ERP5TypeTestCase.login(self, 'contributor1')
1405 1406 1407 1408 1409 1410 1411 1412
    doc = document_module.newContent(portal_type='File', 
                                     title='Test1')
    self.stepTic()
    self.login()
    self.assertSameSet([person1], 
                       doc.getContributorValueList())

    # login as second one
1413
    ERP5TypeTestCase.login(self, 'contributor2')
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
    doc.edit(title='Test2')
    self.stepTic()
    self.login()
    self.assertSameSet([person1, person2], 
                       doc.getContributorValueList())

    # editing with non ERP5 Person object, nothing added to contributor
    self.login()
    doc.edit(title='Test3')
    self.stepTic()
    self.assertSameSet([person1, person2], 
                       doc.getContributorValueList())
1426

1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
  def test_safeHTML_conversion(self):
    """This test create a Web Page and test asSafeHTML conversion.
    Test also with a very non well-formed html document
    to stress conversion engine.
    """
    # create web page
    web_page_portal_type = 'Web Page'
    module = self.portal.getDefaultModule(web_page_portal_type)
    web_page = module.newContent(portal_type=web_page_portal_type)

    html_content = """<html>
      <head>
        <title>My dirty title</title>
1440 1441 1442 1443
        <style type="text/css">
          a {color: #FFAA44;}
        </style>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
1444 1445 1446 1447 1448 1449 1450 1451
      </head>
      <body>
        <div>
          <h1>My splendid title</h1>
        </div>
        <script type="text/javascript" src="http://example.com/something.js"/>
      </body>
    </html>
1452
    """.decode('utf-8').encode('iso-8859-1')
1453 1454
    web_page.edit(text_content=html_content)

1455 1456 1457
    # Check that outputed stripped html is safe

    safe_html = web_page.asStrippedHTML()
1458 1459 1460
    self.assertTrue('My splendid title' in safe_html)
    self.assertTrue('script' not in safe_html, safe_html)
    self.assertTrue('something.js' not in safe_html, safe_html)
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
    self.assertTrue('<body>' not in safe_html)
    self.assertTrue('<head>' not in safe_html)
    self.assertTrue('<style' not in safe_html)
    self.assertTrue('#FFAA44' not in safe_html)

    # Check that outputed entire html is safe
    entire_html = web_page.asEntireHTML()
    self.assertTrue('My splendid title' in entire_html)
    self.assertTrue('script' not in entire_html, entire_html)
    self.assertTrue('something.js' not in entire_html, entire_html)
    self.assertTrue('<title>' in entire_html)
    self.assertTrue('<body>' in entire_html)
    self.assertTrue('<head>' in entire_html)
    self.assertTrue('<style' in entire_html)
    self.assertTrue('#FFAA44' in entire_html)
1476 1477

    # now check converted value is stored in cache
1478
    format = 'html'
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
    self.assertTrue(web_page.hasConversion(format=format))
    web_page.edit(text_content=None)
    self.assertFalse(web_page.hasConversion(format=format))

    # test with not well-formed html document
    html_content = """
    <HTML dir=3Dltr><HEAD>=0A=
<META http-equiv=3DContent-Type content=3D"text/html; charset=3Dunicode">=0A=
<META content=3D"DIRTYHTML 6.00.2900.2722" name=3DGENERATOR></HEAD>=0A=

<BODY>=0A=
<DIV><FONT face=3D"Times New Roman" color=3D#000000 size=3D3>blablalba</FONT></DIV>=0A=
<DIV>&nbsp;</DIV>=0A=
<DIV></DIV>=0A=
<DIV>&nbsp;</DIV>=0A=
<DIV>&nbsp;</DIV>=0A=
<DIV>&nbsp;</DIV>=0A=
<br>=
<!DOCTYPE html PUBLIC \\\"-//W3C//DTD XHTML 1.0 Transitional//EN\\\\=
" \\\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\\\">=
=0A<html xmlns=3D\\\"http://www.w3.org/1999/xhtml\\\">=0A<head>=0A<m=
eta http-equiv=3D\\\"Content-Type\\\" content=3D\\\"text/html; c=
harset=3Diso-8859-1\\\" />=0A<style type=3D\\\"text/css\\\">=0A<=
!--=0A.style1 {font-size: 8px}=0A.style2 {font-family: Arial, Helvetica, san=
s-serif}=0A.style3 {font-size: 8px; font-family: Arial, Helvetica, sans-seri=
f; }=0A-->=0A</style>=0A</head>=0A=0A<body>=0A<div>=0A  <p><span class=3D\\=
\\"style1\\\"><span class=3D\\\"style2\\\"><strong>I'm inside very broken HTML code</strong><br />=0A    ERP5<br />=0A
ERP5
<br />=0A    =
</span></span></p>=0A  <p class=3D\\\"sty=
le3\\\">ERP5:<br />=0A   </p>=0A  <p class=3D\\\"style3\\\"><strong>ERP5</strong>=

<br />=0A    ERP5</p>=0A</di=
v>=0A</body>=0A</html>=0A
<br>=
Nicolas Delaby's avatar
Nicolas Delaby committed
1514 1515
<!-- This is a comment, This string AZERTYY shouldn't be dislayed-->
<style>
1516
<!-- a {color: #FFAA44;} -->
Nicolas Delaby's avatar
Nicolas Delaby committed
1517
</style>
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
<table class=3DMoNormalTable border=3D0 cellspacing=3D0 cellpadding=3D0 =
width=3D64
 style=3D'width:48.0pt;margin-left:-.75pt;border-collapse:collapse'>
 <tr style=3D'height:15.0pt'>
  <td width=3D64 nowrap valign=3Dbottom =
style=3D'width:48.0pt;padding:0cm 5.4pt 0cm 5.4pt;
  height:15.0pt'>
  <p class=3DMoNormal><span =
style=3D'color:black'>05D65812<o:p></o:p></span></p>
  </td>
 </tr>
</table>
1530 1531 1532
</BODY></HTML>
    """
    web_page.edit(text_content=html_content)
1533
    safe_html = web_page.asStrippedHTML()
1534 1535
    self.assertTrue('inside very broken HTML code' in safe_html)
    self.assertTrue('AZERTYY' not in safe_html)
1536
    self.assertTrue('#FFAA44' in safe_html)
1537

1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
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)
1561 1562
    if default_pref.getPreferenceState() != 'global':
      default_pref.enable()
1563
    transaction.commit()
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
    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):
1576 1577
    return ('erp5_base',
            'erp5_ingestion', 'erp5_ingestion_mysql_innodb_catalog',
1578
            'erp5_web', 'erp5_dms')
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588

  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)

1589
    transaction.commit()
1590 1591 1592 1593 1594 1595
    self.tic()

    document.submit()

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

1596
    transaction.commit()
1597 1598 1599 1600
    self.tic()

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

1601 1602 1603 1604
  def test_DownloadableDocumentSize(self):
    '''Check that once the document is converted and cached, its size is
    correctly set'''
    portal = self.getPortalObject()
1605 1606
    portal_type = 'Text'
    document_module = portal.getDefaultModule(portal_type)
1607 1608

    # create a text document in document module
1609
    text_document = document_module.newContent(portal_type=portal_type,
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
                                               reference='Foo_001',
                                               title='Foo_OO1')
    f = makeFileUpload('Foo_001.odt')
    text_document.edit(file=f.read())
    f.close()
    transaction.commit()
    self.tic()

    # the document should be automatically converted to html
    self.assertEquals(text_document.getExternalProcessingState(), 'converted')

    # check there is nothing in the cache for pdf conversion
    self.assertFalse(text_document.hasConversion(format='pdf'))

    # call pdf conversion, in this way, the result should be cached
1625 1626
    mime_type, pdf_data = text_document.convert(format='pdf')
    pdf_size = len(pdf_data)
1627 1628 1629 1630 1631 1632 1633


    # check there is a cache entry for pdf conversion of this document
    self.assertTrue(text_document.hasConversion(format='pdf'))

    # check the size of the pdf conversion
    self.assertEquals(text_document.getConversionSize(format='pdf'), pdf_size)
1634

1635 1636 1637
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestDocument))
1638
  suite.addTest(unittest.makeSuite(TestDocumentWithSecurity))
1639
  return suite
Bartek Górny's avatar
Bartek Górny committed
1640 1641


Fabien Morin's avatar
Fabien Morin committed
1642
# vim: syntax=python shiftwidth=2