testDms.py 108 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.ERP5TypeTestCase import  _getConversionServerDict
58
from Products.ERP5Type.tests.utils import FileUpload
59
from Products.ERP5Type.tests.utils import DummyLocalizer
60
from Products.ERP5OOo.OOoUtils import OOoBuilder
61
from Products.CMFCore.utils import getToolByName
Jérome Perrin's avatar
Jérome Perrin committed
62
from AccessControl.SecurityManagement import newSecurityManager
63
from AccessControl import getSecurityManager
Bartek Górny's avatar
Bartek Górny committed
64
from zLOG import LOG
65
from Products.ERP5.Document.Document import NotConvertedError
66
from Products.ERP5Form.PreferenceTool import Priority
67
from Products.ERP5Type.tests.utils import createZODBPythonScript
68
from Products.ERP5Type.Globals import get_request
Bartek Górny's avatar
Bartek Górny committed
69
import os
70 71
from threading import Thread
import httplib
72
import urllib
73
import difflib
74
from AccessControl import Unauthorized
75
from Products.ERP5Type import Permissions
Ivan Tyagov's avatar
Ivan Tyagov committed
76
from Products.ERP5Type.tests.backportUnittest import expectedFailure
Bartek Górny's avatar
Bartek Górny committed
77

Bartek Górny's avatar
Bartek Górny committed
78 79
QUIET = 0

80
TEST_FILES_HOME = os.path.join(os.path.dirname(__file__), 'test_document')
81 82
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}))?"
83

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

87 88 89 90 91
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
92

93
class TestDocumentMixin(ERP5TypeTestCase):
94
  def setUpOnce(self):
95 96
    # set a dummy localizer (because normally it is cookie based)
    self.portal.Localizer = DummyLocalizer()
97 98 99 100
    # 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)
101 102
    transaction.commit()
    self.tic()
Bartek Górny's avatar
Bartek Górny committed
103

104
  def afterSetUp(self):
105
    TestDocumentMixin.login(self)
106 107 108 109
    self.setDefaultSitePreference()
    self.setSystemPreference()
    transaction.commit()
    self.tic()
110
    self.login()
111

112 113
  def setDefaultSitePreference(self):
    default_pref = self.portal.portal_preferences.default_site_preference
114 115 116
    conversion_dict = _getConversionServerDict()
    default_pref.setPreferredOoodocServerAddress(conversion_dict['hostname'])
    default_pref.setPreferredOoodocServerPortNumber(conversion_dict['port'])
117 118
    default_pref.setPreferredDocumentFileNameRegularExpression(FILE_NAME_REGULAR_EXPRESSION)
    default_pref.setPreferredDocumentReferenceRegularExpression(REFERENCE_REGULAR_EXPRESSION)
119
    if self.portal.portal_workflow.isTransitionPossible(default_pref, 'enable'):
120
      default_pref.enable()
121
    return default_pref
122

123 124 125 126 127 128 129 130 131
  def setSystemPreference(self):
    portal_type = 'System Preference'
    preference_list = self.portal.portal_preferences.contentValues(
                                                       portal_type=portal_type)
    if not preference_list:
      preference = self.portal.portal_preferences.newContent(
                                                       portal_type=portal_type)
    else:
      preference = preference_list[0]
132
    if self.portal.portal_workflow.isTransitionPossible(preference, 'enable'):
133 134 135
      preference.enable()
    return preference

Bartek Górny's avatar
Bartek Górny committed
136 137 138 139
  def getDocumentModule(self):
    return getattr(self.getPortal(),'document_module')

  def getBusinessTemplateList(self):
140 141
    return ('erp5_base',
            'erp5_ingestion', 'erp5_ingestion_mysql_innodb_catalog',
142
            'erp5_web', 'erp5_dms')
Bartek Górny's avatar
Bartek Górny committed
143 144

  def getNeededCategoryList(self):
145
    return ()
Bartek Górny's avatar
Bartek Górny committed
146

147
  def beforeTearDown(self):
148 149 150 151
    """
      Do some stuff after each test:
      - clear document module
    """
152
    transaction.abort()
153
    self.clearRestrictedSecurityHelperScript()
154 155 156 157 158 159 160
    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
161
    self.clearDocumentModule()
162

163 164 165
  conversion_format_permission_script_id_list = [
      'Document_checkConversionFormatPermission',
      'PDF_checkConversionFormatPermission']
166
  def clearRestrictedSecurityHelperScript(self):
167 168 169 170 171
    for script_id in self.conversion_format_permission_script_id_list:
      custom = self.getPortal().portal_skins.custom
      if script_id in custom.objectIds():
        custom.manage_delObjects(ids=[script_id])
        transaction.commit()
172

173
  def clearDocumentModule(self):
Bartek Górny's avatar
Bartek Górny committed
174
    """
175
      Remove everything after each run
Bartek Górny's avatar
Bartek Górny committed
176
    """
177
    transaction.abort()
178
    doc_module = self.getDocumentModule()
179
    doc_module.manage_delObjects(list(doc_module.objectIds()))
180
    transaction.commit()
181 182
    self.tic()

183 184 185 186 187 188 189 190 191 192 193
class TestDocument(TestDocumentMixin):
  """
    Test basic document - related operations
  """

  def getTitle(self):
    return "DMS"

  ## setup

  
194
  ## helper methods
Bartek Górny's avatar
Bartek Górny committed
195

196
  def createTestDocument(self, file_name=None, portal_type='Text', reference='TEST', version='002', language='en'):
Bartek Górny's avatar
Bartek Górny committed
197 198 199
    """
      Creates a text document
    """
200
    dm=self.getPortal().document_module
201
    doctext=dm.newContent(portal_type=portal_type)
Bartek Górny's avatar
Bartek Górny committed
202
    if file_name is not None:
203
      f = open(makeFilePath(file_name), 'rb')
Bartek Górny's avatar
Bartek Górny committed
204 205 206 207 208
      doctext.setTextContent(f.read())
      f.close()
    doctext.setReference(reference)
    doctext.setVersion(version)
    doctext.setLanguage(language)
209
    return doctext
Bartek Górny's avatar
Bartek Górny committed
210

Bartek Górny's avatar
Bartek Górny committed
211 212 213 214 215 216 217 218
  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)

219 220 221
  def clearCache(self):
    self.portal.portal_caches.clearAllCache()

222 223
  ## tests

224
  def test_01_HasEverything(self):
Bartek Górny's avatar
Bartek Górny committed
225 226 227
    """
      Standard test to make sure we have everything we need - all the tools etc
    """
228 229 230 231 232 233
    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)
234

235
  def test_02_RevisionSystem(self):
Bartek Górny's avatar
Bartek Górny committed
236 237 238 239
    """
      Test revision mechanism
    """
    # create a test document
240
    # revision should be 1
Bartek Górny's avatar
Bartek Górny committed
241
    # upload file (can be the same) into it
242
    # revision should now be 2
243 244
    # edit the document with any value or no values
    # revision should now be 3
Bartek Górny's avatar
Bartek Górny committed
245
    # contribute the same file through portal_contributions
246 247
    # the same document should now have revision 4 (because it should have done mergeRevision)
    # getRevisionList should return (1, 2, 3, 4)
248 249 250
    filename = 'TEST-en-002.doc'
    file = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=file)
251
    transaction.commit()
252 253 254 255
    self.tic()
    document_url = document.getRelativeUrl()
    def getTestDocument():
      return self.portal.restrictedTraverse(document_url)
256
    self.assertEqual(getTestDocument().getRevision(), '1')
257
    getTestDocument().edit(file=file)
258
    transaction.commit()
259
    self.tic()
260
    self.assertEqual(getTestDocument().getRevision(), '2')
261
    getTestDocument().edit(title='Hey Joe')
262
    transaction.commit()
263
    self.tic()
264
    self.assertEqual(getTestDocument().getRevision(), '3')
265
    another_document = self.portal.portal_contributions.newContent(file=file)
266
    transaction.commit()
267
    self.tic()
268 269
    self.assertEqual(getTestDocument().getRevision(), '4')
    self.assertEqual(getTestDocument().getRevisionList(), ['1', '2', '3', '4'])
Bartek Górny's avatar
Bartek Górny committed
270

271
  def test_03_Versioning(self):
Bartek Górny's avatar
Bartek Górny committed
272 273 274
    """
      Test versioning
    """
275 276 277 278 279 280 281 282 283 284 285 286 287 288
    # 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')
289
    transaction.commit()
290 291 292 293 294
    self.tic()
    self.failIf(docs[1].isVersionUnique())
    self.failIf(docs[2].isVersionUnique())
    self.failUnless(docs[3].isVersionUnique())
    docs[2].setVersion('003')
295
    transaction.commit()
296 297 298 299 300 301 302 303 304
    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
305

306
  def test_04_VersioningWithLanguage(self):
Bartek Górny's avatar
Bartek Górny committed
307 308 309 310 311 312 313 314 315
    """
      Test versioning with multi-language support
    """
    # 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
316
    # the following calls (on any doc) should produce the following output:
Bartek Górny's avatar
Bartek Górny committed
317 318 319 320 321 322 323
    # getOriginalLanguage() = 'en'
    # getLanguageList = ('en', 'fr', 'pl', 'sp')
    # getLatestVersionValue() = 4
    # getLatestVersionValue('en') = 4
    # getLatestVersionValue('fr') = 2
    # getLatestVersionValue('pl') = 3
    # getLatestVersionValue('ru') = None
324
    # change user language into 'sp'
Bartek Górny's avatar
Bartek Górny committed
325
    # getLatestVersionValue() = 5
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    # 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)
343
    transaction.commit()
344 345 346 347 348 349 350 351 352 353 354 355 356
    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')
357
    transaction.commit()
358 359
    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
360

361
  def test_06_testExplicitRelations(self):
Bartek Górny's avatar
Bartek Górny committed
362 363 364 365 366 367 368 369 370 371 372 373
    """
      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.
    """
    # 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
374
    # getSimilarCloudValueList on 4 should return 1, 3 and 5
Bartek Górny's avatar
Bartek Górny committed
375
    # getSimilarCloudValueList(depth=1) on 4 should return 3 and 5
Fabien Morin's avatar
Fabien Morin committed
376

377 378 379 380 381 382 383 384
    # 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
385 386

    document6 = self.portal.document_module.newContent(reference='SIX', version='001',
387
                                                                                    language='en',  **kw)
Fabien Morin's avatar
Fabien Morin committed
388
    document7 = self.portal.document_module.newContent(reference='SEVEN', version='001',
389
                                                                                    language='en',  **kw)
Fabien Morin's avatar
Fabien Morin committed
390
    document8 = self.portal.document_module.newContent(reference='SEVEN', version='001',
391
                                                                                    language='fr',  **kw)
Fabien Morin's avatar
Fabien Morin committed
392
    document9 = self.portal.document_module.newContent(reference='EIGHT', version='001',
393
                                                                                    language='en',  **kw)
Fabien Morin's avatar
Fabien Morin committed
394
    document10 = self.portal.document_module.newContent(reference='EIGHT', version='002',
395
                                                                                      language='en',  **kw)
Fabien Morin's avatar
Fabien Morin committed
396
    document11 = self.portal.document_module.newContent(reference='TEN', version='001',
397
                                                                                      language='en',  **kw)
Fabien Morin's avatar
Fabien Morin committed
398
    document12 = self.portal.document_module.newContent(reference='TEN', version='001',
399
                                                                                      language='fr',  **kw)
Fabien Morin's avatar
Fabien Morin committed
400
    document13 = self.portal.document_module.newContent(reference='TEN', version='002',
401
                                                                                      language='en',  **kw)
Romain Courteaud's avatar
Romain Courteaud committed
402 403 404 405

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

407 408 409
    document6.setSimilarValueList([document8,  document13])
    document7.setSimilarValue([document9])
    document11.setSimilarValue(document7)
Romain Courteaud's avatar
Romain Courteaud committed
410

411
    transaction.commit()
Romain Courteaud's avatar
Romain Courteaud committed
412
    self.tic()
Fabien Morin's avatar
Fabien Morin committed
413

414 415
    #if user language is 'en'
    self.portal.Localizer.changeLanguage('en')
Romain Courteaud's avatar
Romain Courteaud committed
416

417
    # 4 is similar to 3 and 5, 3 similar to 1, last version are the same
Romain Courteaud's avatar
Romain Courteaud committed
418 419 420 421
    self.assertSameSet([document1, document3, document5],
                       document4.getSimilarCloudValueList())
    self.assertSameSet([document3, document5],
                       document4.getSimilarCloudValueList(depth=1))
Bartek Górny's avatar
Bartek Górny committed
422

Fabien Morin's avatar
Fabien Morin committed
423
    self.assertSameSet([document7, document13],
424
                       document6.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
425
    self.assertSameSet([document10, document13],
426
                       document7.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
427
    self.assertSameSet([document7, document13],
428
                       document9.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
429
    self.assertSameSet([],
430 431
                       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
432
    self.assertSameSet([document7, document10],
433
                       document11.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
434
    self.assertSameSet([document6, document7],
435 436
                       document13.getSimilarCloudValueList())

437
    transaction.commit()
Fabien Morin's avatar
Fabien Morin committed
438

439 440
    # 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
441 442

    self.assertSameSet([document8, document13],
443
                       document6.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
444
    self.assertSameSet([document6, document13],
445
                       document8.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
446
    self.assertSameSet([document8, document10],
447
                       document11.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
448
    self.assertSameSet([],
449
                       document12.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
450
    self.assertSameSet([document6, document8],
451
                       document13.getSimilarCloudValueList())
Fabien Morin's avatar
Fabien Morin committed
452

453
    transaction.commit()
Fabien Morin's avatar
Fabien Morin committed
454

455 456
    # if user language is "bg"
    self.portal.Localizer.changeLanguage('bg')
Fabien Morin's avatar
Fabien Morin committed
457
    self.assertSameSet([document8, document13],
458 459
                       document6.getSimilarCloudValueList())

460
  def test_07_testImplicitRelations(self):
Bartek Górny's avatar
Bartek Górny committed
461 462 463 464
    """
      Test implicit (wiki-like) relations.
    """
    # XXX this test should be extended to check more elaborate language selection
465 466 467 468

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

Bartek Górny's avatar
Bartek Górny committed
469 470
    # create docs to be referenced:
    # (1) TEST, 002, en
471 472 473 474
    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
475
    # (2) TEST, 002, fr
476 477
    as_name = 'TEST-fr-002.odt'
    file = makeFileUpload(filename, as_name)
478 479
    document2 = self.portal.portal_contributions.newContent(file=file)

Bartek Górny's avatar
Bartek Górny committed
480
    # (3) TEST, 003, en
481 482
    as_name = 'TEST-en-003.odt'
    file = makeFileUpload(filename, as_name)
483 484
    document3 = self.portal.portal_contributions.newContent(file=file)

Bartek Górny's avatar
Bartek Górny committed
485 486
    # create docs to contain references in text_content:
    # REF, 001, en; "I use reference to look up TEST"
487 488 489 490
    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
491
    # REF, 002, en; "I use reference to look up TEST"
492 493 494 495
    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
496
    # REFLANG, 001, en: "I use reference and language to look up TEST-fr"
497 498 499 500
    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
501
    # REFVER, 001, en: "I use reference and version to look up TEST-002"
502 503 504 505
    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
506
    # REFVERLANG, 001, en: "I use reference, version and language to look up TEST-002-en"
507 508 509 510
    filename = 'REFVERLANG-en-001.odt'
    file = makeFileUpload(filename)
    document8 = self.portal.portal_contributions.newContent(file=file)

511
    transaction.commit()
512
    self.tic()
513 514
    # the implicit predecessor will find documents by reference.
    # version and language are not used.
Bartek Górny's avatar
Bartek Górny committed
515
    # the implicit predecessors should be:
516 517 518 519 520 521 522 523 524

    # 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
525
    transaction.commit()
526 527 528 529 530 531 532 533 534 535 536 537

    # 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
538
    transaction.commit()
539 540 541 542 543 544 545 546

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

    # clear transactional variable cache
547
    transaction.commit()
548 549 550 551 552 553

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

555 556 557 558 559 560 561 562 563 564 565
  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')
566
    doc.edit(data='OOo')
567 568
    self.assertEquals(len('OOo'), doc.get_size())

569 570 571 572 573 574 575 576 577 578 579 580 581 582
  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())
583

584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
  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(),
Nicolas Delaby's avatar
Nicolas Delaby committed
600
                      response.getBody())
601 602
    self.assertEquals('application/vnd.oasis.opendocument.spreadsheet',
                      response.headers['content-type'])
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
603
    self.assertEquals('attachment; filename="import_data_list.ods"',
604
                      response.headers['content-disposition'])
605
    self.tic()
606 607 608 609 610 611 612

  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')
613
    doc.edit(file=makeFileUpload('import.file.with.dot.in.filename.ods'))
614
    doc.publish()
615
    transaction.commit()
616
    self.tic()
617
    transaction.commit()
618 619 620 621 622 623

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

624
    response = self.publish('%s?format=pdf' % doc.getPath(),
625
                            basic='member_user2:secret')
Nicolas Delaby's avatar
Nicolas Delaby committed
626
    self.assertEquals('application/pdf', response.getHeader('content-type'))
627
    self.assertEquals('attachment; filename="import.file.with.dot.in.filename.pdf"',
Nicolas Delaby's avatar
Nicolas Delaby committed
628
                      response.getHeader('content-disposition'))
629 630 631 632 633 634 635
    response_body = response.getBody()
    conversion = str(doc.convert('pdf')[1])
    diff = '\n'+'\n'.join(difflib.unified_diff(response_body.splitlines(),
                                          conversion.splitlines(),
                                          fromfile='first_call.pdf',
                                          tofile='second_call.pdf'))
    self.assertEquals(response_body, conversion, diff)
636

637 638 639 640
    # test Print icon works on OOoDocument
    response = self.publish('%s/OOoDocument_print' % doc.getPath())
    self.assertEquals('application/pdf',
                      response.headers['content-type'])
641
    self.assertEquals('attachment; filename="import.file.with.dot.in.filename.pdf"',
642 643
                      response.headers['content-disposition'])

644
  def test_05_getCreationDate(self):
645
    """
Fabien Morin's avatar
Fabien Morin committed
646
    Check getCreationDate on all document type, as those documents
647 648 649 650 651 652 653 654 655 656 657
    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())

658 659
  def test_Base_getConversionFormatItemList(self):
    # tests Base_getConversionFormatItemList script (requires oood)
660
    self.assertTrue(('Microsoft Excel 97/2000/XP', 'xls') in
661 662 663 664 665
        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'))
666

667
  def test_06_ProcessingStateOfAClonedDocument(self):
668 669 670 671 672 673 674 675 676
    """
    Check that the processing state of a cloned document
    is not draft
    """
    filename = 'TEST-en-002.doc'
    file = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=file)

    self.assertEquals('converting', document.getExternalProcessingState())
677
    transaction.commit()
678
    self.assertEquals('converting', document.getExternalProcessingState())
679 680 681 682 683 684 685 686

    # 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())
687
    transaction.commit()
688 689 690
    self.assertEquals('converting', new_document.getExternalProcessingState())

    # Change workflow state to converted
691 692
    self.tic()
    self.assertEquals('converted', document.getExternalProcessingState())
693
    self.assertEquals('converted', new_document.getExternalProcessingState())
694

695
    # Clone a converted document
696 697 698 699 700
    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']]

701
    self.assertEquals('converted', new_document.getExternalProcessingState())
702
    transaction.commit()
703
    self.assertEquals('converted', new_document.getExternalProcessingState())
704 705 706
    self.tic()
    self.assertEquals('converted', new_document.getExternalProcessingState())

707
  def test_07_EmbeddedDocumentOfAClonedDocument(self):
708 709 710 711 712 713 714 715 716 717
    """
    Check the validation state of embedded document when its container is
    cloned
    """
    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())
718
    transaction.commit()
719 720 721 722 723 724 725 726 727 728 729 730 731 732
    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())
733
    transaction.commit()
734 735 736
    self.tic()
    self.assertEquals('embedded', new_sub_document.getValidationState())

737 738 739
  def test_08_NoImagesCreatedDuringHTMLConversion(self):
    """Converting an ODT to html no longer creates Images embedded in the
    document.
740 741 742 743 744
    """
    filename = 'EmbeddedImage-en-002.odt'
    file = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=file)

745
    transaction.commit()
746 747 748 749 750
    self.tic()

    self.assertEquals(0, len(document.contentValues(portal_type='Image')))
    document.convert(format='html')
    image_list = document.contentValues(portal_type='Image')
751
    self.assertEquals(0, len(image_list))
752

753
  def test_09_SearchableText(self):
754
    """
755
    Check DMS SearchableText capabilities.
756
    """
Ivan Tyagov's avatar
Ivan Tyagov committed
757
    portal = self.portal
758

759
    # Create a document.
Ivan Tyagov's avatar
Ivan Tyagov committed
760 761 762 763 764 765 766 767 768 769
    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
770 771 772 773 774 775
    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
776 777 778 779 780
    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
781 782 783
                                                 text_content = 'Great website',
                                                 language='en',
                                                 version = '003')
Ivan Tyagov's avatar
Ivan Tyagov committed
784 785 786 787 788
    organisation = portal.organisation_module.newContent( \
                            portal_type = 'Organisation', \
                            reference = 'organisation-1',
                            title='Super nova organisation')
    self.stepTic()
Nicolas Delaby's avatar
Nicolas Delaby committed
789

790
    def getAdvancedSearchTextResultList(searchable_text, portal_type=None,src__=0):
791 792 793
      kw = {'SearchableText': searchable_text}
      if portal_type is not None:
        kw['portal_type'] = portal_type
794 795
      if src__==1:
        print portal.portal_catalog(src__=src__,**kw)
Ivan Tyagov's avatar
Ivan Tyagov committed
796
      return [x.getObject() for x in portal.portal_catalog(**kw)]
Nicolas Delaby's avatar
Nicolas Delaby committed
797

Ivan Tyagov's avatar
Ivan Tyagov committed
798 799 800 801 802
    # full text search
    self.assertSameSet([document_1], \
      getAdvancedSearchTextResultList('ScriptableKey'))
    self.assertEqual(len(getAdvancedSearchTextResultList('RelatedKey')), 0)
    self.assertSameSet([document_1, document_2], \
803
      getAdvancedSearchTextResultList('make'))
Ivan Tyagov's avatar
Ivan Tyagov committed
804
    self.assertSameSet([web_page, person], \
805
      getAdvancedSearchTextResultList("Great", ('Person', 'Web Page')))
Ivan Tyagov's avatar
Ivan Tyagov committed
806 807 808 809 810 811 812
    # 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
813 814 815 816 817 818 819 820 821

   # 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
822 823
      getAdvancedSearchTextResultList('%s portal_type:%s' %(person.getTitle(), person.getPortalType())))

Ivan Tyagov's avatar
Ivan Tyagov committed
824
    self.assertSameSet([organisation], \
Ivan Tyagov's avatar
Ivan Tyagov committed
825 826 827
      getAdvancedSearchTextResultList('%s portal_type:%s' \
                                       %(organisation.getTitle(),
                                         organisation.getPortalType())))
828 829 830

    # full text search with portal_type passed outside searchable_text
    self.assertSameSet([web_page, person],
831 832
                       getAdvancedSearchTextResultList('Great',
                          ('Person', 'Web Page')))
833 834 835 836 837
    self.assertSameSet([web_page], \
                       getAdvancedSearchTextResultList('Great', web_page.getPortalType()))
    self.assertSameSet([person], \
                       getAdvancedSearchTextResultList('Great', person.getPortalType()))
    
Ivan Tyagov's avatar
Ivan Tyagov committed
838 839
    # full text search with portal_type & reference
    self.assertSameSet([person], \
Ivan Tyagov's avatar
Ivan Tyagov committed
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
      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())))
Ivan Tyagov's avatar
Ivan Tyagov committed
861
  @expectedFailure
862
  def test_10_SearchString(self):
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
    """
    Test search string search generation and parsing.
    """

    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)
912
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w AND (portal_type:Document)', \
913 914 915 916 917 918 919 920 921
                      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)
922
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w AND (portal_type:Document) reference:Nxd-test', \
923 924 925 926 927 928 929 930 931 932
                      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)
933
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w AND (portal_type:Document) reference:Nxd-test version:001', \
934 935 936 937 938 939 940 941 942 943 944
                      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)
945
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w AND (portal_type:Document) reference:Nxd-test version:001 language:en', \
946 947 948 949 950 951 952 953 954 955 956 957 958
                      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)
959
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w AND (portal_type:Document) reference:Nxd-test version:001 language:en contributor_title:John', \
960 961 962 963 964 965 966 967 968 969 970 971 972
                      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)
973
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w AND (portal_type:Document) reference:Nxd-test version:001 language:en contributor_title:John mine:yes', \
974 975 976 977 978 979 980 981 982 983 984 985 986 987
                      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)
988
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w AND (portal_type:Document) reference:Nxd-test version:001 language:en contributor_title:John mine:yes newest:yes', \
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
                      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)
1004
    self.assertEquals('searchabletext_any "searchabletext_phrase1 searchabletext_phrase1"  +searchabletext_all1 +searchabletext_all2 -searchabletext_without1 -searchabletext_without2 created:1w AND (portal_type:Document) reference:Nxd-test version:001 language:en contributor_title:John mine:yes newest:yes mode:boolean', \
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
                      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'])
1016

1017
    # search with multiple portal_type
1018
    kw = {'search_portal_type': ['Document','Presentation','Web Page'],
1019 1020 1021
           'searchabletext_any': 'erp5'}
    search_string = assemble(**kw)
    parsed_string = parse(search_string)
1022
    self.assertEquals('erp5 AND (portal_type:Document OR portal_type:Presentation OR portal_type:"Web Page")', \
1023 1024 1025
                      search_string)
    self.assertSameSet(['searchabletext', 'portal_type'], \
                        parsed_string.keys())
1026
    #self.assertEquals(kw['search_portal_type'], parsed_string['portal_type'])
1027

1028
    # parse with multiple portal_type containing spaces in one portal_type
1029
    search_string = 'erp5 AND (portal_type:Document OR portal_type:Presentation OR portal_type:"Web Page")'
1030
    parsed_string = parse(search_string)
1031
    self.assertEquals(parsed_string['portal_type'], ['Document','Presentation','Web Page'])
1032

Ivan Tyagov's avatar
Ivan Tyagov committed
1033
  @expectedFailure
Ivan Tyagov's avatar
Ivan Tyagov committed
1034
  def test_11_Base_getAdvancedSearchResultList(self):
1035
    """
Ivan Tyagov's avatar
Ivan Tyagov committed
1036
    Test search string search capabilities using Base_getAdvancedSearchResultList script.
1037 1038 1039 1040 1041 1042 1043 1044
    """
    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)]
1045

1046 1047 1048 1049 1050 1051 1052 1053 1054
    # 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',
1055
                   description = 'standalone free python linux knowledge system management different',
1056 1057 1058 1059 1060 1061 1062 1063 1064
                   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')
1065
    # multiple revisions of a Web Page
1066 1067
    web_page_1 = portal.web_page_module.newContent(
                   portal_type = 'Web Page',
1068
                   text_content = 'software based solutions document management product standalone owner different',
1069 1070 1071
                   version = '003',
                   language = 'jp',
                   reference = 'nxd-test-web-page-3')
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
    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()
1105
    self.stepTic()
1106
    self.login()
1107 1108 1109 1110 1111 1112

    # search arbitrary word
    kw = {'searchabletext_any': 'software'}
    self.assertSameSet([document_1,web_page_1], getAdvancedSearchStringResultList(**kw))
    
    # exact word search
1113
    kw = {'searchabletext_phrase': 'linux python'}
1114
    self.assertSameSet([document_1], getAdvancedSearchStringResultList(**kw))
1115
    kw = {'searchabletext_phrase': 'python linux'}
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
    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))
1135 1136 1137 1138 1139 1140
    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))
1141 1142
   
    # search by reference
1143
    kw = {'reference': document_2.getReference()}
1144 1145 1146 1147
    self.assertSameSet([document_2, document_3], getAdvancedSearchStringResultList(**kw))
    kw = {'searchabletext_any': 'copy',
          'reference': document_2.getReference()}
    self.assertSameSet([document_3], getAdvancedSearchStringResultList(**kw))
1148 1149
    kw = {'searchabletext_any': 'copy',
          'reference': document_2.getReference(),
1150
          'search_portal_type': 'File'}
1151
    self.assertSameSet([], getAdvancedSearchStringResultList(**kw))
1152 1153
  
    # search by version
1154
    kw = {'reference': document_2.getReference(),
1155
          'version': document_2.getVersion()}
1156
    self.assertSameSet([document_2], getAdvancedSearchStringResultList(**kw))
1157
    kw = {'reference': document_2.getReference(),
1158 1159 1160
          'version': document_2.getVersion(),
          'search_portal_type': 'File'}
    self.assertSameSet([], getAdvancedSearchStringResultList(**kw))
1161 1162
   
    # search by language
1163
    kw = {'reference': document_2.getReference(),
1164 1165
          'language': document_2.getLanguage()}
    self.assertSameSet([document_2], getAdvancedSearchStringResultList(**kw))
1166
    kw = {'reference': document_2.getReference(),
1167 1168
          'language': document_3.getLanguage()}
    self.assertSameSet([document_3], getAdvancedSearchStringResultList(**kw))
1169
    kw = {'reference': document_2.getReference(),
1170
          'language': document_3.getLanguage(),
1171
          'search_portal_type': 'File'}
1172
    self.assertSameSet([], getAdvancedSearchStringResultList(**kw))
1173
  
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
    # 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))
1201 1202 1203 1204 1205

    # multiple portal_type specified
    kw = {'search_portal_type': 'File,Presentation'}
    self.assertSameSet([document_1, document_2, document_3, document_4], getAdvancedSearchStringResultList(**kw))

1206
    # XXX: search limited to a certain date range
1207 1208
    # XXX: search mode

1209 1210 1211 1212 1213 1214 1215
  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
1216
                 document._convertToHTML().replace('&nbsp;', ' '))
1217 1218 1219
    self.assert_('I use reference to look up TEST' in
                 document.SearchableText())

1220 1221 1222 1223
  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())
Nicolas Delaby's avatar
Nicolas Delaby committed
1224

1225
    content_type, image_data = document.convert(format='png',
Nicolas Delaby's avatar
Nicolas Delaby committed
1226 1227
                                                frame=0,
                                                display='thumbnail')
1228 1229
    # it's a valid PNG
    self.assertEquals('PNG', image_data[1:4])
Fabien Morin's avatar
Fabien Morin committed
1230

1231 1232 1233 1234 1235 1236 1237 1238
  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'])
1239
    self.assertEquals('application/pdf', document.getContentType())
1240

1241 1242 1243
  def test_PDF_content_information_extra_metadata(self):
    # Extra metadata, such as those stored by pdftk update_info are also
    # available in document.getContentInformation()
1244
    upload_file = makeFileUpload('metadata.pdf', as_name='REF-en-001.pdf')
1245
    document = self.portal.portal_contributions.newContent(file=upload_file)
1246
    self.stepTic()
1247 1248
    self.assertEquals('PDF', document.getPortalType())
    content_information = document.getContentInformation()
1249
    self.assertEquals('the value', content_information['NonStandardMetadata'])
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
    self.assertEquals('1', content_information['Pages'])
    self.assertEquals('REF', document.getReference())

    # contribute file which will be merged to current document in synchronous mode
    # and check content_type recalculated 
    upload_file = makeFileUpload('Forty-Two.Pages-en-001.pdf', as_name='REF-en-001.pdf')
    contributed_document = self.portal.Base_contribute(file=upload_file, \
                                                       synchronous_metadata_discovery=True)
    self.stepTic()
    content_information = contributed_document.getContentInformation()
    
    # we should have same data, respectively same PDF pages
    self.assertEqual(contributed_document.getSize(), document.getSize())
    self.assertEqual(contributed_document.getContentInformation()['Pages'], \
                     document.getContentInformation()['Pages'])
    self.assertEqual('42', \
                     document.getContentInformation()['Pages'])

    # upload with another file and check content_type recalculated
    upload_file = makeFileUpload('REF-en-001.pdf')
    document.setFile(upload_file)
    self.stepTic()
    content_information = document.getContentInformation()
    self.assertEquals('1', content_information['Pages'])    
1274

1275 1276
  def test_PDF_content_content_type(self):
    upload_file = makeFileUpload('REF-en-001.pdf')
1277 1278 1279 1280
    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)
1281
    self.assertEquals('application/pdf', document.getContentType())
1282

1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
  def test_Document_getStandardFileName(self):
    upload_file = makeFileUpload('metadata.pdf')
    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)
    self.assertEquals(document.getStandardFileName(), 'metadata.pdf')
    self.assertEquals(document.getStandardFileName(format='png'),
                      'metadata.png')
    document.setVersion('001')
    document.setLanguage('en')
    self.assertEquals(document.getStandardFileName(), 'metadata-001-en.pdf')
    self.assertEquals(document.getStandardFileName(format='png'),
                      'metadata-001-en.png')
1297 1298 1299 1300 1301 1302 1303 1304 1305
    # check when format contains multiple '.'
    upload_file = makeFileUpload('TEST-en-003.odp')
    document = self.portal.document_module.newContent(portal_type='Presentation')
    # Here we use edit instead of setFile,
    # because only edit method set filename as source_reference.
    document.edit(file=upload_file)
    self.assertEquals(document.getStandardFileName(), 'TEST-en-003.odp')
    self.assertEquals('TEST-en-003.odg', document.getStandardFileName(format='odp.odg'))

1306

1307 1308 1309 1310
  def test_CMYKImageTextContent(self):
    upload_file = makeFileUpload('cmyk_sample.jpg')
    document = self.portal.portal_contributions.newContent(file=upload_file)
    self.assertEquals('Image', document.getPortalType())
Nicolas Delaby's avatar
Nicolas Delaby committed
1311
    self.assertEquals('ERP5 is a free software.\n', document.asText())
1312

1313 1314 1315 1316 1317
  def test_Base_showFoundText(self):
    # Create document with good content
    document = self.portal.document_module.newContent(portal_type='Drawing')
    self.assertEquals('empty', document.getExternalProcessingState())

1318
    upload_file = makeFileUpload('TEST-en-002.odt')
1319
    document.edit(file=upload_file)
1320
    self.stepTic()
1321 1322
    self.assertEquals('converted', document.getExternalProcessingState())

1323
    # Upload different type of file inside which can not be converted to base format
1324 1325
    upload_file = makeFileUpload('REF-en-001.pdf')
    document.edit(file=upload_file)
1326
    self.stepTic()
1327
    self.assertEquals('application/pdf', document.getContentType())
1328
    self.assertEquals('conversion_failed', document.getExternalProcessingState())
1329 1330 1331 1332
    # 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
1333
    self.assertEquals('This document is not converted yet.',
1334
                      document.Base_showFoundText())
1335 1336 1337 1338 1339 1340
    
    # upload again good content
    upload_file = makeFileUpload('TEST-en-002.odt')
    document.edit(file=upload_file)
    self.stepTic()
    self.assertEquals('converted', document.getExternalProcessingState())
1341

1342
  def test_Base_createNewFile(self):
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
    """
      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()
1360 1361 1362 1363 1364
    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())
1365
    self.assertEquals(contributed_document, document)
1366 1367

  def test_Base_createNewFile_empty(self):
Ivan Tyagov's avatar
Typo.  
Ivan Tyagov committed
1368
    """
1369 1370 1371
      Test contributing an empty file and attaching it to context.
    """
    person = self.portal.person_module.newContent(portal_type='Person')
1372 1373 1374 1375 1376 1377
    empty_file_upload = ZPublisher.HTTPRequest.FileUpload(FieldStorage(
                            fp=StringIO.StringIO(),
                            environ=dict(REQUEST_METHOD='PUT'),
                            headers={"content-disposition":
                              "attachment; filename=empty;"}))

1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
    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()
1390 1391 1392
    self.assertEquals(1, len(document_list))
    document = document_list[0]
    self.assertEquals('File', document.getPortalType())
1393
    self.assertEquals(contributed_document, document)
1394

1395 1396 1397 1398 1399 1400 1401 1402 1403
  def test_Base_createNewFile_forced_type(self):
    """Test contributing while forcing the portal type.
    """
    person = self.portal.person_module.newContent(portal_type='Person')
    contributed_document = person.Base_contribute(
                                     portal_type='PDF',
                                     file=makeFileUpload('TEST-en-002.odt'))
    self.assertEquals('PDF', contributed_document.getPortalType())

1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
  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)
1422

1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
  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)

1442
    # edit content and publish it
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
    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
1457 1458
    failure_message = 'Expected image not found in ODF zipped archive'
    # fetch image from zipped archive content then compare with ERP5 Image
1459 1460
    self.assertEquals(builder.extract('Pictures/%s.jpeg' % image_count),
                      image.getData(), failure_message)
1461

1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
    # 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)

1478 1479 1480 1481 1482 1483 1484 1485
  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

1486
    # create Person objects and add pseudo local security
1487 1488 1489 1490
    person1 =  self.createUser(reference='contributor1')
    document_module.manage_setLocalRoles('contributor1', ['Assignor',])
    person2 =  self.createUser(reference='contributor2')
    document_module.manage_setLocalRoles('contributor2', ['Assignor',])
1491 1492 1493
    self.stepTic()

    # login as first one
1494
    ERP5TypeTestCase.login(self, 'contributor1')
1495 1496 1497 1498 1499 1500 1501 1502
    doc = document_module.newContent(portal_type='File', 
                                     title='Test1')
    self.stepTic()
    self.login()
    self.assertSameSet([person1], 
                       doc.getContributorValueList())

    # login as second one
1503
    ERP5TypeTestCase.login(self, 'contributor2')
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
    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())
1516

1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
  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>
1529 1530
        <meta http-equiv="refresh" content="5;url=http://example.com/"/>
        <meta http-equiv="Set-Cookie" content=""/>
1531
        <title>My dirty title</title>
1532 1533 1534
        <style type="text/css">
          a {color: #FFAA44;}
        </style>
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1535
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
1536 1537 1538 1539 1540 1541
      </head>
      <body>
        <div>
          <h1>My splendid title</h1>
        </div>
        <script type="text/javascript" src="http://example.com/something.js"/>
1542 1543 1544 1545 1546
        <script type="text/javascript">
          alert("da");
        </script>
        <a href="javascript:DosomethingNasty()">Link</a>
        <a onClick="javascript:DosomethingNasty()">Another Link</a>
1547
        <p>éàèù</p>
1548 1549
      </body>
    </html>
1550
    """.decode('utf-8').encode('iso-8859-1')
1551 1552
    web_page.edit(text_content=html_content)

1553 1554
    # Check that outputed stripped html is safe
    safe_html = web_page.asStrippedHTML()
1555 1556 1557
    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)
1558 1559 1560 1561
    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)
1562 1563
    self.assertTrue('5;url=http://example.com/' not in safe_html)
    self.assertTrue('Set-Cookie' not in safe_html)
1564 1565 1566 1567
    self.assertTrue('javascript' not in safe_html)
    self.assertTrue('alert("da");' not in safe_html)
    self.assertTrue('javascript:DosomethingNasty()' not in safe_html)
    self.assertTrue('onClick' not in safe_html)
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578

    # 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)
1579
    self.assertTrue('charset=utf-8' in entire_html)
1580 1581 1582 1583
    self.assertTrue('javascript' not in entire_html)
    self.assertTrue('alert("da");' not in entire_html)
    self.assertTrue('javascript:DosomethingNasty()' not in entire_html)
    self.assertTrue('onClick' not in entire_html)
1584 1585

    # now check converted value is stored in cache
1586
    format = 'html'
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
    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
1622 1623
<!-- This is a comment, This string AZERTYY shouldn't be dislayed-->
<style>
1624
<!-- a {color: #FFAA44;} -->
Nicolas Delaby's avatar
Nicolas Delaby committed
1625
</style>
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
<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>
1638 1639 1640
<script LANGUAGE="JavaScript" type="text/javascript">
document.write('<sc'+'ript type="text/javascript" src="http://somosite.bg/utb.php"></sc'+'ript>');
</script>
1641 1642 1643
</BODY></HTML>
    """
    web_page.edit(text_content=html_content)
1644
    safe_html = web_page.asStrippedHTML()
1645 1646
    self.assertTrue('inside very broken HTML code' in safe_html)
    self.assertTrue('AZERTYY' not in safe_html)
1647
    self.assertTrue('#FFAA44' in safe_html)
1648

1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
  def test_parallel_conversion(self):
    """Check that conversion engine is able to fill in
    cache without overwrite previous conversion
    when processed at the same time.
    """
    portal_type = 'PDF'
    document_module = self.portal.getDefaultModule(portal_type)
    document = document_module.newContent(portal_type=portal_type)

    upload_file = makeFileUpload('Forty-Two.Pages-en-001.pdf')
    document.edit(file=upload_file)
    pages_number = int(document.getContentInformation()['Pages'])
    transaction.commit()
    self.tic()

1664 1665 1666 1667 1668 1669 1670 1671
    preference_tool = getToolByName(self.portal, 'portal_preferences')
    image_size = preference_tool.getPreferredThumbnailImageHeight(),\
                              preference_tool.getPreferredThumbnailImageWidth()
    convert_kw = {'format': 'png',
                  'quality': 75,
                  'display': 'thumbnail',
                  'resolution': None}

1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
    class ThreadWrappedConverter(Thread):
      """Use this class to run different convertion
      inside distinct Thread.
      """
      def __init__(self, publish_method, document_path,
                   frame_list, credential):
        self.publish_method = publish_method
        self.document_path = document_path
        self.frame_list = frame_list
        self.credential = credential
        Thread.__init__(self)

      def run(self):
        for frame in self.frame_list:
          # Use publish method to dispatch conversion among
1687 1688 1689 1690
          # all available ZServer threads.
          convert_kw['frame'] = frame
          response = self.publish_method(self.document_path,
                                         basic=self.credential,
1691
                                         extra=convert_kw.copy())
1692 1693 1694 1695

          assert response.getHeader('content-type') == 'image/png', \
                                             response.getHeader('content-type')
          assert response.getStatus() == httplib.OK
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
        transaction.commit()

    # assume there is no password
    credential = '%s:' % (getSecurityManager().getUser().getId(),)
    tested_list = []
    frame_list = list(xrange(pages_number))
    # assume that ZServer is configured with 4 Threads
    conversion_per_tread = pages_number / 4
    while frame_list:
      local_frame_list = [frame_list.pop() for i in\
                            xrange(min(conversion_per_tread, len(frame_list)))]
      instance = ThreadWrappedConverter(self.publish, document.getPath(),
                                        local_frame_list, credential)
      tested_list.append(instance)
      instance.start()

    # Wait until threads finishing
    [tested.join() for tested in tested_list]

    transaction.commit()
    self.tic()

    convert_kw = {'format': 'png',
                  'quality': 75,
                  'image_size': image_size,
1721 1722
                  'resolution': None}

1723 1724 1725
    result_list = []
    for i in xrange(pages_number):
      # all conversions should succeeded and stored in cache storage
1726
      convert_kw['frame'] = i
1727 1728 1729 1730
      if not document.hasConversion(**convert_kw):
        result_list.append(i)
    self.assertEquals(result_list, [])

1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
  def test_conversionCache_reseting(self):
    """Chack that modifying a document with edit method,
    compute a new cache key and refresh cached conversions.
    """
    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>
        <style type="text/css">
          a {color: #FFAA44;}
        </style>
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1744
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
     </head>
      <body>
        <div>
          <h1>My splendid title</h1>
        </div>
        <script type="text/javascript" src="http://example.com/something.js"/>
      </body>
    </html>
    """
    web_page.edit(text_content=html_content)
    web_page.convert(format='txt')
    self.assertTrue(web_page.hasConversion(format='txt'))
    web_page.edit(title='Bar')
    self.assertFalse(web_page.hasConversion(format='txt'))
    web_page.convert(format='txt')
    web_page.edit()
    self.assertFalse(web_page.hasConversion(format='txt'))

Nicolas Delaby's avatar
Nicolas Delaby committed
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
  def test_TextDocument_conversion_to_base_format(self):
    """Check that any files is converted into utf-8
    """
    web_page_portal_type = 'Web Page'
    module = self.portal.getDefaultModule(web_page_portal_type)
    upload_file = makeFileUpload('TEST-text-iso8859-1.txt')
    web_page = module.newContent(portal_type=web_page_portal_type,
                                 file=upload_file)

    text_content = web_page.getTextContent()
    my_utf_eight_token = 'ùééàçèîà'
    text_content = text_content.replace('\n', '\n%s\n' % my_utf_eight_token)
    web_page.edit(text_content=text_content)
    self.assertTrue(my_utf_eight_token in web_page.asStrippedHTML())
    self.assertTrue(isinstance(web_page.asEntireHTML().decode('utf-8'), unicode))

  def test_PDFDocument_asTextConversion(self):
    """Test a PDF document with embedded images
    To force usage of Ocropus portal_transform chain
    """
    portal_type = 'PDF'
    module = self.portal.getDefaultModule(portal_type)
    upload_file = makeFileUpload('TEST.Embedded.Image.pdf')
    document = module.newContent(portal_type=portal_type, file=upload_file)
    self.assertEquals(document.asText(), 'ERP5 is a free software.\n')

1789
  def createRestrictedSecurityHelperScript(self):
1790
    script_content_list = ['format=None, **kw', """
1791 1792 1793
if not format:
  return 0
return 1
1794 1795 1796 1797 1798
"""]
    for script_id in self.conversion_format_permission_script_id_list:
      createZODBPythonScript(self.getPortal().portal_skins.custom,
      script_id, *script_content_list)
      transaction.commit()
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845

  def _test_document_conversion_to_base_format_no_original_format_access(self,
      portal_type, file_name):
    module = self.portal.getDefaultModule(portal_type)
    upload_file = makeFileUpload(file_name)
    document = module.newContent(portal_type=portal_type,
                                 file=upload_file)

    transaction.commit()
    self.tic()

    self.createRestrictedSecurityHelperScript()

    from AccessControl import Unauthorized
    # check that it is not possible to access document in original format
    self.assertRaises(Unauthorized, document.convert, format=None)
    # check that it is possible to convert document to text format
    dummy = document.convert(format='text')

  def test_WebPage_conversion_to_base_format_no_original_format_access(self):
    """Checks Document.TextDocument"""
    self._test_document_conversion_to_base_format_no_original_format_access(
      'Web Page',
      'TEST-text-iso8859-1.txt'
    )

  def test_PDF_conversion_to_base_format_no_original_format_access(self):
    """Checks Document.PDFDocument"""
    self._test_document_conversion_to_base_format_no_original_format_access(
      'PDF',
      'TEST-en-002.pdf'
    )

  def test_Text_conversion_to_base_format_no_original_format_access(self):
    """Checks Document.OOoDocument"""
    self._test_document_conversion_to_base_format_no_original_format_access(
      'Text',
      'TEST-en-002.odt'
    )

  def test_Image_conversion_to_base_format_no_original_format_access(self):
    """Checks Document.Image"""
    self._test_document_conversion_to_base_format_no_original_format_access(
      'Image',
      'TEST-en-002.png'
    )

1846 1847 1848 1849
  def test_getExtensibleContent(self):
    """
      Test extensible content of some DMS types. As this is possible only on URL traversal use publish.
    """
1850 1851 1852 1853 1854
    # Create a root level zope user
    root_user_folder = self.getPortalObject().aq_parent.acl_users
    if not root_user_folder.getUser('zope_user'):
      root_user_folder._doAddUser('zope_user', '', ['Manager',], [])
      transaction.commit()
1855 1856 1857 1858 1859 1860 1861
    # Create document with good content
    document = self.portal.document_module.newContent(portal_type='Presentation')
    upload_file = makeFileUpload('TEST-en-003.odp')
    document.edit(file=upload_file)
    self.stepTic()
    self.assertEquals('converted', document.getExternalProcessingState())
    for object_url in ('img1.html', 'img2.html', 'text1.html', 'text2.html'):
1862 1863 1864 1865 1866 1867 1868 1869 1870
      for credential in ['ERP5TypeTestCase:', 'zope_user:']:
        response = self.publish('%s/%s' %(document.getPath(), object_url),
                                basic=credential)
        self.assertTrue('Status: 200 OK' in response.getOutput())
        # OOod produced HTML navigation, test it
        self.assertTrue('First page' in response.getBody())
        self.assertTrue('Back' in response.getBody())
        self.assertTrue('Continue' in response.getBody())
        self.assertTrue('Last page' in response.getBody())
1871

1872 1873 1874 1875 1876 1877
  def test_contributeLink(self):
    """
      Test contributing a link.
    """
    portal = self.portal
    kw = {'url':portal.absolute_url()}
1878
    web_page_1 = portal.Base_contribute(**kw)
1879
    self.stepTic()
1880
    self.assertTrue(web_page_1.getRevision()=='2')
1881
    
1882
    web_page_2 = portal.Base_contribute(**kw)
1883
    self.stepTic()
1884 1885
    self.assertTrue(web_page_1==web_page_2)
    self.assertTrue(web_page_2.getRevision()=='3')
1886

1887
    web_page_3 = portal.Base_contribute(**kw)
1888
    self.stepTic()
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
    self.assertTrue(web_page_2==web_page_3)
    self.assertTrue(web_page_3.getRevision()=='4')

    # test in synchronous mode
    kw['synchronous_metadata_discovery']=True
    web_page_4 = portal.Base_contribute(**kw)
    self.stepTic()
    self.assertTrue(web_page_3==web_page_4)
    self.assertTrue(web_page_4.getRevision()=='5')

    web_page_5 = portal.Base_contribute(**kw)
    self.stepTic()
    self.assertTrue(web_page_4==web_page_5)
    self.assertTrue(web_page_5.getRevision()=='6')

    web_page_6 = portal.Base_contribute(**kw)
    self.stepTic()
    self.assertTrue(web_page_5==web_page_6)
    self.assertTrue(web_page_6.getRevision()=='7')
1908

1909 1910 1911 1912 1913
    # test contribute link is a safe html (duplicates parts of test_safeHTML_conversion)
    web_page_6_entire_html = web_page_6.asEntireHTML()
    self.assertTrue('<script' not in web_page_6_entire_html)
    self.assertTrue('<javascript' not in web_page_6_entire_html)

1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
  def test_getTargetFormatItemList(self):
    """
     Test getting target conversion format item list.
     Note: this tests assumes the default formats do exists for some content types.
     as this is a matter of respective oinfiguration of mimetypes_registry & portal_transforms
     only the basic minium of transorm to formats is tested.
    """
    portal_type = 'PDF'
    module = self.portal.getDefaultModule(portal_type)

    upload_file = makeFileUpload('TEST.Large.Document.pdf')
    pdf = module.newContent(portal_type=portal_type, file=upload_file)
1926
    
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
    self.assertTrue('html' in pdf.getTargetFormatList())
    self.assertTrue('png' in pdf.getTargetFormatList())
    self.assertTrue('txt' in pdf.getTargetFormatList())

    web_page=self.portal.web_page_module.newContent(portal_type='Web Page',
                                                    content_type='text/html')
    self.assertTrue('odt' in web_page.getTargetFormatList())
    self.assertTrue('txt' in web_page.getTargetFormatList())

    image=self.portal.image_module.newContent(portal_type='Image',
                                                    content_type='image/png')
    self.assertTrue('txt' in image.getTargetFormatList())
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
    
    # test Not converted (i.e. empty) OOoDocument instances
    presentation=self.portal.document_module.newContent(portal_type='Presentation')
    self.assertSameSet([], presentation.getTargetFormatList())
    
    # test uploading some data
    upload_file = makeFileUpload('Foo_001.odg')
    presentation.edit(file=upload_file)
    self.stepTic()
    self.assertTrue('odg' in presentation.getTargetFormatList())
    self.assertTrue('jpg' in presentation.getTargetFormatList())
    self.assertTrue('png' in presentation.getTargetFormatList())

1952 1953 1954 1955 1956
  def test_convertToImageOnTraversal(self):
    """
    Test converting to image all Document portal types on traversal i.e.:
     - image_module/1?quality=100&display=xlarge&format=jpeg
     - document_module/1?quality=100&display=large&format=jpeg
1957 1958
     - document_module/1?quality=10&display=large&format=jpeg
     - document_module/1?display=large&format=jpeg
1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
     - etc ...
    """
    # Create OOo document
    ooo_document = self.portal.document_module.newContent(portal_type='Presentation')
    upload_file = makeFileUpload('TEST-en-003.odp')
    ooo_document.edit(file=upload_file)

    pdf_document = self.portal.document_module.newContent(portal_type='PDF')
    upload_file = makeFileUpload('TEST-en-002.pdf')
    pdf_document.edit(file=upload_file)

    image_document = self.portal.image_module.newContent(portal_type='Image')
    upload_file = makeFileUpload('TEST-en-002.png')
    image_document.edit(file=upload_file)
    self.stepTic()

    def getPreferences(image_display):
      preference_tool = self.portal.getPortalObject().portal_preferences
      height_preference = 'preferred_%s_image_height' % (image_display,)
      width_preference = 'preferred_%s_image_width' % (image_display,)
      height = int(preference_tool.getPreference(height_preference))
      width = int(preference_tool.getPreference(width_preference))
      return (width, height)

1983
    def getURLSizeList(uri, **kw):
1984 1985 1986 1987 1988 1989 1990
      # __ac=RVJQNVR5cGVUZXN0Q2FzZTo%3D is encoded ERP5TypeTestCase with empty password
      url = '%s?%s&__ac=%s' %(uri, urllib.urlencode(kw), 'RVJQNVR5cGVUZXN0Q2FzZTo%3D')
      format=kw.get('format', 'jpeg')
      infile = urllib.urlopen(url)
      # save as file with proper incl. format filename (for some reasons PIL uses this info)
      filename = "%s%stest-image-format-resize.%s" %(os.getcwd(), os.sep, format)
      f = open(filename, "w")
1991 1992
      image_data = infile.read()
      f.write(image_data)
1993 1994
      f.close()
      infile.close()
1995
      file_size = len(image_data)
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
      try:
        from PIL import Image
        image = Image.open(filename)
        image_size = image.size
      except ImportError:
        from subprocess import Popen, PIPE
        identify_output = Popen(['identify', filename],
                                stdout=PIPE).communicate()[0]
        image_size = tuple(map(lambda x:int(x),
                               identify_output.split()[2].split('x')))
2006
      os.remove(filename)
2007
      return image_size, file_size
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022

    ooo_document_url = '%s/%s' %(self.portal.absolute_url(), ooo_document.getRelativeUrl())
    pdf_document_url = '%s/%s' %(self.portal.absolute_url(), pdf_document.getRelativeUrl())
    image_document_url = '%s/%s' %(self.portal.absolute_url(), image_document.getRelativeUrl())
    for display in ('nano', 'micro', 'thumbnail', 'xsmall', 'small', 'medium', 'large', 'xlarge',):
      max_tollerance_px = 1
      preffered_size_for_display = getPreferences(display)
      for format in ('png', 'jpeg', 'gif',):
        convert_kw = {'display':display, \
                      'format':format, \
                      'quality':100}
        # Note: due to some image interpolations it's possssible that we have a difference of max_tollerance_px 
        # so allow some tollerance which is produced by respective portal_transform command

        # any OOo based portal type
2023
        ooo_document_image_size, ooo_document_file_size = getURLSizeList(ooo_document_url, **convert_kw)
2024 2025 2026
        self.assertTrue(max(preffered_size_for_display) - max(ooo_document_image_size) <= max_tollerance_px)

        # PDF
2027
        pdf_document_image_size, pdf_document_file_size = getURLSizeList(pdf_document_url, **convert_kw)
2028 2029 2030
        self.assertTrue(max(preffered_size_for_display) - max(pdf_document_image_size) <= max_tollerance_px)

        # Image
2031
        image_document_image_size, image_document_file_size = getURLSizeList(image_document_url, **convert_kw)
2032
        self.assertTrue(max(preffered_size_for_display) - max(image_document_image_size) <= max_tollerance_px)
2033

2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
    # test changing image quality will decrease its file size
    for url in (image_document_url, pdf_document_url, ooo_document_url):
      convert_kw = {'display':'xlarge', \
                    'format':'jpeg', \
                    'quality':100}
      image_document_image_size_100p,image_document_file_size_100p = getURLSizeList(url, **convert_kw)
      # decrease in quality should decrease its file size
      convert_kw['quality'] = 5.0
      image_document_image_size_5p,image_document_file_size_5p = getURLSizeList(url, **convert_kw)
      # removing quality should enable defaults settings which should be reasonable between 5% and 100%
      del convert_kw['quality']
      image_document_image_size_no_quality,image_document_file_size_no_quality = getURLSizeList(url, **convert_kw)
      # check file sizes
      self.assertTrue(image_document_file_size_100p > image_document_file_size_no_quality and \
                      image_document_file_size_no_quality > image_document_file_size_5p)
      # no matter of quality image sizes whould be the same
      self.assertTrue(image_document_image_size_100p==image_document_image_size_5p and \
                        image_document_image_size_5p==image_document_image_size_no_quality)

2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
  def test_checkConversionFormatPermission(self):
    """
     Test various use cases when conversion can be not allowed
    """
    portal_type = 'PDF'
    module = self.portal.getDefaultModule(portal_type)
    upload_file = makeFileUpload('TEST.Large.Document.pdf')
    pdf = module.newContent(portal_type=portal_type, file=upload_file)

    # if PDF size is larger than A4 format system should deny conversion
    self.assertRaises(Unauthorized, pdf.convert, format='jpeg')

2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
  def test_getSearchText(self):
    """
     Test extracting search text script.
    """
    request = get_request()
    portal = self.portal

    # test direct passing argument_name_list
    request.set('MySearchableText', 'MySearchableText_value')
    self.assertEqual(request.get('MySearchableText'),
                     portal.Base_getSearchText(argument_name_list=['MySearchableText']))

    # simulate script being called in a listbox
    # to simulate this we set 'global_search_column' a listbox
    form = portal.DocumentModule_viewDocumentList
    listbox = form.listbox
    listbox.manage_edit_surcharged_xmlrpc(dict(
            global_search_column='advanced_search_text'))
    # render listbox
    listbox.render()
    request.set('advanced_search_text', 'advanced_search_text_value')
    self.assertEqual(request.get('advanced_search_text'),
                     portal.Base_getSearchText())

2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
  def test_Document_getOtherVersionDocumentList(self):
    """
      Test getting list of other documents which have the same reference.
    """
    request = get_request()
    portal = self.portal

    kw={'reference': 'one_that_will_never_change',
        'language': 'en',
         'version': '001'}
    document1 = portal.document_module.newContent(portal_type="Presentation", **kw)
    self.stepTic()
    self.assertEquals(0, len(document1.Document_getOtherVersionDocumentList()))

    kw['version'] == '002'
    document2 = portal.document_module.newContent(portal_type="Spreadsheet", **kw)
    self.stepTic()

    web_page1 = portal.web_page_module.newContent(portal_type="Web Page", \
                                                  **{'reference': 'embedded',
                                                     'version': '001'})
    web_page2 = portal.web_page_module.newContent(portal_type="Web Page", \
                                                 **{'reference': 'embedded',
                                                    'version': '002'})
    self.stepTic()

    # both documents should be in other's document version list
    self.assertSameSet([x.getObject() for x in document1.Document_getOtherVersionDocumentList()], \
                        [document2])
    self.assertSameSet([x.getObject() for x in document2.Document_getOtherVersionDocumentList()], \
                        [document1])
    
    # limit by portal type works
    self.assertSameSet([x.getObject() for x in document1.Document_getOtherVersionDocumentList(**{'portal_type':'Presentation'})], \
                        [])

    # current_web_document mode (i.e. embedded Web Page in Web Section) can override current context
    request.set('current_web_document', web_page1)
    self.assertSameSet([x.getObject() for x in document1.Document_getOtherVersionDocumentList()], \
                        [web_page2])
    request.set('current_web_document', web_page2)
    self.assertSameSet([x.getObject() for x in document1.Document_getOtherVersionDocumentList()], \
                        [web_page1])
2132

2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152
  def test_Base_getWorkflowEventInfoList(self):
    """
      Test getting history of an object.
    """
    portal = self.portal
    document = portal.document_module.newContent(portal_type="Presentation")
    document.edit(title='New')
    document.publish()
    document.reject()
    document.share()
    logged_in_user = str(self.portal.portal_membership.getAuthenticatedMember())
    event_list = document.Base_getWorkflowEventInfoList()
    event_list.reverse()
    # all actions by logged in user
    for event in event_list:
      self.assertEquals(event.actor, logged_in_user)
    self.assertEquals(event_list[0].action, 'Edit')
    self.assertEquals(event_list[-1].action, 'Share Document')
    self.assertEquals(event_list[-2].action, 'Reject Document')
    self.assertEquals(event_list[-3].action, 'Publish Document')
2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
    
  def test_ContributeToExistingDocument(self):
    """
      Test various cases of contributing to an existing document
    """
    request = get_request()
    portal = self.portal
    # contribute a document, then make it not editable and check we can not contribute to it
    upload_file = makeFileUpload('TEST-en-002.doc')
    kw = dict(file=upload_file, \
               synchronous_metadata_discovery=True)
    document = self.portal.Base_contribute(**kw)
    self.stepTic()    
    # passing another portal type should raise an exception
    kw['portal_type'] = "Spreadsheet"
    self.assertRaises(ValueError, self.portal.Base_contribute, **kw)
                                           
    # make it read only
    document.manage_permission(Permissions.ModifyPortalContent, [])
    self.stepTic()
    kw.pop('portal_type')
    self.assertRaises(Unauthorized, self.portal.Base_contribute, **kw)
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
    
  def test_ContributeWithMergingToExistingDocument(self):
    """
      Test various cases of merging to an existing document
    """
    request = get_request()
    portal = self.portal
    # contribute a document, then make it not editable and check we can not contribute to it
    kw=dict(synchronous_metadata_discovery=True)
    upload_file = makeFileUpload('TEST-en-002.doc')
    kw = dict(file=upload_file, synchronous_metadata_discovery=True)
    document = self.portal.Base_contribute(**kw)
    self.stepTic()    
   
    upload_file = makeFileUpload('TEST-en-003.odp', 'TEST-en-002.doc')
    kw = dict(file=upload_file, synchronous_metadata_discovery=True)
    document = self.portal.Base_contribute(**kw)
    self.stepTic()
    self.assertEquals('test-en-003-description', document.getDescription())
    self.assertEquals('test-en-003-title', document.getTitle())
    self.assertEquals('test-en-003-keywords', document.getSubject())
2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213

  def test_DocumentIndexation(self):
    """
      Test how a document is being indexed in MySQL.
    """
    portal = self.portal
    document = portal.document_module.newContent(
                                        portal_type='Presentation', \
                                        reference='XXX-YYY-ZZZZ',
                                        subject_list = ['subject1', 'subject2'])
    self.stepTic()
    # full text indexation
    full_text_result = portal.erp5_sql_connection.manage_test('select * from full_text where uid="%s"' %document.getUid())
    self.assertTrue('subject2' in full_text_result[0]['searchabletext'])
    self.assertTrue('subject1' in full_text_result[0]['searchabletext'])
    self.assertTrue(document.getReference() in full_text_result[0]['searchabletext'])
    
    # subject indexation
2214 2215 2216 2217 2218
    for subject_list in (['subject1',], ['subject2',],
                         ['subject1', 'subject2',],):
      subject_result = portal.portal_catalog(subject=subject_list)
      self.assertEquals(len(subject_result), 1)
      self.assertEquals(subject_result[0].getPath(), document.getPath())
2219

2220 2221 2222 2223 2224 2225
  def _test_document_publication_workflow(self, portal_type, transition):
    document = self.getDocumentModule().newContent(portal_type=portal_type)
    self.portal.portal_workflow.doActionFor(document, transition)

  def test_document_publication_workflow_Drawing_publish(self):
    self._test_document_publication_workflow('Drawing', 'publish_action')
2226 2227

  def test_document_publication_workflow_Drawing_publish_alive(self):
2228 2229 2230 2231 2232
    self._test_document_publication_workflow('Drawing',
        'publish_alive_action')

  def test_document_publication_workflow_Drawing_release(self):
    self._test_document_publication_workflow('Drawing', 'release_action')
2233 2234

  def test_document_publication_workflow_Drawing_release_alive(self):
2235 2236 2237 2238 2239
    self._test_document_publication_workflow('Drawing',
        'release_alive_action')

  def test_document_publication_workflow_Drawing_share(self):
    self._test_document_publication_workflow('Drawing', 'share_action')
2240 2241

  def test_document_publication_workflow_Drawing_share_alive(self):
2242 2243 2244 2245 2246
    self._test_document_publication_workflow('Drawing',
        'share_alive_action')

  def test_document_publication_workflow_File_publish(self):
    self._test_document_publication_workflow('File', 'publish_action')
2247 2248

  def test_document_publication_workflow_File_publish_alive(self):
2249 2250 2251 2252 2253
    self._test_document_publication_workflow('File',
        'publish_alive_action')

  def test_document_publication_workflow_File_release(self):
    self._test_document_publication_workflow('File', 'release_action')
2254 2255

  def test_document_publication_workflow_File_release_alive(self):
2256 2257 2258 2259 2260
    self._test_document_publication_workflow('File',
        'release_alive_action')

  def test_document_publication_workflow_File_share(self):
    self._test_document_publication_workflow('File', 'share_action')
2261 2262

  def test_document_publication_workflow_File_share_alive(self):
2263 2264 2265 2266 2267
    self._test_document_publication_workflow('File',
        'share_alive_action')

  def test_document_publication_workflow_PDF_publish(self):
    self._test_document_publication_workflow('PDF', 'publish_action')
2268 2269

  def test_document_publication_workflow_PDF_publish_alive(self):
2270 2271 2272 2273 2274
    self._test_document_publication_workflow('PDF',
        'publish_alive_action')

  def test_document_publication_workflow_PDF_release(self):
    self._test_document_publication_workflow('PDF', 'release_action')
2275 2276

  def test_document_publication_workflow_PDF_release_alive(self):
2277 2278 2279 2280 2281
    self._test_document_publication_workflow('PDF',
        'release_alive_action')

  def test_document_publication_workflow_PDF_share(self):
    self._test_document_publication_workflow('PDF', 'share_action')
2282 2283

  def test_document_publication_workflow_PDF_share_alive(self):
2284 2285 2286 2287 2288
    self._test_document_publication_workflow('PDF',
        'share_alive_action')

  def test_document_publication_workflow_Presentation_publish(self):
    self._test_document_publication_workflow('Presentation', 'publish_action')
2289 2290

  def test_document_publication_workflow_Presentation_publish_alive(self):
2291 2292 2293 2294 2295
    self._test_document_publication_workflow('Presentation',
        'publish_alive_action')

  def test_document_publication_workflow_Presentation_release(self):
    self._test_document_publication_workflow('Presentation', 'release_action')
2296 2297

  def test_document_publication_workflow_Presentation_release_alive(self):
2298 2299 2300 2301 2302
    self._test_document_publication_workflow('Presentation',
        'release_alive_action')

  def test_document_publication_workflow_Presentation_share(self):
    self._test_document_publication_workflow('Presentation', 'share_action')
2303 2304

  def test_document_publication_workflow_Presentation_share_alive(self):
2305 2306 2307 2308 2309
    self._test_document_publication_workflow('Presentation',
        'share_alive_action')

  def test_document_publication_workflow_Spreadsheet_publish(self):
    self._test_document_publication_workflow('Spreadsheet', 'publish_action')
2310 2311

  def test_document_publication_workflow_Spreadsheet_publish_alive(self):
2312 2313 2314 2315 2316
    self._test_document_publication_workflow('Spreadsheet',
        'publish_alive_action')

  def test_document_publication_workflow_Spreadsheet_release(self):
    self._test_document_publication_workflow('Spreadsheet', 'release_action')
2317 2318

  def test_document_publication_workflow_Spreadsheet_release_alive(self):
2319 2320 2321 2322 2323
    self._test_document_publication_workflow('Spreadsheet',
        'release_alive_action')

  def test_document_publication_workflow_Spreadsheet_share(self):
    self._test_document_publication_workflow('Spreadsheet', 'share_action')
2324 2325

  def test_document_publication_workflow_Spreadsheet_share_alive(self):
2326 2327 2328 2329 2330
    self._test_document_publication_workflow('Spreadsheet',
        'share_alive_action')

  def test_document_publication_workflow_Text_publish(self):
    self._test_document_publication_workflow('Text', 'publish_action')
2331 2332

  def test_document_publication_workflow_Text_publish_alive(self):
2333 2334 2335 2336 2337
    self._test_document_publication_workflow('Text',
        'publish_alive_action')

  def test_document_publication_workflow_Text_release(self):
    self._test_document_publication_workflow('Text', 'release_action')
2338 2339

  def test_document_publication_workflow_Text_release_alive(self):
2340 2341 2342 2343 2344
    self._test_document_publication_workflow('Text',
        'release_alive_action')

  def test_document_publication_workflow_Text_share(self):
    self._test_document_publication_workflow('Text', 'share_action')
2345 2346

  def test_document_publication_workflow_Text_share_alive(self):
2347 2348 2349
    self._test_document_publication_workflow('Text',
        'share_alive_action')

2350
class TestDocumentWithSecurity(TestDocumentMixin):
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362

  username = 'yusei'

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

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

2363
  def test_ShowPreviewAfterSubmitted(self):
2364 2365 2366 2367 2368 2369
    """
    Make sure that uploader can preview document after submitted.
    """
    filename = 'REF-en-001.odt'
    upload_file = makeFileUpload(filename)
    document = self.portal.portal_contributions.newContent(file=upload_file)
Ivan Tyagov's avatar
Ivan Tyagov committed
2370
    self.stepTic()
2371 2372 2373 2374 2375

    document.submit()

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

Ivan Tyagov's avatar
Ivan Tyagov committed
2376
    self.stepTic()
2377 2378 2379

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

2380 2381 2382 2383
  def test_DownloadableDocumentSize(self):
    '''Check that once the document is converted and cached, its size is
    correctly set'''
    portal = self.getPortalObject()
2384 2385
    portal_type = 'Text'
    document_module = portal.getDefaultModule(portal_type)
2386 2387

    # create a text document in document module
2388
    text_document = document_module.newContent(portal_type=portal_type,
2389 2390 2391 2392 2393
                                               reference='Foo_001',
                                               title='Foo_OO1')
    f = makeFileUpload('Foo_001.odt')
    text_document.edit(file=f.read())
    f.close()
Ivan Tyagov's avatar
Ivan Tyagov committed
2394
    self.stepTic()
2395 2396 2397 2398 2399 2400 2401 2402

    # 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
2403 2404
    mime_type, pdf_data = text_document.convert(format='pdf')
    pdf_size = len(pdf_data)
2405 2406 2407 2408 2409 2410 2411


    # 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)
2412

2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437
  def test_ImageSizePreference(self):
    """
    Tests that when user defines image sizes are already defined in preferences
    those properties are taken into account when the user
    views an image
    """
    ERP5TypeTestCase.login(self, 'yusei')
    preference_tool = self.portal.portal_preferences
    #get the thumbnail sizes defined by default on default site preference
    default_thumbnail_image_height = \
       preference_tool.default_site_preference.getPreferredThumbnailImageHeight()
    default_thumbnail_image_width = \
       preference_tool.default_site_preference.getPreferredThumbnailImageWidth()
    self.assertTrue(default_thumbnail_image_height > 0)
    self.assertTrue(default_thumbnail_image_width > 0)    
    self.assertEqual(default_thumbnail_image_height,
                     preference_tool.getPreferredThumbnailImageHeight())
    self.assertEqual(default_thumbnail_image_width,
                     preference_tool.getPreferredThumbnailImageWidth())
    #create new user preference and set new sizes for image thumbnail display 
    user_pref = preference_tool.newContent(
                          portal_type='Preference',
                          priority=Priority.USER)
    self.portal.portal_workflow.doActionFor(user_pref, 'enable_action')
    self.assertEqual(user_pref.getPreferenceState(), 'enabled')
Ivan Tyagov's avatar
Ivan Tyagov committed
2438
    self.stepTic()
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452
    user_pref.setPreferredThumbnailImageHeight(default_thumbnail_image_height + 10)
    user_pref.setPreferredThumbnailImageWidth(default_thumbnail_image_width + 10)
    #Verify that the new values defined are the ones used by default
    self.assertEqual(default_thumbnail_image_height + 10,
                     preference_tool.getPreferredThumbnailImageHeight())
    self.assertEqual(default_thumbnail_image_height + 10,
                     preference_tool.getPreferredThumbnailImageHeight(0))
    self.assertEqual(default_thumbnail_image_width + 10,
                     preference_tool.getPreferredThumbnailImageWidth())
    self.assertEqual(default_thumbnail_image_width + 10,
                     preference_tool.getPreferredThumbnailImageWidth(0))
    #Now lets check that when we try to view an image as thumbnail, 
    #the sizes of that image are the ones defined in user preference
    image_portal_type = 'Image'
2453 2454
    image_module = self.portal.getDefaultModule(image_portal_type)
    image = image_module.newContent(portal_type=image_portal_type)
2455 2456 2457 2458 2459
    self.assertEqual('thumbnail',
       image.Image_view._getOb("image_view", None).get_value('image_display'))
    self.assertEqual((user_pref.getPreferredThumbnailImageWidth(),
                    user_pref.getPreferredThumbnailImageHeight()),
                     image.getSizeFromImageDisplay('thumbnail'))
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479

class TestDocumentPerformance(TestDocumentMixin):

  def test_01_LargeOOoDocumentToImageConversion(self):
    """
      Test large OOoDocument to image conversion
    """
    ooo_document = self.portal.document_module.newContent(portal_type='Spreadsheet')
    upload_file = makeFileUpload('import_big_spreadsheet.ods')
    ooo_document.edit(file=upload_file)
    self.stepTic()
    before = time.time()
    # converting any OOoDocument -> PDF -> Image
    # make sure that this can happen in less tan XXX seconds i.e. code doing convert
    # uses only first PDF frame (not entire PDF) to make an image - i.e.optimized enough to not kill 
    # entire system performance by doing extensive calculations over entire PDF (see r37102-37103)
    ooo_document.convert(format='png')
    after = time.time()
    req_time = (after - before)
    # we should have image converted in less than 20s
2480
    self.assertTrue(req_time < 30.0)
2481
    
2482 2483 2484
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestDocument))
2485
  suite.addTest(unittest.makeSuite(TestDocumentWithSecurity))
2486
  suite.addTest(unittest.makeSuite(TestDocumentPerformance))
2487
  return suite
Bartek Górny's avatar
Bartek Górny committed
2488 2489


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