testERP5Catalog.py 170 KB
Newer Older
Sebastien Robin's avatar
Sebastien Robin committed
1 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
##############################################################################
#
# 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.
#
##############################################################################

Jérome Perrin's avatar
Jérome Perrin committed
29 30
import unittest
import sys
31
from _mysql_exceptions import ProgrammingError
Sebastien Robin's avatar
Sebastien Robin committed
32 33 34

from Testing import ZopeTestCase
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
35
from AccessControl import getSecurityManager
36
from AccessControl.SecurityManagement import newSecurityManager
Sebastien Robin's avatar
Sebastien Robin committed
37 38
from zLOG import LOG
from DateTime import DateTime
39
from Products.ERP5Type.tests.utils import LogInterceptor
40 41
from Products.ERP5Type.tests.utils import createZODBPythonScript, todo_erp5, \
                                          getExtraSqlConnectionStringList
42
from Products.ERP5Type.tests.backportUnittest import skip
43 44 45
from Products.ZSQLCatalog.ZSQLCatalog import HOT_REINDEXING_FINISHED_STATE,\
      HOT_REINDEXING_RECORDING_STATE, HOT_REINDEXING_DOUBLE_INDEXING_STATE
from Products.CMFActivity.Errors import ActivityFlushError
46
from Products.ZSQLCatalog.SQLCatalog import Query, ComplexQuery
47

Sebastien Robin's avatar
Sebastien Robin committed
48

49 50 51 52 53
try:
  from transaction import get as get_transaction
except ImportError:
  pass

54 55 56 57
from OFS.ObjectManager import ObjectManager
from random import randint

class IndexableDocument(ObjectManager):
58 59 60

  # this property is required for dummy providesIMovement
  __allow_access_to_unprotected_subobjects__ = 1
61
  isRADContent = 0
62

63 64 65 66 67 68 69 70
  def getUid(self):
    uid = getattr(self, 'uid', None)
    if uid is None:
      self.uid = uid = randint(1, 100) + 100000
    return uid

  def __getattr__(self, name):
    # Case for all "is..." magic properties (isMovement, ...)
71 72 73
    if name.startswith('is') or \
       name.startswith('provides'):
      return lambda: 0
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    raise AttributeError, name

  def getPath(self):
    return '' # Whatever

  def getRelativeUrl(self):
    return '' # Whatever

class FooDocument(IndexableDocument):
  def getReference(self):
    return 'foo'

class BarDocument(IndexableDocument):
  # Does not define any getReference method.
  pass

90
class TestERP5Catalog(ERP5TypeTestCase, LogInterceptor):
Sebastien Robin's avatar
Sebastien Robin committed
91
  """
92
    Tests for ERP5 Catalog.
Sebastien Robin's avatar
Sebastien Robin committed
93 94 95 96 97
  """

  def getTitle(self):
    return "ERP5Catalog"

Sebastien Robin's avatar
Sebastien Robin committed
98 99 100
  def getBusinessTemplateList(self):
    return ('erp5_base',)

Sebastien Robin's avatar
Sebastien Robin committed
101
  # Different variables used for this test
102
  run_all_test = 1
103
  quiet = 0
104
  username = 'seb'
105

106
  def afterSetUp(self):
107 108 109 110
    uf = self.getPortal().acl_users
    uf._doAddUser(self.username, '', ['Manager'], [])

    self.login(self.username)
111 112
    # make sure there is no message any more
    self.tic()
113 114 115 116 117 118 119 120

  def beforeTearDown(self):
    for module in [ self.getPersonModule(),
                    self.getOrganisationModule(),
                    self.getCategoryTool().region,
                    self.getCategoryTool().group ]:
      module.manage_delObjects(list(module.objectIds()))
    get_transaction().commit()
121
    self.tic()
Sebastien Robin's avatar
Sebastien Robin committed
122

123
  def getSQLPathList(self,connection_id=None, sql=None):
Sebastien Robin's avatar
Sebastien Robin committed
124 125 126
    """
    Give the full list of path in the catalog
    """
127 128 129
    if connection_id is None:
      sql_connection = self.getSQLConnection()
    else:
130 131 132
      sql_connection = getattr(self.getPortal(), connection_id)
    if sql is None:
      sql = 'select distinct(path) from catalog'
Sebastien Robin's avatar
Sebastien Robin committed
133
    result = sql_connection.manage_test(sql)
134
    path_list = map(lambda x: x['path'], result)
Sebastien Robin's avatar
Sebastien Robin committed
135
    return path_list
136 137 138 139 140
  
  def getSQLPathListWithRolesAndUsers(self, connection_id):
    sql = 'select distinct(path) from catalog, roles_and_users\
           where catalog.security_uid=roles_and_users.uid'
    return self.getSQLPathList(connection_id, sql)
Sebastien Robin's avatar
Sebastien Robin committed
141

142 143
  def checkRelativeUrlInSQLPathList(self,url_list,connection_id=None):
    path_list = self.getSQLPathList(connection_id=connection_id)
Sebastien Robin's avatar
Sebastien Robin committed
144 145 146 147
    portal_id = self.getPortalId()
    for url in url_list:
      path = '/' + portal_id + '/' + url
      self.failUnless(path in path_list)
148
      LOG('checkRelativeUrlInSQLPathList found path:',0,path)
Sebastien Robin's avatar
Sebastien Robin committed
149

150 151
  def checkRelativeUrlNotInSQLPathList(self,url_list,connection_id=None):
    path_list = self.getSQLPathList(connection_id=connection_id)
Sebastien Robin's avatar
Sebastien Robin committed
152 153 154 155
    portal_id = self.getPortalId()
    for url in url_list:
      path = '/' + portal_id + '/' + url
      self.failUnless(path not in  path_list)
156
      LOG('checkRelativeUrlInSQLPathList not found path:',0,path)
Sebastien Robin's avatar
Sebastien Robin committed
157

158
  def test_01_HasEverything(self, quiet=quiet, run=run_all_test):
Sebastien Robin's avatar
Sebastien Robin committed
159 160 161 162 163 164 165
    if not run: return
    if not quiet:
      ZopeTestCase._print('\nTest Has Everything ')
      LOG('Testing... ',0,'testHasEverything')
    self.failUnless(self.getCategoryTool()!=None)
    self.failUnless(self.getSimulationTool()!=None)
    self.failUnless(self.getTypeTool()!=None)
166
    self.failUnless(self.getSQLConnection()!=None)
Sebastien Robin's avatar
Sebastien Robin committed
167 168
    self.failUnless(self.getCatalogTool()!=None)

169
  def test_02_EverythingCatalogued(self, quiet=quiet, run=run_all_test):
Sebastien Robin's avatar
Sebastien Robin committed
170 171 172 173 174
    if not run: return
    if not quiet:
      ZopeTestCase._print('\nTest Everything Catalogued')
      LOG('Testing... ',0,'testEverythingCatalogued')
    portal_catalog = self.getCatalogTool()
175
    self.tic()
Sebastien Robin's avatar
Sebastien Robin committed
176 177 178
    organisation_module_list = portal_catalog(portal_type='Organisation Module')
    self.assertEquals(len(organisation_module_list),1)

179
  def test_03_CreateAndDeleteObject(self, quiet=quiet, run=run_all_test):
Sebastien Robin's avatar
Sebastien Robin committed
180 181 182 183 184 185 186 187
    if not run: return
    if not quiet:
      message = 'Test Create And Delete Objects'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
    portal_catalog = self.getCatalogTool()
    person_module = self.getPersonModule()
    person = person_module.newContent(id='1',portal_type='Person')
188
    path_list = [person.getRelativeUrl()]
189
    self.checkRelativeUrlNotInSQLPathList(path_list)
Sebastien Robin's avatar
Sebastien Robin committed
190
    person.immediateReindexObject()
191
    self.checkRelativeUrlInSQLPathList(path_list)
Sebastien Robin's avatar
Sebastien Robin committed
192
    person_module.manage_delObjects('1')
193 194
    get_transaction().commit()
    self.tic()
195
    self.checkRelativeUrlNotInSQLPathList(path_list)
Sebastien Robin's avatar
Sebastien Robin committed
196
    # Now we will ask to immediatly reindex
197
    person = person_module.newContent(id='2',
198 199
                                      portal_type='Person',)
    person.immediateReindexObject()
200
    path_list = [person.getRelativeUrl()]
201
    self.checkRelativeUrlInSQLPathList(path_list)
Sebastien Robin's avatar
Sebastien Robin committed
202
    person.immediateReindexObject()
203
    self.checkRelativeUrlInSQLPathList(path_list)
Sebastien Robin's avatar
Sebastien Robin committed
204
    person_module.manage_delObjects('2')
205 206
    get_transaction().commit()
    self.tic()
207
    self.checkRelativeUrlNotInSQLPathList(path_list)
Sebastien Robin's avatar
Sebastien Robin committed
208 209
    # Now we will try with the method deleteContent
    person = person_module.newContent(id='3',portal_type='Person')
210
    path_list = [person.getRelativeUrl()]
211
    self.checkRelativeUrlNotInSQLPathList(path_list)
Sebastien Robin's avatar
Sebastien Robin committed
212
    person.immediateReindexObject()
213
    self.checkRelativeUrlInSQLPathList(path_list)
Sebastien Robin's avatar
Sebastien Robin committed
214
    person_module.deleteContent('3')
215
    # Now delete things is made with activities
216
    self.checkRelativeUrlNotInSQLPathList(path_list)
217 218
    get_transaction().commit()
    self.tic()
219
    self.checkRelativeUrlNotInSQLPathList(path_list)
Sebastien Robin's avatar
Sebastien Robin committed
220

221
  def test_04_SearchFolderWithDeletedObjects(self, quiet=quiet, run=run_all_test):
Sebastien Robin's avatar
Sebastien Robin committed
222 223 224 225 226 227 228 229 230
    if not run: return
    if not quiet:
      message = 'Search Folder With Deleted Objects'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
    person_module = self.getPersonModule()
    # Now we will try the same thing as previous test and look at searchFolder
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertEquals([],folder_object_list)
231 232
    person = person_module.newContent(id='4',portal_type='Person',)
    person.immediateReindexObject()
Sebastien Robin's avatar
Sebastien Robin committed
233 234 235 236
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertEquals(['4'],folder_object_list)
    person.immediateReindexObject()
    person_module.manage_delObjects('4')
237 238
    get_transaction().commit()
    self.tic()
Sebastien Robin's avatar
Sebastien Robin committed
239 240 241
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertEquals([],folder_object_list)

242
  def test_05_SearchFolderWithImmediateReindexObject(self, quiet=quiet, run=run_all_test):
Sebastien Robin's avatar
Sebastien Robin committed
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    if not run: return
    if not quiet:
      message = 'Search Folder With Immediate Reindex Object'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()

    # Now we will try the same thing as previous test and look at searchFolder
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertEquals([],folder_object_list)

    person = person_module.newContent(id='4',portal_type='Person')
    person.immediateReindexObject()
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertEquals(['4'],folder_object_list)
    
    person_module.manage_delObjects('4')
261 262
    get_transaction().commit()
    self.tic()
Sebastien Robin's avatar
Sebastien Robin committed
263 264 265
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertEquals([],folder_object_list)

266 267
  def test_06_SearchFolderWithRecursiveImmediateReindexObject(self,
                                              quiet=quiet, run=run_all_test):
Sebastien Robin's avatar
Sebastien Robin committed
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    if not run: return
    if not quiet:
      message = 'Search Folder With Recursive Immediate Reindex Object'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()

    # Now we will try the same thing as previous test and look at searchFolder
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertEquals([],folder_object_list)

    person = person_module.newContent(id='4',portal_type='Person')
    person_module.recursiveImmediateReindexObject()
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertEquals(['4'],folder_object_list)
    
    person_module.manage_delObjects('4')
286 287
    get_transaction().commit()
    self.tic()
Sebastien Robin's avatar
Sebastien Robin committed
288 289 290
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertEquals([],folder_object_list)

291
  def test_07_ClearCatalogAndTestNewContent(self, quiet=quiet, run=run_all_test):
Sebastien Robin's avatar
Sebastien Robin committed
292 293 294 295 296 297 298 299 300 301 302 303
    if not run: return
    if not quiet:
      message = 'Clear Catalog And Test New Content'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()

    # Clear catalog
    portal_catalog = self.getCatalogTool()
    portal_catalog.manage_catalogClear()

304 305
    person = person_module.newContent(id='4',portal_type='Person')
    person.immediateReindexObject()
Sebastien Robin's avatar
Sebastien Robin committed
306 307 308
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertEquals(['4'],folder_object_list)

309 310
  def test_08_ClearCatalogAndTestRecursiveImmediateReindexObject(self,
                                               quiet=quiet, run=run_all_test):
Sebastien Robin's avatar
Sebastien Robin committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    if not run: return
    if not quiet:
      message = 'Clear Catalog And Test Recursive Immediate Reindex Object'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()

    # Clear catalog
    portal_catalog = self.getCatalogTool()
    portal_catalog.manage_catalogClear()

    person = person_module.newContent(id='4',portal_type='Person')
    person_module.recursiveImmediateReindexObject()
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertEquals(['4'],folder_object_list)

328 329
  def test_09_ClearCatalogAndTestImmediateReindexObject(self, quiet=quiet,
                                                        run=run_all_test):
Sebastien Robin's avatar
Sebastien Robin committed
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    if not run: return
    if not quiet:
      message = 'Clear Catalog And Test Immediate Reindex Object'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()

    # Clear catalog
    portal_catalog = self.getCatalogTool()
    portal_catalog.manage_catalogClear()

    person = person_module.newContent(id='4',portal_type='Person')
    person.immediateReindexObject()
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertEquals(['4'],folder_object_list)

347
  def test_10_OrderedSearchFolder(self, quiet=quiet, run=run_all_test):
Sebastien Robin's avatar
Sebastien Robin committed
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
    if not run: return
    if not quiet:
      message = 'Ordered Search Folder'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()

    # Clear catalog
    portal_catalog = self.getCatalogTool()
    portal_catalog.manage_catalogClear()

    person = person_module.newContent(id='a',portal_type='Person',title='a',description='z')
    person.immediateReindexObject()
    person = person_module.newContent(id='b',portal_type='Person',title='a',description='y')
    person.immediateReindexObject()
    person = person_module.newContent(id='c',portal_type='Person',title='a',description='x')
    person.immediateReindexObject()
366 367
    folder_object_list = [x.getObject().getId()
              for x in person_module.searchFolder(sort_on=[('id','ascending')])]
Sebastien Robin's avatar
Sebastien Robin committed
368
    self.assertEquals(['a','b','c'],folder_object_list)
369 370 371
    folder_object_list = [x.getObject().getId()
              for x in person_module.searchFolder(
              sort_on=[('title','ascending'), ('description','ascending')])]
Sebastien Robin's avatar
Sebastien Robin committed
372
    self.assertEquals(['c','b','a'],folder_object_list)
373 374 375
    folder_object_list = [x.getObject().getId()
              for x in person_module.searchFolder(
              sort_on=[('title','ascending'),('description','descending')])]
Sebastien Robin's avatar
Sebastien Robin committed
376 377
    self.assertEquals(['a','b','c'],folder_object_list)

378
  def test_11_CastStringAsInt(self, quiet=quiet, run=run_all_test):
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    if not run: return
    if not quiet:
      message = 'Cast String As Int With Order By'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()

    # Clear catalog
    portal_catalog = self.getCatalogTool()
    portal_catalog.manage_catalogClear()

    person = person_module.newContent(id='a',portal_type='Person',title='1')
    person.immediateReindexObject()
    person = person_module.newContent(id='b',portal_type='Person',title='2')
    person.immediateReindexObject()
    person = person_module.newContent(id='c',portal_type='Person',title='12')
    person.immediateReindexObject()
    folder_object_list = [x.getObject().getTitle() for x in person_module.searchFolder(sort_on=[('title','ascending')])]
    self.assertEquals(['1','12','2'],folder_object_list)
    folder_object_list = [x.getObject().getTitle() for x in person_module.searchFolder(sort_on=[('title','ascending','int')])]
    self.assertEquals(['1','2','12'],folder_object_list)

402
  def test_12_TransactionalUidBuffer(self, quiet=quiet, run=run_all_test):
Sebastien Robin's avatar
Sebastien Robin committed
403 404
    if not run: return
    if not quiet:
405
      message = 'Transactional Uid Buffer'
Sebastien Robin's avatar
Sebastien Robin committed
406 407 408
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

409 410 411 412 413
    portal_catalog = self.getCatalogTool()
    catalog = portal_catalog.getSQLCatalog()
    self.failUnless(catalog is not None)

    # Clear out the uid buffer.
414 415 416 417 418 419 420 421 422 423 424 425 426 427
    #from Products.ZSQLCatalog.SQLCatalog import uid_buffer_dict, get_ident
    #uid_buffer_key = get_ident()
    #if uid_buffer_key in uid_buffer_dict:
    #  del uid_buffer_dict[uid_buffer_key]
    def getUIDBuffer(*args, **kw):
      uid_lock = catalog.__class__._reserved_uid_lock
      uid_lock.acquire()
      try:
        result = catalog.getUIDBuffer(*args, **kw)
      finally:
        uid_lock.release()
      return result

    getUIDBuffer(force_new_buffer=True)
428 429 430 431 432 433

    # Need to abort a transaction artificially, so commit the current
    # one, first.
    get_transaction().commit()

    catalog.newUid()
434 435
    uid_buffer = getUIDBuffer()
    self.failUnless(len(uid_buffer) > 0)
Sebastien Robin's avatar
Sebastien Robin committed
436

437
    get_transaction().abort()
438 439
    uid_buffer = getUIDBuffer()
    self.failUnless(len(uid_buffer) == 0)
Romain Courteaud's avatar
Romain Courteaud committed
440

441
  def test_13_ERP5Site_reindexAll(self, quiet=quiet, run=run_all_test):
Romain Courteaud's avatar
Romain Courteaud committed
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
    if not run: return
    if not quiet:
      message = 'ERP5Site_reindexAll'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
    # Flush message queue
    get_transaction().commit()
    self.tic()
    # Create some objects
    portal = self.getPortal()
    portal_category = self.getCategoryTool()
    base_category = portal_category.newContent(portal_type='Base Category',
                                               title="GreatTitle1")
    module = portal.getDefaultModule('Organisation')
    organisation = module.newContent(portal_type='Organisation',
                                     title="GreatTitle2")
    # Flush message queue
    get_transaction().commit()
    self.tic()
    # Clear catalog
    portal_catalog = self.getCatalogTool()
    portal_catalog.manage_catalogClear()
464
    sql_connection = self.getSQLConnection()
Romain Courteaud's avatar
Romain Courteaud committed
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
    sql = 'select count(*) from catalog where portal_type!=NULL'
    result = sql_connection.manage_test(sql)
    message_count = result[0]['COUNT(*)']
    self.assertEquals(0, message_count)
    # Commit
    get_transaction().commit()
    # Reindex all
    portal.ERP5Site_reindexAll()
    get_transaction().commit()
    self.tic()
    get_transaction().commit()
    # Check catalog
    sql = 'select count(*) from message'
    result = sql_connection.manage_test(sql)
    message_count = result[0]['COUNT(*)']
    self.assertEquals(0, message_count)
    # Check if object are catalogued
482
    self.checkRelativeUrlInSQLPathList([
Romain Courteaud's avatar
Romain Courteaud committed
483 484
                organisation.getRelativeUrl(),
                'portal_categories/%s' % base_category.getRelativeUrl()])
485

486
  def test_14_ReindexWithBrokenCategory(self, quiet=quiet, run=run_all_test):
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
    if not run: return
    if not quiet:
      message = 'Reindexing an object with 1 broken category must not'\
                ' affect other valid categories '
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ', 0, message)
    # Flush message queue
    get_transaction().commit()
    self.tic()
    # Create some objects
    portal = self.getPortal()
    portal_category = self.getCategoryTool()
    group_nexedi_category = portal_category.group\
                                .newContent( id = 'nexedi', )
    region_europe_category = portal_category.region\
                                .newContent( id = 'europe', )
    module = portal.getDefaultModule('Organisation')
    organisation = module.newContent(portal_type='Organisation',)
    organisation.setGroup('nexedi')
    self.assertEquals(organisation.getGroupValue(), group_nexedi_category)
    organisation.setRegion('europe')
    self.assertEquals(organisation.getRegionValue(), region_europe_category)
    organisation.setRole('not_exists')
    self.assertEquals(organisation.getRoleValue(), None)
    # Flush message queue
    get_transaction().commit()
    self.tic()
    # Clear catalog
    portal_catalog = self.getCatalogTool()
    portal_catalog.manage_catalogClear()
517
    sql_connection = self.getSQLConnection()
518 519 520 521 522 523 524 525 526 527 528
    
    sql = 'SELECT COUNT(*) FROM category '\
        'WHERE uid=%s and category_strict_membership = 1' %\
        organisation.getUid()
    result = sql_connection.manage_test(sql)
    message_count = result[0]['COUNT(*)']
    self.assertEquals(0, message_count)
    # Commit
    get_transaction().commit()
    self.tic()
    # Check catalog
529 530 531 532
    organisation.reindexObject()
    # Commit
    get_transaction().commit()
    self.tic()
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    sql = 'select count(*) from message'
    result = sql_connection.manage_test(sql)
    message_count = result[0]['COUNT(*)']
    self.assertEquals(0, message_count)
    # Check region and group categories are catalogued
    for base_cat, theorical_count in {
                                      'region':1,
                                      'group':1,
                                      'role':0}.items() :
      sql = """SELECT COUNT(*) FROM category
            WHERE category.uid=%s and category.category_strict_membership = 1
            AND category.base_category_uid = %s""" % (organisation.getUid(),
                    portal_category[base_cat].getUid())
      result = sql_connection.manage_test(sql)
      cataloged_obj_count = result[0]['COUNT(*)']
      self.assertEquals(theorical_count, cataloged_obj_count,
            'category %s is not cataloged correctly' % base_cat)

551
  def test_15_getObject(self, quiet=quiet, run=run_all_test):
552 553 554 555 556
    if not run: return
    if not quiet:
      message = 'getObject'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
557
    # portal_catalog.getObject raises a ValueError if UID parameter is a string
558
    portal_catalog = self.getCatalogTool()
559
    self.assertRaises(ValueError, portal_catalog.getObject, "StringUID")
560 561 562 563 564 565
     
    obj = self._makeOrganisation()
    # otherwise it returns the object
    self.assertEquals(obj, portal_catalog.getObject(obj.getUid()).getObject())
    # but raises KeyError if object is not in catalog
    self.assertRaises(KeyError, portal_catalog.getObject, sys.maxint)
566
  
567 568 569 570 571 572 573 574 575 576 577 578 579
  def test_getitem(self):
    portal_catalog = self.getCatalogTool()
    obj = self._makeOrganisation()
    self.assertEquals(obj,
        portal_catalog.getSQLCatalog()[obj.getUid()].getObject())
    
  def test_path(self):
    portal_catalog = self.getCatalogTool()
    obj = self._makeOrganisation()
    self.assertEquals(obj.getPath(), portal_catalog.getpath(obj.getUid()))
    self.assertRaises(KeyError, portal_catalog.getpath, sys.maxint)

     
580
  def test_16_newUid(self, quiet=quiet, run=run_all_test):
581 582 583 584 585 586 587 588 589 590 591
    if not run: return
    if not quiet:
      message = 'newUid'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
    # newUid should not assign the same uid
    portal_catalog = self.getCatalogTool()
    from Products.ZSQLCatalog.SQLCatalog import UID_BUFFER_SIZE
    uid_dict = {}
    for i in xrange(UID_BUFFER_SIZE * 3):
      uid = portal_catalog.newUid()
592
      self.failUnless(isinstance(uid, long))
593
      self.failIf(uid in uid_dict)
594
      uid_dict[uid] = None
595
  
596
  def test_17_CreationDate_ModificationDate(self, quiet=quiet, run=run_all_test):
597 598 599 600 601 602 603
    if not run: return
    if not quiet:
      message = 'getCreationDate, getModificationDate'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
    portal_catalog = self.getCatalogTool()
    portal = self.getPortal()
604
    sql_connection = self.getSQLConnection()
605 606 607
    
    module = portal.getDefaultModule('Organisation')
    organisation = module.newContent(portal_type='Organisation',)
608 609
    creation_date = organisation.getCreationDate().toZone('UTC').ISO()
    modification_date = organisation.getModificationDate().toZone('UTC').ISO()
610
    get_transaction().commit()
611
    now = DateTime()
612 613 614 615
    self.tic()
    sql = """select creation_date, modification_date 
             from catalog where uid = %s""" % organisation.getUid()
    result = sql_connection.manage_test(sql)
616 617 618 619 620 621
    self.assertEquals(creation_date, 
                      result[0]['creation_date'].ISO())
    self.assertEquals(modification_date,
                      result[0]['modification_date'].ISO())
    self.assertEquals(creation_date, 
                      result[0]['modification_date'].ISO())
622 623 624 625 626 627 628
    
    import time; time.sleep(3)
    organisation.edit(title='edited')
    get_transaction().commit()
    self.tic()
    result = sql_connection.manage_test(sql)
    self.assertEquals(creation_date, result[0]['creation_date'].ISO())
629 630 631
    modification_date = organisation.getModificationDate().toZone('UTC').ISO()
    self.assertNotEquals(modification_date,
                         organisation.getCreationDate())
632 633 634
    # This test was first written with a now variable initialized with
    # DateTime(). But since we are never sure of the time required in
    # order to execute some line of code
635 636
    self.assertEquals(modification_date,
                      result[0]['modification_date'].ISO())
637 638
    self.assertTrue(organisation.getModificationDate()>now)
    self.assertTrue(result[0]['creation_date']<result[0]['modification_date'])
639 640 641 642
  
  # TODO: this test is disabled (and maybe not complete), because this feature
  # is not implemented
  def test_18_buildSQLQueryAnotherTable(self, quiet=quiet, run=0):
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
    """Tests that buildSQLQuery works with another query_table than 'catalog'"""
    if not run: return
    if not quiet:
      message = 'buildSQLQuery with query_table'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
    portal = self.getPortal()
    portal_catalog = self.getCatalogTool()
    # clear catalog
    portal_catalog.manage_catalogClear()
    get_transaction().commit()
    
    # create some content to use destination_section_title as related key
    # FIXME: create the related key here ?
    module = portal.getDefaultModule('Organisation')
    source_organisation = module.newContent( portal_type='Organisation',
                                        title = 'source_organisation')
    destination_organisation = module.newContent( portal_type='Organisation',
                                        title = 'destination_organisation')
    source_organisation.setDestinationSectionValue(destination_organisation)
    source_organisation.recursiveReindexObject()
    destination_organisation.recursiveReindexObject()
665
    get_transaction().commit()
666 667 668 669 670 671 672
    self.tic()

    # buildSQLQuery can use arbitrary table name.
    query_table = "node"
    sql_squeleton = """
    SELECT %(query_table)s.uid,
           %(query_table)s.id
673
    FROM
674
      <dtml-in prefix="table" expr="from_table_list"> 
675 676
        <dtml-var table_item> AS <dtml-var table_key>
        <dtml-unless sequence-end>, </dtml-unless>
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
      </dtml-in>
    <dtml-if where_expression>
    WHERE 
      <dtml-var where_expression>
    </dtml-if>
    <dtml-if order_by_expression>
      ORDER BY <dtml-var order_by_expression>
    </dtml-if>
    """ % {'query_table' : query_table}
    
    portal_skins_custom = portal.portal_skins.custom
    portal_skins_custom.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod(
          id = 'testMethod',
          title = '',
          connection_id = 'erp5_sql_connection',
          arguments = "\n".join([ 'from_table_list',
                                  'where_expression',
                                  'order_by_expression' ]),
          template = sql_squeleton)
    testMethod = portal_skins_custom['testMethod']
    
    default_parametrs = {}
    default_parametrs['portal_type'] = 'Organisation'
    default_parametrs['from_table_list'] = {}
    default_parametrs['where_expression'] = ""
    default_parametrs['order_by_expression'] = None
    
704
    #import pdb; pdb.set_trace()
705 706 707 708 709
    # check that we retrieve our 2 organisations by default.
    kw = default_parametrs.copy()
    kw.update( portal_catalog.buildSQLQuery(
                  query_table = query_table,
                  **kw) )
710 711
    LOG('kw', 0, kw)
    LOG('SQL', 0, testMethod(src__=1, **kw))
712 713 714 715 716 717 718 719
    self.assertEquals(len(testMethod(**kw)), 2)
    
    # check we can make a simple filter on title.
    kw = default_parametrs.copy()
    kw.update( portal_catalog.buildSQLQuery(
                  query_table = query_table,
                  title = 'source_organisation',
                  **kw) )
720 721
    LOG('kw', 1, kw)
    LOG('SQL', 1, testMethod(src__=1, **kw))
722 723 724 725 726 727 728 729 730 731 732 733
    self.assertEquals( len(testMethod(**kw)), 1,
                       testMethod(src__=1, **kw) )
    self.assertEquals( testMethod(**kw)[0]['uid'],
                        source_organisation.getUid(),
                        testMethod(src__=1, **kw) )
    
    # check sort
    kw = default_parametrs.copy()
    kw.update(portal_catalog.buildSQLQuery(
                  query_table = query_table,
                  sort_on = [('id', 'ascending')],
                  **kw))
734 735
    LOG('kw', 2, kw)
    LOG('SQL', 2, testMethod(src__=1, **kw))
736 737 738 739 740 741 742 743 744 745 746 747
    brains = testMethod(**kw)
    self.assertEquals( len(brains), 2,
                       testMethod(src__=1, **kw))
    self.failIf( brains[0]['id'] > brains[1]['id'],
                 testMethod(src__=1, **kw) )
    
    # check related keys works
    kw = default_parametrs.copy()
    kw.update(portal_catalog.buildSQLQuery(
                  query_table = query_table,
                  destination_section_title = 'organisation_destination'),
                  **kw)
748 749
    LOG('kw', 3, kw)
    LOG('SQL', 3, testMethod(src__=1, **kw))
750 751 752 753 754 755
    brains = testMethod(**kw)
    self.assertEquals( len(brains), 1, testMethod(src__=1, **kw) )
    self.assertEquals( brains[0]['uid'],
                       source_organisation.getUid(),
                       testMethod(src__=1, **kw) )
    
756 757
  def test_19_SearchFolderWithNonAsciiCharacter(self,
                                quiet=quiet, run=run_all_test):
Sebastien Robin's avatar
Sebastien Robin committed
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
    if not run: return
    if not quiet:
      message = 'Search Folder With Non Ascii Character'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()

    # Now we will try the same thing as previous test and look at searchFolder
    title='S\xc3\xa9bastien'
    person = person_module.newContent(id='5',portal_type='Person',title=title)
    person.immediateReindexObject()
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertEquals(['5'],folder_object_list)
    folder_object_list = [x.getObject().getId() for x in 
                              person_module.searchFolder(title=title)]
    self.assertEquals(['5'],folder_object_list)
775 776 777 778
  

  def test_20_SearchFolderWithDynamicRelatedKey(self,
                                  quiet=quiet, run=run_all_test):
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
    if not run: return
    if not quiet:
      message = 'Search Folder With Dynamic Related Key'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    # Create some objects
    portal = self.getPortal()
    portal_category = self.getCategoryTool()
    portal_category.group.manage_delObjects([x for x in
        portal_category.group.objectIds()])
    group_nexedi_category = portal_category.group\
                                .newContent( id = 'nexedi', title='Nexedi',
                                             description='a')
    group_nexedi_category2 = portal_category.group\
                                .newContent( id = 'storever', title='Storever',
                                             description='b')
    module = portal.getDefaultModule('Organisation')
    organisation = module.newContent(portal_type='Organisation',)
    organisation.setGroup('nexedi')
    self.assertEquals(organisation.getGroupValue(), group_nexedi_category)
    organisation2 = module.newContent(portal_type='Organisation',)
    organisation2.setGroup('storever')
802
    organisation2.setTitle('Organisation 2')
803 804 805 806 807 808 809 810 811
    self.assertEquals(organisation2.getGroupValue(), group_nexedi_category2)
    # Flush message queue
    get_transaction().commit()
    self.tic()

    # Try to get the organisation with the group title Nexedi
    organisation_list = [x.getObject() for x in 
                         module.searchFolder(group_title='Nexedi')]
    self.assertEquals(organisation_list,[organisation])
812 813 814
    organisation_list = [x.getObject() for x in 
                         module.searchFolder(default_group_title='Nexedi')]
    self.assertEquals(organisation_list,[organisation])
815
    # Try to get the organisation with the group id 
816 817 818 819 820 821 822
    organisation_list = [x.getObject() for x in 
                         module.searchFolder(group_id='storever')]
    self.assertEquals(organisation_list,[organisation2])
    # Try to get the organisation with the group description 'a'
    organisation_list = [x.getObject() for x in 
                         module.searchFolder(group_description='a')]
    self.assertEquals(organisation_list,[organisation])
823 824 825 826 827 828 829 830
    # Try to get the organisation with the group description 'c'
    organisation_list = [x.getObject() for x in 
                         module.searchFolder(group_description='c')]
    self.assertEquals(organisation_list,[])
    # Try to get the organisation with the default group description 'c'
    organisation_list = [x.getObject() for x in 
                         module.searchFolder(default_group_description='c')]
    self.assertEquals(organisation_list,[])
831 832 833 834 835
    # Try to get the organisation with group relative_url
    group_relative_url = group_nexedi_category.getRelativeUrl()
    organisation_list = [x.getObject() for x in 
                 module.searchFolder(group_relative_url=group_relative_url)]
    self.assertEquals(organisation_list, [organisation])
836 837 838 839
    # Try to get the organisation with group uid
    organisation_list = [x.getObject() for x in 
                 module.searchFolder(group_uid=group_nexedi_category.getUid())]
    self.assertEquals(organisation_list, [organisation])
840 841 842 843 844 845
    # Try to get the organisation with the group id AND title of the document
    organisation_list = [x.getObject() for x in 
                         module.searchFolder(group_id='storever',
                                             title='Organisation 2')]
    self.assertEquals(organisation_list,[organisation2])

846

847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
  def test_21_SearchFolderWithDynamicStrictRelatedKey(self,
                                  quiet=quiet, run=run_all_test):
    if not run: return
    if not quiet:
      message = 'Search Folder With Strict Dynamic Related Key'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    # Create some objects
    portal = self.getPortal()
    portal_category = self.getCategoryTool()
    portal_category.group.manage_delObjects([x for x in
        portal_category.group.objectIds()])
    group_nexedi_category = portal_category.group\
                                .newContent( id = 'nexedi', title='Nexedi',
                                             description='a')
    sub_group_nexedi = group_nexedi_category\
                                .newContent( id = 'erp5', title='ERP5',
                                             description='b')
    module = portal.getDefaultModule('Organisation')
    organisation = module.newContent(portal_type='Organisation',)
    organisation.setGroup('nexedi/erp5')
    self.assertEquals(organisation.getGroupValue(), sub_group_nexedi)
    # Flush message queue
    get_transaction().commit()
    self.tic()

    # Try to get the organisation with the group title Nexedi
    organisation_list = [x.getObject() for x in 
                         module.searchFolder(strict_group_title='Nexedi')]
    self.assertEquals(organisation_list,[])
    # Try to get the organisation with the group title ERP5
    organisation_list = [x.getObject() for x in 
                         module.searchFolder(strict_group_title='ERP5')]
    self.assertEquals(organisation_list,[organisation])
    # Try to get the organisation with the group description a
    organisation_list = [x.getObject() for x in 
                         module.searchFolder(strict_group_description='a')]
    self.assertEquals(organisation_list,[])
    # Try to get the organisation with the group description b
    organisation_list = [x.getObject() for x in 
                         module.searchFolder(strict_group_description='b')]
    self.assertEquals(organisation_list,[organisation])

  def test_22_SearchingWithUnicode(self, quiet=quiet, run=run_all_test):
892 893 894 895 896 897 898 899 900 901 902
    if not run: return
    if not quiet:
      message = 'Test searching with unicode'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()
    person_module.newContent(portal_type='Person', title='A Person')
    get_transaction().commit()
    self.tic()
    self.assertNotEquals([], self.getCatalogTool().searchResults(
903 904
                                     portal_type='Person', title=u'A Person'))
    
905 906 907 908 909 910 911 912 913 914
  def test_23_DeleteObjectRaiseErrorWhenQueryFail(self, quiet=quiet, run=run_all_test):
    if not run: return
    if not quiet:
      message = 'Test That Delete Object Raise Error When the Query Fail'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
    portal_catalog = self.getCatalogTool()
    person_module = self.getPersonModule()
    # Now we will ask to immediatly reindex
    person = person_module.newContent(id='2',
915 916
                                      portal_type='Person',)
    person.immediateReindexObject()
917
    path_list = [person.getRelativeUrl()]
918
    self.checkRelativeUrlInSQLPathList(path_list)
919 920 921 922 923
    # We will delete the connector
    # in order to make sure it will not work any more
    portal = self.getPortal()
    portal.manage_delObjects('erp5_sql_connection')
    # Then it must be impossible to delete an object
924 925 926
    uid = person.getUid()
    unindex = portal_catalog.unindexObject
    self.assertRaises(AttributeError,unindex,person,uid=person.getUid())
927
    get_transaction().abort()
Sebastien Robin's avatar
Sebastien Robin committed
928

Bartek Górny's avatar
Bartek Górny committed
929
  def test_24_SortOn(self, quiet=quiet, run=run_all_test):
930
    if not run: return
931 932 933 934
    if not quiet:
      message = 'Test Sort On'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
935
    self.assertTrue(
936
            self.getCatalogTool().buildSQLQuery(
937
            sort_on=(('catalog.title', 'ascending'),))['order_by_expression'] in \
938
            ('catalog.title', '`catalog`.`title` ASC', 'catalog.title ASC'))
939

Bartek Górny's avatar
Bartek Górny committed
940
  def test_25_SortOnDescending(self, quiet=quiet, run=run_all_test):
941
    if not run: return
942 943 944 945
    if not quiet:
      message = 'Test Sort On Descending'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
946
    self.assertTrue(
947
            self.getCatalogTool().buildSQLQuery(
948 949
            sort_on=(('catalog.title', 'descending'),))['order_by_expression'] in \
            ('catalog.title DESC', '`catalog`.`title` DESC'))
950
    
951
  def test_26_SortOnUnknownKeys(self, quiet=quiet, run=run_all_test):
952
    if not run: return
953 954 955 956 957
    if not run: return
    if not quiet:
      message = 'Test Sort On Unknow Keys'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
958 959 960 961
    self.assertEquals('',
          self.getCatalogTool().buildSQLQuery(
          sort_on=(('ignored', 'ascending'),))['order_by_expression'])
  
Bartek Górny's avatar
Bartek Górny committed
962
  def test_27_SortOnAmbigousKeys(self, quiet=quiet, run=run_all_test):
963
    if not run: return
964 965 966 967
    if not quiet:
      message = 'Test Sort On Ambigous Keys'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
968 969
    # if the sort key is found on the catalog table, it will use that catalog
    # table.
970
    self.assertTrue(
971
          self.getCatalogTool().buildSQLQuery(
972 973
          sort_on=(('title', 'ascending'),))['order_by_expression'] in \
          ('catalog.title', '`catalog`.`title` ASC'))
974 975 976
    
    # if not found on catalog, it won't do any filtering
    # in the above, start_date exists both in delivery and movement table.
977 978 979
    self.assertRaises(ValueError, self.getCatalogTool().buildSQLQuery,
          sort_on=(('start_date', 'ascending'),))

980
    # of course, in that case, it's possible to prefix with table name
981
    self.assertTrue(
982 983
          self.getCatalogTool().buildSQLQuery(
          sort_on=(('delivery.start_date', 'ascending'),
984 985
                    ))['order_by_expression'] in \
          ('delivery.start_date', 'delivery.start_date ASC'))
986
    
Bartek Górny's avatar
Bartek Górny committed
987
  def test_28_SortOnMultipleKeys(self, quiet=quiet, run=run_all_test):
988
    if not run: return
989 990 991 992
    if not quiet:
      message = 'Test Sort On Multiple Keys'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
993
    self.assertTrue(
994 995 996
              self.getCatalogTool().buildSQLQuery(
              sort_on=(('catalog.title', 'ascending'),
                       ('catalog.id', 'asc')))
997
                       ['order_by_expression'].replace(' ', '') in \
998
              ('catalog.title,catalog.id', '`catalog`.`title`ASC,`catalog`.`id`ASC', 'catalog.titleASC,catalog.idASC'))
999

Bartek Górny's avatar
Bartek Górny committed
1000
  def test_29_SortOnRelatedKey(self, quiet=quiet, run=run_all_test):
1001 1002 1003
    """Sort-on parameter and related key. (Assumes that region_title is a \
    valid related key)"""
    if not run: return
1004 1005 1006 1007
    if not quiet:
      message = 'Test Sort On Related Keys'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    self.assertTrue(
              self.getCatalogTool().buildSQLQuery(region_title='foo',
              sort_on=(('region_title', 'ascending'),))['order_by_expression'].endswith('.`title` ASC'))
    self.assertTrue(
              self.getCatalogTool().buildSQLQuery(region_title='foo',
              sort_on=(('region_title', 'descending'),))['order_by_expression'].endswith('.`title` DESC'))
    self.assertTrue(
              self.getCatalogTool().buildSQLQuery(
              sort_on=(('region_title', 'ascending'),))['order_by_expression'].endswith('.`title` ASC'),
              'sort_on parameter must be taken into account even if related key '
              'is not a parameter of the current query')
    self.assertTrue(
1020
              self.getCatalogTool().buildSQLQuery(
1021
              sort_on=(('region_title', 'descending'),))['order_by_expression'].endswith('.`title` DESC'),
1022 1023 1024
              'sort_on parameter must be taken into account even if related key '
              'is not a parameter of the current query')

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
  def _makeOrganisation(self, **kw):
    """Creates an Organisation in it's default module and reindex it.
    By default, it creates a group/nexedi category, and make the organisation a
    member of this category.
    """
    group_cat = self.getCategoryTool().group
    if not hasattr(group_cat, 'nexedi'):
      group_cat.newContent(id='nexedi', title='Nexedi Group',)
    module = self.getPortal().getDefaultModule('Organisation')
    organisation = module.newContent(portal_type='Organisation')
    kw.setdefault('group', 'group/nexedi')
    organisation.edit(**kw)
    get_transaction().commit()
    self.tic()
    return organisation
1040
  
Bartek Górny's avatar
Bartek Górny committed
1041
  def test_30_SimpleQueryDict(self, quiet=quiet, run=run_all_test):
1042 1043 1044
    """use a dict as a keyword parameter.
    """
    if not run: return
1045 1046 1047 1048
    if not quiet:
      message = 'Test Simple Query Dict'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
1049 1050 1051 1052 1053 1054
    organisation_title = 'Nexedi Organisation'
    organisation = self._makeOrganisation(title=organisation_title)
    self.assertEquals([organisation.getPath()],
        [x.path for x in self.getCatalogTool()(
                title={'query': organisation_title})])

Bartek Górny's avatar
Bartek Górny committed
1055
  def test_31_RelatedKeySimpleQueryDict(self, quiet=quiet, run=run_all_test):
1056 1057 1058
    """use a dict as a keyword parameter, but using a related key
    """
    if not run: return
1059 1060 1061 1062
    if not quiet:
      message = 'Test Related Key Simple Query Dict'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
1063 1064 1065 1066 1067 1068 1069 1070
    organisation = self._makeOrganisation()
    self.assertEquals([organisation.getPath()],
        [x.path for x in self.getCatalogTool()(
                group_title={'query': 'Nexedi Group'},
                # have to filter on portal type, because the group category is
                # also member of itself
                portal_type=organisation.getPortalTypeName())])

Bartek Górny's avatar
Bartek Górny committed
1071
  def test_32_SimpleQueryDictWithOrOperator(self, quiet=quiet,
1072 1073 1074 1075
                                                    run=run_all_test):
    """use a dict as a keyword parameter, with OR operator.
    """
    if not run: return
1076 1077 1078 1079
    if not quiet:
      message = 'Test Query Dict With Or Operator'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
1080 1081 1082 1083 1084 1085 1086 1087
    organisation_title = 'Nexedi Organisation'
    organisation = self._makeOrganisation(title=organisation_title)
  
    self.assertEquals([organisation.getPath()],
        [x.path for x in self.getCatalogTool()(
                title={'query': (organisation_title, 'something else'),
                       'operator': 'or'})])

Bartek Górny's avatar
Bartek Górny committed
1088
  def test_33_SimpleQueryDictWithAndOperator(self, quiet=quiet,
1089 1090 1091 1092
                                                     run=run_all_test):
    """use a dict as a keyword parameter, with AND operator.
    """
    if not run: return
1093 1094 1095 1096
    if not quiet:
      message = 'Test Query Dict With And Operator'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
1097 1098 1099 1100 1101 1102 1103 1104 1105
    organisation_title = 'Nexedi Organisation'
    organisation = self._makeOrganisation(title=organisation_title)
  
    self.assertEquals([organisation.getPath()],
        [x.path for x in self.getCatalogTool()(
                # this is useless, we must find a better use case
                title={'query': (organisation_title, organisation_title),
                       'operator': 'and'})])

Bartek Górny's avatar
Bartek Górny committed
1106
  def test_34_SimpleQueryDictWithMaxRangeParameter(self, quiet=quiet,
1107 1108 1109 1110
                                                     run=run_all_test):
    """use a dict as a keyword parameter, with max range parameter ( < )
    """
    if not run: return
1111 1112 1113 1114
    if not quiet:
      message = 'Test Query Dict With Max Range Operator'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
1115 1116 1117 1118 1119 1120 1121 1122 1123
    org_a = self._makeOrganisation(title='A')
    org_b = self._makeOrganisation(title='B')
    org_c = self._makeOrganisation(title='C')
  
    self.assertEquals([org_a.getPath()],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',
                title={'query': 'B', 'range': 'max'})])
  
Bartek Górny's avatar
Bartek Górny committed
1124
  def test_35_SimpleQueryDictWithMinRangeParameter(self, quiet=quiet,
1125 1126 1127 1128
                                                     run=run_all_test):
    """use a dict as a keyword parameter, with min range parameter ( >= )
    """
    if not run: return
1129 1130 1131 1132
    if not quiet:
      message = 'Test Query Dict With Min Range Operator'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
    org_a = self._makeOrganisation(title='A')
    org_b = self._makeOrganisation(title='B')
    org_c = self._makeOrganisation(title='C')
  
    self.failIfDifferentSet([org_b.getPath(), org_c.getPath()],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',
                title={'query': 'B', 'range': 'min'})])


Bartek Górny's avatar
Bartek Górny committed
1143
  def test_36_SimpleQueryDictWithNgtRangeParameter(self, quiet=quiet,
1144 1145 1146 1147
                                                     run=run_all_test):
    """use a dict as a keyword parameter, with ngt range parameter ( <= )
    """
    if not run: return
1148 1149 1150 1151
    if not quiet:
      message = 'Test Query Dict With Ngt Range Operator'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
1152 1153 1154 1155 1156 1157 1158 1159 1160
    org_a = self._makeOrganisation(title='A')
    org_b = self._makeOrganisation(title='B')
    org_c = self._makeOrganisation(title='C')
  
    self.failIfDifferentSet([org_a.getPath(), org_b.getPath()],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',
                title={'query': 'B', 'range': 'ngt'})])

Bartek Górny's avatar
Bartek Górny committed
1161
  def test_37_SimpleQueryDictWithMinMaxRangeParameter(self, quiet=quiet,
1162 1163 1164 1165
                                                     run=run_all_test):
    """use a dict as a keyword parameter, with minmax range parameter ( >=  < )
    """
    if not run: return
1166 1167 1168 1169
    if not quiet:
      message = 'Test Query Dict With Min Max Range Operator'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
1170 1171 1172 1173 1174 1175 1176 1177 1178
    org_a = self._makeOrganisation(title='A')
    org_b = self._makeOrganisation(title='B')
    org_c = self._makeOrganisation(title='C')
  
    self.assertEquals([org_b.getPath()],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',
                title={'query': ('B', 'C'), 'range': 'minmax'})])
  
Bartek Górny's avatar
Bartek Górny committed
1179
  def test_38_SimpleQueryDictWithMinNgtRangeParameter(self, quiet=quiet,
1180 1181 1182 1183
                                                     run=run_all_test):
    """use a dict as a keyword parameter, with minngt range parameter ( >= <= )
    """
    if not run: return
1184 1185 1186 1187
    if not quiet:
      message = 'Test Query Dict With Min Ngt Range Operator'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
1188 1189 1190 1191 1192 1193 1194 1195 1196
    org_a = self._makeOrganisation(title='A')
    org_b = self._makeOrganisation(title='B')
    org_c = self._makeOrganisation(title='C')
  
    self.failIfDifferentSet([org_b.getPath(), org_c.getPath()],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',
                title={'query': ('B', 'C'), 'range': 'minngt'})])

1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
  def test_QueryDictFromRequest(self):
    """use a dict from REQUEST as a keyword parameter.
    """
    org_a = self._makeOrganisation(title='A')
    org_b = self._makeOrganisation(title='B')
    org_c = self._makeOrganisation(title='C')
    
    query_dict = {'query': ('B', 'C'), 'range': 'minngt'}
    from ZPublisher.HTTPRequest import record
    query_record = record()
    for k, v in query_dict.items():
      setattr(query_record, k, v)

    self.assertEquals(set([org_b.getPath(), org_c.getPath()]),
        set([x.path for x in self.getCatalogTool()(
                portal_type='Organisation',
                title=query_record)]))

Bartek Górny's avatar
Bartek Górny committed
1215
  def test_39_DeferredConnection(self, quiet=quiet, run=run_all_test):
1216 1217 1218
    """ERP5Catalog uses a deferred connection for full text indexing.
    """
    if not run: return
1219 1220 1221 1222
    if not quiet:
      message = 'Test Deferred Connection'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
    erp5_sql_deferred_connection = getattr(self.getPortal(),
                                    'erp5_sql_deferred_connection',
                                    None)
    self.failUnless(erp5_sql_deferred_connection is not None)
    self.assertEquals('Z MySQL Deferred Database Connection',
                      erp5_sql_deferred_connection.meta_type)
    for method in ['z0_drop_fulltext',
                   'z0_uncatalog_fulltext',
                   'z_catalog_fulltext_list',
                   'z_create_fulltext', ]:
      self.assertEquals('erp5_sql_deferred_connection',
                getattr(self.getCatalogTool().getSQLCatalog(),
                              method).connection_id)

Bartek Górny's avatar
Bartek Górny committed
1237
  def test_40_DeleteObject(self, quiet=quiet, run=run_all_test):
1238 1239 1240
    """Simple test to exercise object deletion
    """
    if not run: return
1241 1242 1243 1244
    if not quiet:
      message = 'Test Delete Object'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
1245 1246 1247 1248 1249 1250 1251 1252
    folder = self.getOrganisationModule()
    ob = folder.newContent()
    get_transaction().commit()
    self.tic()
    folder.manage_delObjects([ob.getId()])
    get_transaction().commit()
    self.tic()
    self.assertEquals(0, len(folder.searchFolder()))
1253

Bartek Górny's avatar
Bartek Górny committed
1254
  def test_41_ProxyRolesInRestrictedPython(self, quiet=quiet, run=run_all_test):
1255 1256 1257
    """test that proxy roles apply to catalog queries within python scripts
    """
    if not run: return
1258 1259 1260 1261
    if not quiet:
      message = 'Proxy Roles In Restricted Python'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
1262 1263 1264 1265 1266 1267
    perm = 'View'

    uf = self.getPortal().acl_users
    uf._doAddUser('alice', '', ['Member', 'Manager', 'Assignor'], [])
    uf._doAddUser('bob', '', ['Member'], [])
    # create restricted object
1268
    self.login('alice')
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
    folder = self.getOrganisationModule()
    ob = folder.newContent()
    # make sure permissions are correctly set
    folder.manage_permission('Access contents information', ['Member'], 1)
    folder.manage_permission(perm, ['Member'], 1)
    ob.manage_permission('Access contents information', ['Member'], 1)
    ob.manage_permission(perm, ['Manager'], 0)
    get_transaction().commit()
    self.tic()
    # check access
    self.assertEquals(1, getSecurityManager().checkPermission(perm, folder))
    self.assertEquals(1, getSecurityManager().checkPermission(perm, ob))
1281
    self.login('bob')
1282 1283 1284
    self.assertEquals(1, getSecurityManager().checkPermission(perm, folder))
    self.assertEquals(None, getSecurityManager().checkPermission(perm, ob))
    # add a script that calls a catalog method
1285
    self.login('alice')
1286 1287 1288 1289 1290
    script = createZODBPythonScript(self.getPortal().portal_skins.custom,
        'catalog_test_script', '', "return len(context.searchFolder())")

    # test without proxy role
    self.assertEquals(1, folder.catalog_test_script())
1291
    self.login('bob')
1292 1293 1294
    self.assertEquals(0, folder.catalog_test_script())

    # test with proxy role and correct role
1295
    self.login('alice')
1296 1297
    script.manage_proxy(['Manager'])
    self.assertEquals(1, folder.catalog_test_script())
1298
    self.login('bob')
1299 1300 1301
    self.assertEquals(1, folder.catalog_test_script())

    # test with proxy role and wrong role
1302
    self.login('alice')
1303 1304 1305 1306
    script.manage_proxy(['Assignor'])
    # proxy roles must overwrite the user's roles, even if he is the owner
    # of the script
    self.assertEquals(0, folder.catalog_test_script())
1307
    self.login('bob')
1308 1309
    self.assertEquals(0, folder.catalog_test_script())

Bartek Górny's avatar
Bartek Górny committed
1310
  def test_42_SearchableText(self, quiet=quiet, run=run_all_test):
1311 1312 1313
    """Tests SearchableText is working in ERP5Catalog
    """
    if not run: return
1314 1315 1316 1317
    if not quiet:
      message = 'Searchable Text'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
1318 1319 1320 1321
    folder = self.getOrganisationModule()
    ob = folder.newContent()
    ob.setTitle('The title of this object')
    self.failUnless('this' in ob.SearchableText(), ob.SearchableText())
1322 1323
    # add some other objects, we need to create a minimum quantity of data for
    # full text queries to work correctly
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
    for i in range(10):
      otherob = folder.newContent()
      otherob.setTitle('Something different')
      self.failIf('this' in otherob.SearchableText(), otherob.SearchableText())
    # catalog those objects
    get_transaction().commit()
    self.tic()
    self.assertEquals([ob],
        [x.getObject() for x in self.getCatalogTool()(
                portal_type='Organisation', SearchableText='title')])
1334 1335
    self.assertEquals(1, self.getCatalogTool().countResults(
              portal_type='Organisation', SearchableText='title')[0][0])
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
    
    # 'different' is found in more than 50% of records
    # MySQL ignores such a word, but Tritonn does not ignore.
    try:
      self.portal.erp5_sql_connection.manage_test('SHOW SENNA STATUS')
    except ProgrammingError:
      # MySQL
      self.assertEquals([],
          [x.getObject for x in self.getCatalogTool()(
                  portal_type='Organisation', SearchableText='different')])
      self.assertEquals(0, self.getCatalogTool().countResults(
                portal_type='Organisation', SearchableText='different')[0][0])
    else:
      # Tritonn
      self.assertEquals(10, self.getCatalogTool().countResults(
                portal_type='Organisation', SearchableText='different')[0][0])
1352
    
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
  def test_43_ManagePasteObject(self, quiet=quiet, run=run_all_test):
    if not run: return
    if not quiet:
      message = 'Manage Paste Objects'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
    portal_catalog = self.getCatalogTool()
    person_module = self.getPersonModule()
    person = person_module.newContent(id='1',portal_type='Person')
    get_transaction().commit()
    self.tic()
    copy_data = person_module.manage_copyObjects([person.getId()])
    new_id = person_module.manage_pasteObjects(copy_data)[0]['new_id']
    new_person = person_module[new_id]
    get_transaction().commit()
    self.tic()
    path_list = [new_person.getRelativeUrl()]
1370
    self.checkRelativeUrlInSQLPathList(path_list)
1371

1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
  def test_44_ParentRelatedKeys(self, quiet=quiet, run=run_all_test):
    if not run: return
    if not quiet:
      message = 'Parent related keys'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
    portal_catalog = self.getCatalogTool()
    person_module = self.getPersonModule()
    person_module.reindexObject()
    person = person_module.newContent(id='1',portal_type='Person')
    get_transaction().commit()
    self.tic()
    self.assertEquals([person],
        [x.getObject() for x in self.getCatalogTool()(
               parent_title=person_module.getTitle())])
    
1388
  def test_45_QueryAndComplexQuery(self,quiet=quiet, run=run_all_test):
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
    """
    """
    if not run: return
    if not quiet:
      message = 'Query And Complex Query'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
    org_a = self._makeOrganisation(title='abc',description='abc')
    org_b = self._makeOrganisation(title='bcd',description='bcd')
    org_c = self._makeOrganisation(title='efg',description='efg')
    org_e = self._makeOrganisation(title='foo',description='bir')
    org_f = self._makeOrganisation(title='foo',description='bar')

1402 1403 1404 1405 1406 1407
    # uid=[]
    catalog_kw= {'query':Query(uid=[])}
    self.failIfDifferentSet(
        [x.getPath() for x in (org_a, org_b, org_c, org_e, org_f)],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',**catalog_kw)])
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
    # title='abc'
    catalog_kw= {'title':Query(title='abc')}
    self.failIfDifferentSet([org_a.getPath()],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',**catalog_kw)])
    # title with b and c
    catalog_kw= {'title':Query(title=['%b%','%c%'],operator='AND')}
    self.failIfDifferentSet([org_a.getPath(), org_b.getPath()],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',**catalog_kw)])
    # title='bcd' OR description='efg'
    catalog_kw = {'query':ComplexQuery(Query(title='bcd'),
                                       Query(description='efg'),
                                       operator='OR')}
    self.failIfDifferentSet([org_b.getPath(), org_c.getPath()],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',**catalog_kw)])
    # Recursive Complex Query
    # (title='abc' and description='abc') OR 
    #  title='foo' and description='bar'
    catalog_kw = {'query':ComplexQuery(ComplexQuery(Query(title='abc'),
                                                    Query(description='abc'),
                                                    operator='AND'),
                                       ComplexQuery(Query(title='foo'),
                                                    Query(description='bar'),
                                                    operator='AND'),
                                       operator='OR')}
    self.failIfDifferentSet([org_a.getPath(), org_f.getPath()],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',**catalog_kw)])
Nicolas Delaby's avatar
Nicolas Delaby committed
1438
  
1439
  def test_46_TestLimit(self,quiet=quiet, run=run_all_test):
Nicolas Delaby's avatar
Nicolas Delaby committed
1440 1441 1442 1443 1444 1445 1446
    """
    """
    if not run: return
    if not quiet:
      message = 'Test Limit'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
1447 1448

    ctool = self.getCatalogTool()
1449 1450
    old_default_result_limit = ctool.default_result_limit
    max_ = ctool.default_result_limit = 3
1451 1452 1453 1454 1455
    #Create max + 2 Organisations
    for i in xrange(max_ + 2):
      self._makeOrganisation(title='abc%s' % (i), description='abc')
    self.assertEqual(max_,
                     len(self.getCatalogTool()(portal_type='Organisation')))
1456
    self.assertEqual(max_ + 2,
1457 1458
            len(self.getCatalogTool()(portal_type='Organisation', limit=None)))
    ctool.default_result_limit = old_default_result_limit
1459

1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
  def playActivityList(self, method_id_list):
    get_transaction().commit()
    portal_activities = self.getActivityTool()
    for i in range(0,100):
      message_list = portal_activities.getMessageList()
      for message in message_list:
        #if message.method_id=='setHotReindexingState':
        #  import pdb;pdb.set_trace()
        if message.method_id in method_id_list:
          try:
            portal_activities.manageInvoke(message.object_path,message.method_id)
          except ActivityFlushError,m:
            pass
      get_transaction().commit()

1475
  def test_48_ERP5Site_hotReindexAll(self, quiet=quiet, run=run_all_test):
1476 1477 1478 1479 1480 1481
    """
      test the hot reindexing of catalog -> catalog2 
      then a hot reindexing detailed catalog2 -> catalog
      
      this test use the variable environment: extra_sql_connection_string_list
    """
1482 1483 1484 1485 1486 1487 1488
    if not run: return
    if not quiet:
      message = 'Hot Reindex All'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    portal = self.getPortal()
1489
    self.original_connection_id = 'erp5_sql_connection'
1490
    self.original_deferred_connection_id = 'erp5_sql_deferred_connection2'
1491
    self.new_connection_id = 'erp5_sql_connection2'
1492
    self.new_deferred_connection_id = 'erp5_sql_deferred_connection2'
1493
    new_connection_string = getExtraSqlConnectionStringList()[0]
1494 1495 1496 1497 1498 1499 1500 1501 1502

    # Skip this test if default connection string is not "test test".
    original_connection = getattr(portal, self.original_connection_id)
    connection_string = original_connection.connection_string
    if (connection_string == new_connection_string):
      message = 'SKIPPED: default connection string is the same as the one for hot-reindex catalog'
      ZopeTestCase._print(message)
      LOG('Testing... ',0,message)

1503
    portal_category = self.getCategoryTool()
1504
    portal_activities = self.getActivityTool()
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
    self.base_category = portal_category.newContent(portal_type='Base Category',
                                               title="GreatTitle1")
    module = portal.getDefaultModule('Organisation')
    self.organisation = module.newContent(portal_type='Organisation',
                                     title="GreatTitle2")
    # Flush message queue
    get_transaction().commit()
    self.tic()
    # Create new connectors
    portal.manage_addZMySQLConnection(self.new_connection_id,'',
1515
                                      new_connection_string)
1516 1517
    new_connection = portal[self.new_connection_id]
    new_connection.manage_open_connection()
1518 1519 1520 1521 1522 1523 1524 1525
    portal.manage_addZMySQLConnection(self.new_deferred_connection_id,'',
                                      new_connection_string)
    new_connection = portal[self.new_deferred_connection_id]
    new_connection.manage_open_connection()
    # the transactionless connector must not be change because this one
    # create the portal_ids otherwise it create of conflicts with uid
    # objects

1526 1527 1528 1529 1530 1531
    # Create new catalog
    portal_catalog = self.getCatalogTool()
    self.original_catalog_id = 'erp5_mysql_innodb'
    self.new_catalog_id = self.original_catalog_id + '2'
    cp_data = portal_catalog.manage_copyObjects(ids=('erp5_mysql_innodb',))
    new_id = portal_catalog.manage_pasteObjects(cp_data)[0]['new_id']
1532
    portal_catalog.manage_renameObject(id=new_id, new_id=self.new_catalog_id)
1533 1534 1535

    # Parse all methods in the new catalog in order to change the connector
    new_catalog = portal_catalog[self.new_catalog_id]
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
    source_sql_connection_id_list=list((self.original_connection_id,
                                  self.original_deferred_connection_id))
    destination_sql_connection_id_list=list((self.new_connection_id,
                                       self.new_deferred_connection_id))
    #launch the full hot reindexing 
    portal_catalog.manage_hotReindexAll(source_sql_catalog_id=self.original_catalog_id,
                 destination_sql_catalog_id=self.new_catalog_id,
                 source_sql_connection_id_list=source_sql_connection_id_list,
                 destination_sql_connection_id_list=destination_sql_connection_id_list,
                 update_destination_sql_catalog=True)

1547 1548 1549 1550 1551
    # Flush message queue
    get_transaction().commit()
    self.tic()
    self.organisation2 = module.newContent(portal_type='Organisation',
                                     title="GreatTitle2")
1552
    first_deleted_url = self.organisation2.getRelativeUrl()
1553 1554 1555
    get_transaction().commit()
    self.tic()
    path_list = [self.organisation.getRelativeUrl()]
1556 1557
    self.checkRelativeUrlInSQLPathList(path_list, connection_id=self.original_connection_id)
    self.checkRelativeUrlInSQLPathList(path_list, connection_id=self.new_connection_id)
1558
    path_list = [first_deleted_url]
1559 1560
    self.checkRelativeUrlNotInSQLPathList(path_list, connection_id=self.original_connection_id)
    self.checkRelativeUrlInSQLPathList(path_list, connection_id=self.new_connection_id)
1561 1562

    # Make sure some zsql method use the right connection_id
1563
    zsql_method = portal.portal_skins.erp5_core.Resource_zGetInventoryList
1564 1565
    self.assertEquals(getattr(zsql_method,'connection_id'),self.new_connection_id)

1566 1567 1568
    self.assertEquals(portal_catalog.getHotReindexingState(),
                      HOT_REINDEXING_FINISHED_STATE)

1569 1570 1571 1572 1573
    # Do a hot reindex in the reverse way, but this time a more
    # complicated hot reindex
    portal_catalog.manage_hotReindexAll(self.new_catalog_id,
                                 self.original_catalog_id)
    get_transaction().commit()
1574 1575
    self.assertEquals(portal_catalog.getHotReindexingState(),
                      HOT_REINDEXING_RECORDING_STATE)
1576 1577
    self.organisation3 = module.newContent(portal_type='Organisation',
                                     title="GreatTitle2")
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
    # Try something more complicated, create new object, reindex it
    # and then delete it
    self.deleted_organisation = module.newContent(portal_type='Organisation',
                                     title="GreatTitle2")
    self.deleted_organisation.immediateReindexObject()
    get_transaction().commit()
    deleted_url = self.deleted_organisation.getRelativeUrl()
    module.manage_delObjects(ids=[self.deleted_organisation.getId()])
    get_transaction().commit()
    # We will invoke acitivities one by one in order to make sure we can test
    # the double indexing state of hot reindexing
    self.playActivityList(('Folder_reindexAll',
                         'InventoryModule_reindexMovementList',
                         'immediateReindexObject',
                         'Folder_reindexObjectList',
1593 1594 1595 1596 1597
                         'unindexObject',
                         'recursiveImmediateReindexObject'))
    # try to delete objects in double indexing state
    module.manage_delObjects(ids=[self.organisation2.getId()])
    self.playActivityList(('immediateReindexObject',
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
                         'unindexObject',
                         'recursiveImmediateReindexObject',
                         'playBackRecordedObjectList',
                         'getId',
                         'setHotReindexingState'))
    self.assertEquals(portal_catalog.getHotReindexingState(),
                      HOT_REINDEXING_DOUBLE_INDEXING_STATE)
    # Now we have started an double indexing
    self.next_deleted_organisation = module.newContent(portal_type='Organisation',
                                     title="GreatTitle2",id='toto')
    next_deleted_url = self.next_deleted_organisation.getRelativeUrl()
    get_transaction().commit()
    self.playActivityList(( 'immediateReindexObject',
                         'recursiveImmediateReindexObject',))
    path_list=[next_deleted_url]
    self.checkRelativeUrlInSQLPathList(path_list,connection_id=self.new_connection_id)
    self.checkRelativeUrlInSQLPathList(path_list,connection_id=self.original_connection_id)
    module.manage_delObjects(ids=[self.next_deleted_organisation.getId()])
1616 1617 1618 1619
    #Create object during the double indexing to check the security object
    #after the hot reindexing
    self.organisation4 = module.newContent(portal_type='Organisation',
                                     title="GreatTitle2")
1620 1621
    get_transaction().commit()
    self.tic()
1622 1623
    self.assertEquals(portal_catalog.getHotReindexingState(),
                      HOT_REINDEXING_FINISHED_STATE)
1624 1625 1626 1627 1628 1629 1630
    # Check Security UID object exist in roles and users
    # compare the number object in the catalog
    count_catalog = len(self.getSQLPathList(self.original_connection_id))
    count_restricted_catalog = len(self.getSQLPathListWithRolesAndUsers(\
                               self.original_connection_id))
    self.assertEquals(count_catalog, count_restricted_catalog)

1631 1632 1633
    path_list = [self.organisation3.getRelativeUrl()]
    self.checkRelativeUrlInSQLPathList(path_list,connection_id=self.new_connection_id)
    self.checkRelativeUrlInSQLPathList(path_list,connection_id=self.original_connection_id)
1634
    path_list = [first_deleted_url,deleted_url,next_deleted_url]
1635 1636
    self.checkRelativeUrlNotInSQLPathList(path_list,connection_id=self.new_connection_id)
    self.checkRelativeUrlNotInSQLPathList(path_list,connection_id=self.original_connection_id)
1637 1638 1639 1640
    # Make sure module are there
    path_list = [module.getRelativeUrl()]
    self.checkRelativeUrlInSQLPathList(path_list, connection_id=self.new_connection_id)
    self.checkRelativeUrlInSQLPathList(path_list, connection_id=self.original_connection_id)
1641
    
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
  def test_47_Unrestricted(self, quiet=quiet, run=run_all_test):
    """test unrestricted search/count results.
    """
    if not run: return
    if not quiet:
      message = 'Unrestricted queries'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    uf = self.getPortal().acl_users
    uf._doAddUser('alice', '', ['Member', 'Manager', 'Assignor'], [])
    uf._doAddUser('bob', '', ['Member'], [])
1654

1655
    # create a document that only alice can view
1656
    self.login('alice')
1657 1658 1659 1660 1661 1662 1663
    folder = self.getOrganisationModule()
    ob = folder.newContent(title='Object Title')
    ob.manage_permission('View', ['Manager'], 0)
    get_transaction().commit()
    self.tic()
    
    # bob cannot see the document
1664
    self.login('bob')
1665 1666 1667 1668 1669 1670 1671 1672 1673
    ctool = self.getCatalogTool()
    self.assertEquals(0, len(ctool.searchResults(title='Object Title')))
    self.assertEquals(0, ctool.countResults(title='Object Title')[0][0])
    
    # unless using unrestricted searches
    self.assertEquals(1,
                len(ctool.unrestrictedSearchResults(title='Object Title')))
    self.assertEquals(1,
                ctool.unrestrictedCountResults(title='Object Title')[0][0])
1674
    
1675
  @todo_erp5
Aurel's avatar
Aurel committed
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
  def test_49_IndexInOrderedSearchFolder(self, quiet=quiet, run=run_all_test):
    if not run: return
    if not quiet:
      message = 'Index In Ordered Search Folder'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()

    # Clear catalog
    portal_catalog = self.getCatalogTool()
    portal_catalog.manage_catalogClear()
    catalog = portal_catalog.objectValues()[0]

    person = person_module.newContent(id='a',portal_type='Person',title='a',description='z')
    person.immediateReindexObject()
    person = person_module.newContent(id='b',portal_type='Person',title='a',description='y')
    person.immediateReindexObject()
    person = person_module.newContent(id='c',portal_type='Person',title='a',description='x')
    person.immediateReindexObject()
    index_columns = getattr(catalog, 'sql_catalog_index_on_order_keys', None)
    self.assertNotEqual(index_columns, None)
    self.assertEqual(len(index_columns), 0)
    # Check catalog don't tell to use index if nothing defined
    sql = person_module.searchFolder(src__=1)
    self.failUnless('use index' not in sql)
    sql = person_module.searchFolder(src__=1, sort_on=[('id','ascending')])
    self.failUnless('use index' not in sql)
    sql = person_module.searchFolder(src__=1, sort_on=[('title','ascending')])
    self.failUnless('use index' not in sql)
    # Defined that catalog must tell to use index when order by catalog.title
    index_columns = ('catalog.title',)
    setattr(catalog, 'sql_catalog_index_on_order_keys', index_columns)
    index_columns = getattr(catalog, 'sql_catalog_index_on_order_keys', None)
    self.assertNotEqual(index_columns, None)
    self.assertEqual(len(index_columns), 1)
    # Check catalog tell to use index only when ordering by catalog.title
    sql = person_module.searchFolder(src__=1)
    self.failUnless('use index' not in sql)
    sql = person_module.searchFolder(src__=1, sort_on=[('id','ascending')])
    self.failUnless('use index' not in sql)
    sql = person_module.searchFolder(src__=1, sort_on=[('title','ascending')])
    self.failUnless('use index' in sql)

1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
  def test_50_LocalRolesArgument(self, quiet=quiet, run=run_all_test):
    """test local_roles= argument
    """
    if not run: return
    if not quiet:
      message = 'local_roles= argument'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    uf = self.getPortal().acl_users
    uf._doAddUser('bob', '', ['Member'], [])

    # create two documents, one with Assignee local roles, one without
    folder = self.getOrganisationModule()
    ob1 = folder.newContent(title='Object Title')
    ob1.manage_permission('View', ['Member'], 1)
    ob2 = folder.newContent(title='Object Title')
1737
    ob2_id = ob2.getId()
1738 1739 1740 1741 1742
    ob2.manage_addLocalRoles('bob', ['Assignee'])
    get_transaction().commit()
    self.tic()
    
    # by default bob can see those 2 documents
1743
    self.login('bob')
1744 1745 1746 1747 1748 1749
    ctool = self.getCatalogTool()
    self.assertEquals(2, len(ctool.searchResults(title='Object Title')))
    self.assertEquals(2, ctool.countResults(title='Object Title')[0][0])
    
    # if we specify local_roles= it will only returns documents on with bob has
    # a local roles
1750 1751 1752 1753 1754 1755
    self.assertEquals(0,
                len(ctool.searchResults(title='Object Title',
                                        local_roles='UnexistingRole')))
    self.assertEquals(0,
                len(ctool.searchResults(title='Object Title',
                                        local_roles='Assignor')))
1756
    self.assertEquals(1,
1757 1758
                len(ctool.searchResults(title='Object Title',
                                        local_roles='Assignee')))
1759
    self.assertEquals(1,
1760 1761 1762
                ctool.countResults(title='Object Title',
                                   local_roles='Assignee')[0][0])

1763 1764 1765 1766 1767 1768
    # this also work for searchFolder and countFolder
    self.assertEquals(1, len(folder.searchFolder(title='Object Title',
                                             local_roles='Assignee')))
    self.assertEquals(1, folder.countFolder(title='Object Title',
                                             local_roles='Assignee')[0][0])
    
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
    # and local_roles can be a list, then this a OR (ie. you must have at least
    # one role).
    self.assertEquals(1,
                len(ctool.searchResults(title='Object Title',
                                       local_roles=['Assignee', 'Auditor'])))
    self.assertEquals(1,
                ctool.countResults(title='Object Title',
                                   local_roles=['Assignee', 'Auditor'])[0][0])

    # this list can also be given in ; form, for worklists URL
    self.assertEquals(1,
                len(ctool.searchResults(title='Object Title',
                                       local_roles='Assignee;Auditor')))
    self.assertEquals(1,
                ctool.countResults(title='Object Title',
                                   local_roles='Assignee;Auditor')[0][0])

1786 1787
    #Test if bob can't see object even if Assignee role (without View permission) is defined on object
    ob1.manage_addLocalRoles('bob', ['Assignee'])
1788 1789
    ob1.manage_permission('View', ['Assignor'], 0)
    ob1.reindexObject()
1790 1791
    get_transaction().commit()
    self.tic()
1792 1793 1794 1795 1796 1797
    user = getSecurityManager().getUser()
    self.assertFalse(user.has_permission('View', ob1))
    self.assertTrue(user.has_role('Assignee', ob1))
    result_list = [r.getId() for r in ctool(title='Object Title', local_roles='Assignee')]
    self.assertEquals(1, len(result_list))
    self.assertEquals([ob2_id], result_list)
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
    self.assertEquals(1,
                ctool.countResults(title='Object Title',
                                   local_roles='Assignee')[0][0])

    # this also work for searchFolder and countFolder
    self.assertEquals(1, len(folder.searchFolder(title='Object Title',
                                             local_roles='Assignee')))
    self.assertEquals(1, folder.countFolder(title='Object Title',
                                             local_roles='Assignee')[0][0])

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
  def test_51_SearchWithKeyWords(self, quiet=quiet, run=run_all_test):
    if not run: return
    if not quiet:
      message = 'Test searching with SQL keywords'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()
    and_ = person_module.newContent(portal_type='Person', title='AND')
    or_ = person_module.newContent(portal_type='Person', title='OR')
    like_ = person_module.newContent(portal_type='Person', title='LIKE')
    select_ = person_module.newContent(portal_type='Person', title='SELECT')

    get_transaction().commit()
    self.tic()
    ctool = self.getCatalogTool()
    self.assertEquals([and_], [x.getObject() for x in
                                   ctool(portal_type='Person', title='AND')])

    self.assertEquals([or_], [x.getObject() for x in
                                   ctool(portal_type='Person', title='OR')])

    self.assertEquals([like_], [x.getObject() for x in
                                   ctool(portal_type='Person', title='LIKE')])

    self.assertEquals([select_], [x.getObject() for x in
                                   ctool(portal_type='Person', title='SELECT')])

1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
  def test_52_QueryAndTableAlias(self,quiet=quiet, run=run_all_test):
    """
    Make sure we can use aliases for tables wich will
    be used by related keys. This allow in some particular
    cases to decrease a lot the number of aliases
    """
    if not run: return
    if not quiet:
      message = 'Query And Table Alias'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    org_a = self._makeOrganisation(title='abc',default_address_city='abc')
    module = self.getOrganisationModule()
    module.immediateReindexObject()
    # First try without aliases
    query1 = Query(parent_portal_type="Organisation")
    query2 = Query(grand_parent_portal_type="Organisation Module")
    complex_query = ComplexQuery(query1, query2, operator="AND")
    self.failIfDifferentSet([org_a.getPath() + '/default_address'],
        [x.path for x in self.getCatalogTool()(query=complex_query)])
    # Then try without aliases
    query1 = Query(parent_portal_type="Organisation", 
                   table_alias_list=(("catalog" , "parent"),))
    query2 = Query(grand_parent_portal_type="Organisation Module",
                   table_alias_list=(("catalog" , "parent"), 
                                    ("catalog", "grand_parent")))
    complex_query = ComplexQuery(query1, query2, operator="AND")
    self.failIfDifferentSet([org_a.getPath() + '/default_address'],
        [x.path for x in self.getCatalogTool()(query=complex_query)])
    sql_kw = self.getCatalogTool().buildSQLQuery(query=complex_query)
    # Make sure we have the right list of aliases
    table_alias_list = sql_kw["from_table_list"]
    self.failIfDifferentSet((("catalog","catalog"),
                             ("parent","catalog"),
                             ("grand_parent","catalog")),
                             table_alias_list)
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
    
  def test_53_DateFormat(self, quiet=quiet, run=run_all_test):
    if not run: return
    if not quiet:
      message = 'Date Format'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
    org_a = self._makeOrganisation(title='org_a')
    org_b = self._makeOrganisation(title='org_b')
    sql_connection = self.getSQLConnection()
    # Add a method in order to directly put values we want into
    # the catalog.
    def updateDate(organisation,date):
      uid = organisation.getUid()
      sql = "UPDATE catalog SET modification_date='%s' '\
          'WHERE uid=%s" %\
          (date,uid)
      result = sql_connection.manage_test(sql)
    updateDate(org_a,'2007-01-12 01:02:03')
    updateDate(org_b,'2006-02-24 15:09:06')

    catalog_kw = {'modification_date':{'query':'24/02/2006',
                               'format':'%d/%m/%Y',
                               'type':'date'}}
    self.failIfDifferentSet([org_b.getPath()],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',**catalog_kw)])
    catalog_kw = {'modification_date':{'query':'2007-01-12',
                               'format':'%Y-%m-%d',
                               'type':'date'}}
    self.failIfDifferentSet([org_a.getPath()],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',**catalog_kw)])
    catalog_kw = {'modification_date':{'query':'>31/12/2006',
                               'format':'%d/%m/%Y',
                               'type':'date'}}
    self.failIfDifferentSet([org_a.getPath()],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',**catalog_kw)])
    catalog_kw = {'modification_date':{'query':'2006',
                               'format':'%Y',
                               'type':'date'}}
    self.failIfDifferentSet([org_b.getPath()],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',**catalog_kw)])
    catalog_kw = {'modification_date':{'query':'>2006',
                               'format':'%Y',
                               'type':'date'}}
    self.failIfDifferentSet([org_a.getPath()],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',**catalog_kw)])
1924 1925 1926 1927 1928 1929 1930
    # If the date is an empty string, check that all objects are displayed.
    catalog_kw = {'modification_date':{'query':'',
                               'format':'%d/%m/%Y',
                               'type':'date'}}
    self.failIfDifferentSet([org_a.getPath(), org_b.getPath()],
        [x.path for x in self.getCatalogTool()(
                portal_type='Organisation',**catalog_kw)])
1931

1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
  def test_54_FixIntUid(self, quiet=quiet, run=run_all_test):
    if not run: return
    if not quiet:
      message = 'Test if portal_catalog ensures that uid is long'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
    portal_catalog = self.getCatalogTool()
    portal = self.getPortal()

    module = portal.getDefaultModule('Organisation')
    organisation = module.newContent(portal_type='Organisation',)
    # Ensure that the new uid is long.
    uid = organisation.uid
    self.failUnless(isinstance(uid, long))
    get_transaction().commit()
    self.tic()

    # Ensure that the uid did not change after the indexing.
    self.assertEquals(organisation.uid, uid)

    # Force to convert the uid to int.
    self.uid = int(uid)
    get_transaction().commit()
    self.tic()

    # After the indexing, the uid must be converted to long automatically,
    # and the value must be equivalent.
    self.failUnless(isinstance(uid, long))
    self.assertEquals(organisation.uid, uid)

1962 1963 1964 1965 1966 1967
  def test_55_FloatFormat(self, quiet=quiet, run=run_all_test):
    if not run: return
    if not quiet:
      message = 'Float Format'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)
Jérome Perrin's avatar
Jérome Perrin committed
1968 1969 1970 1971

    catalog_kw = {'uid': {'query': '2 567.54',
                          'format': '1 234.12',
                          'type': 'float'}}
1972 1973 1974
    sql_src = self.getCatalogTool().buildSQLQuery(**catalog_kw)['where_expression']
    self.assertTrue("TRUNCATE(catalog.uid,2) = '2567.54'" in sql_src or \
                    'TRUNCATE(`catalog`.`uid`, 2) = 2567.54' in sql_src, sql_src)
1975

1976 1977
  @skip('Regression portal_ids must be delete of catalog')
  def test_56_CreateUidDuringClearCatalog(self, quiet=quiet,run=run_all_test):
1978 1979 1980 1981 1982 1983 1984
    """
      Create a script in the catalog to generate a uid list
      Check the creation some objects, or activities, during a clear
    """
    # Add a script to create uid list
    catalog = self.getCatalogTool().getSQLCatalog()
    script_id = 'z0_zCreateUid'
1985 1986 1987
    script_content = "context.getPortalObject().portal_ids.generateNewLengthIdList(id_group='text_uid')"
    script = createZODBPythonScript(catalog, script_id,
                          '*args,**kw', script_content)
1988 1989 1990 1991 1992 1993 1994 1995
    sql_clear_catalog = list(catalog.sql_clear_catalog)
    sql_clear_catalog.append(script_id)
    sql_clear_catalog.sort()
    catalog.sql_clear_catalog = tuple(sql_clear_catalog)
    # launch the sql_clear_catalog with the script after the drop tables and
    # before the recreate tables of catalog
    catalog.manage_catalogClear()

1996 1997
  def test_SearchOnOwner(self, quiet=quiet, run=run_all_test):
    if not run: return  
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
    # owner= can be used a search key in the catalog to have all documents for
    # a specific owner and on which he have the View permission.
    obj = self._makeOrganisation(title='The Document')
    obj2 = self._makeOrganisation(title='The Document')
    obj2.manage_permission('View', [], 0)
    obj2.reindexObject()
    get_transaction().commit()
    self.tic()
    ctool = self.getCatalogTool()
    self.assertEquals([obj], [x.getObject() for x in
                                   ctool(title='The Document',
                                         owner=self.username)])
    self.assertEquals([], [x.getObject() for x in
                                   ctool(title='The Document',
                                         owner='somebody else')])

Jérome Perrin's avatar
Jérome Perrin committed
2014

Ivan Tyagov's avatar
Ivan Tyagov committed
2015 2016
  def test_SubDocumentsSecurityIndexing(self, quiet=quiet, run=run_all_test):
    if not run: return    
2017 2018 2019 2020 2021 2022 2023 2024 2025
    # make sure indexing of security on sub-documents works as expected
    uf = self.getPortal().acl_users
    uf._doAddUser('bob', '', ['Member'], [])
    obj = self._makeOrganisation(title='The Document')
    obj2 = obj.newContent(portal_type='Bank Account')
    obj2.manage_addLocalRoles('bob', ['Auditor'])
    get_transaction().commit()
    self.tic()

2026
    self.login('bob')
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
    self.assertEquals([obj2], [x.getObject() for x in
                               obj.searchFolder(portal_type='Bank Account')])
    # now if we pass the bank account in deleted state, it's no longer returned
    # by searchFolder.
    # This will work as long as Bank Account are associated to a workflow that
    # allow deletion.
    obj2.delete()
    get_transaction().commit()
    self.tic()
    self.assertEquals([], [x.getObject() for x in
                           obj.searchFolder(portal_type='Bank Account')])

2039
  @todo_erp5
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
  def test_SubDocumentsWithAcquireLocalRoleSecurityIndexing(
                                   self, quiet=quiet, run=run_all_test):
    if not run: return    
    # Check that sub object indexation is compatible with ZODB settings
    # when the sub object acquires the parent local roles
    perm = 'View'

    # Create some users
    logout = self.logout
    user1 = 'local_foo_1'
    user2 = 'local_bar_1'
    uf = self.getPortal().acl_users
    uf._doAddUser(user1, user1, ['Member', ], [])
    uf._doAddUser(user2, user2, ['Member', ], [])

    container_portal_type = 'Organisation'
    # Create a container, define a local role, and set view permission
    folder = self.getOrganisationModule()

    # user1 should be auditor on container
    # user2 should be assignor on subdocument
    container = folder.newContent(portal_type=container_portal_type)
    container.manage_setLocalRoles(user1, ['Auditor'])
#     container.manage_setLocalRoles(user2, [])
    container.manage_permission(perm, ['Owner', 'Auditor', 'Assignor'], 0)

    # By default, local roles are acquired from container for Email portal type
    object_portal_type = 'Email'
    obj = container.newContent(portal_type=object_portal_type)
    # Acquire permission from parent
    obj.manage_permission(perm, [], 1)
    obj.manage_setLocalRoles(user2, ['Assignor'])

    obj.reindexObject()
    get_transaction().commit()
    self.tic()

    logout()
2078
    self.login(user1)
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
    result = obj.portal_catalog(portal_type=object_portal_type)
    self.assertSameSet([obj, ], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=object_portal_type, 
                                local_roles='Owner')
    self.assertSameSet([], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=object_portal_type, 
                                local_roles='Assignor')
    self.assertSameSet([], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=object_portal_type, 
                                local_roles='Auditor')
    self.assertSameSet([obj], [x.getObject() for x in result])

    logout()
2092
    self.login(user2)
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
    result = obj.portal_catalog(portal_type=object_portal_type)
    self.assertSameSet([obj, ], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=object_portal_type, 
                                local_roles='Owner')
    self.assertSameSet([], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=object_portal_type, 
                                local_roles='Assignor')
    self.assertSameSet([obj], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=object_portal_type, 
                                local_roles='Auditor')
    self.assertSameSet([], [x.getObject() for x in result])

2105
  def test_60_ViewableOwnerIndexing(self, quiet=quiet, run=run_all_test):
2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
    if not run: 
      return

    logout = self.logout
    uf = self.getPortal().acl_users
    uf._doAddUser('super_owner', '', ['Member', 'Author', 'Assignee'], [])
    uf._doAddUser('little_owner', '', ['Member', 'Author'], [])

    perm = 'View'
    folder = self.getOrganisationModule()
    portal_type = 'Organisation'
    sub_portal_type_id = 'Address'
    sub_portal_type = self.getPortal().portal_types._getOb(sub_portal_type_id)

    sql_connection = self.getSQLConnection()
2121
    sql = 'select viewable_owner as owner from catalog where uid=%s'
2122

2123
    self.login('super_owner')
2124 2125 2126 2127 2128 2129 2130

    # Check that Owner is not catalogued if he can't view the object
    obj = folder.newContent(portal_type='Organisation')
    obj.manage_permission(perm, [], 0)
    get_transaction().commit()
    self.tic()
    result = sql_connection.manage_test(sql % obj.getUid())
2131
    self.assertSameSet([''], [x.owner for x in result])
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147

    # Check that Owner is catalogued when he can view the object
    obj = folder.newContent(portal_type='Organisation')
    obj.manage_permission(perm, ['Owner'], 0)
    get_transaction().commit()
    self.tic()
    result = sql_connection.manage_test(sql % obj.getUid())
    self.assertSameSet(['super_owner'], [x.owner for x in result])

    # Check that Owner is not catalogued when he can view the 
    # object because he has another role
    obj = folder.newContent(portal_type='Organisation')
    obj.manage_permission(perm, ['Assignee'], 0)
    get_transaction().commit()
    self.tic()
    result = sql_connection.manage_test(sql % obj.getUid())
2148
    self.assertSameSet([''], [x.owner for x in result])
2149 2150 2151 2152 2153 2154

    # Check that Owner is not catalogued when he can't view the 
    # object and when the portal type does not acquire the local roles.
    sub_portal_type.acquire_local_roles = False
    self.portal.portal_caches.clearAllCache()
    logout()
2155
    self.login('super_owner')
2156 2157 2158
    obj = folder.newContent(portal_type='Organisation')
    obj.manage_permission(perm, ['Owner'], 0)
    logout()
2159
    self.login('little_owner')
2160 2161 2162 2163 2164
    sub_obj = obj.newContent(portal_type='Address')
    sub_obj.manage_permission(perm, [], 0)
    get_transaction().commit()
    self.tic()
    result = sql_connection.manage_test(sql % sub_obj.getUid())
2165
    self.assertSameSet([''], [x.owner for x in result])
2166 2167 2168 2169 2170 2171

    # Check that Owner is catalogued when he can view the 
    # object and when the portal type does not acquire the local roles.
    sub_portal_type.acquire_local_roles = False
    self.portal.portal_caches.clearAllCache()
    logout()
2172
    self.login('super_owner')
2173 2174 2175
    obj = folder.newContent(portal_type='Organisation')
    obj.manage_permission(perm, ['Owner'], 0)
    logout()
2176
    self.login('little_owner')
2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
    sub_obj = obj.newContent(portal_type='Address')
    sub_obj.manage_permission(perm, ['Owner'], 0)
    get_transaction().commit()
    self.tic()
    result = sql_connection.manage_test(sql % sub_obj.getUid())
    self.assertSameSet(['little_owner'], [x.owner for x in result])

    # Check that Owner is catalogued when he can view the 
    # object because permissions are acquired and when the portal type does not
    # acquire the local roles.
    sub_portal_type.acquire_local_roles = False
    self.portal.portal_caches.clearAllCache()
    logout()
2190
    self.login('super_owner')
2191 2192 2193
    obj = folder.newContent(portal_type='Organisation')
    obj.manage_permission(perm, ['Owner'], 0)
    logout()
2194
    self.login('little_owner')
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
    sub_obj = obj.newContent(portal_type='Address')
    sub_obj.manage_permission(perm, [], 1)
    get_transaction().commit()
    self.tic()
    result = sql_connection.manage_test(sql % sub_obj.getUid())
    self.assertSameSet(['little_owner'], [x.owner for x in result])

    # Check that Owner is not catalogued when he can't view the 
    # object and when the portal type acquires the local roles.
    sub_portal_type.acquire_local_roles = True
    self.portal.portal_caches.clearAllCache()
    logout()
2207
    self.login('super_owner')
2208 2209 2210
    obj = folder.newContent(portal_type='Organisation')
    obj.manage_permission(perm, ['Owner'], 0)
    logout()
2211
    self.login('little_owner')
2212 2213 2214 2215 2216
    sub_obj = obj.newContent(portal_type='Address')
    sub_obj.manage_permission(perm, [], 0)
    get_transaction().commit()
    self.tic()
    result = sql_connection.manage_test(sql % sub_obj.getUid())
2217
    self.assertSameSet([''], [x.owner for x in result])
2218 2219 2220 2221 2222 2223

    # Check that Owner is catalogued when he can view the 
    # object and when the portal type acquires the local roles.
    sub_portal_type.acquire_local_roles = True
    self.portal.portal_caches.clearAllCache()
    logout()
2224
    self.login('super_owner')
2225 2226 2227
    obj = folder.newContent(portal_type='Organisation')
    obj.manage_permission(perm, ['Owner'], 0)
    logout()
2228
    self.login('little_owner')
2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241
    sub_obj = obj.newContent(portal_type='Address')
    sub_obj.manage_permission(perm, ['Owner'], 0)
    get_transaction().commit()
    self.tic()
    result = sql_connection.manage_test(sql % sub_obj.getUid())
    self.assertSameSet(['little_owner'], [x.owner for x in result])

    # Check that Owner is catalogued when he can view the 
    # object because permissions are acquired and when the portal type
    # acquires the local roles.
    sub_portal_type.acquire_local_roles = True
    self.portal.portal_caches.clearAllCache()
    logout()
2242
    self.login('super_owner')
2243 2244 2245
    obj = folder.newContent(portal_type='Organisation')
    obj.manage_permission(perm, ['Owner'], 0)
    logout()
2246
    self.login('little_owner')
2247 2248 2249 2250 2251 2252 2253
    sub_obj = obj.newContent(portal_type='Address')
    sub_obj.manage_permission(perm, [], 1)
    get_transaction().commit()
    self.tic()
    result = sql_connection.manage_test(sql % sub_obj.getUid())
    self.assertSameSet(['little_owner'], [x.owner for x in result])

2254 2255
  def test_ExactMatchSearch(self, quiet=quiet, run=run_all_test):
    if not run: return
2256 2257 2258 2259 2260 2261
    # test exact match search with queries
    doc = self._makeOrganisation(title='Foo%')
    other_doc = self._makeOrganisation(title='FooBar')
    ctool = self.getCatalogTool()

    # by default, % in catalog search is a wildcard:
2262 2263
    self.assertSameSet([doc, other_doc], [x.getObject() for x in 
        ctool(portal_type='Organisation', title='Foo%')])
2264 2265 2266 2267
    # ... but you can force searches with an exact match key
    self.assertEquals([doc], [x.getObject() for x in
       ctool(portal_type='Organisation', title=dict(query='Foo%',
                                                    key='ExactMatch'))])
2268

2269 2270
  def test_KeywordSearch(self, quiet=quiet, run=run_all_test):
    if not run: return  
2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
    # test keyword search with queries
    doc = self._makeOrganisation(description='Foo')
    other_doc = self._makeOrganisation(description='Foobar')
    ctool = self.getCatalogTool()

    # description is not a keyword by default. (This might change in the
    # future, in this case, this test have to be updated)
    self.assertSameSet([doc], [x.getObject() for x in 
        ctool(portal_type='Organisation', description='Foo')])
    self.assertEquals(set([doc, other_doc]), set([x.getObject() for x in
      ctool(portal_type='Organisation', description=dict(query='Foo',
                                                         key='Keyword'))]))


2285 2286
  def test_ignore_empty_string(self, quiet=quiet, run=run_all_test):
    if not run: return  
2287
    # ERP5Catalog ignore empty strings by default
2288 2289
    doc_with_description = self._makeOrganisation(description='X')
    doc_with_empty_description = self._makeOrganisation(description='')
2290 2291 2292 2293 2294
    ctool = self.getCatalogTool()
    def searchResults(**kw):
      kw['portal_type'] = 'Organisation'
      return set([x.getObject() for x in ctool.searchResults(**kw)])
    
2295 2296 2297
    # description='' is ignored
    self.assertEquals(set([doc_with_empty_description, doc_with_description]),
                      searchResults(description=''))
2298
    # unless we exlicitly say we don't want to ignore empty strings
2299 2300
    self.assertEquals(set([doc_with_empty_description]),
                      searchResults(ignore_empty_string=0, description=''))
2301 2302 2303

  def test_ignore_empty_string_related_key(self):
    # ERP5Catalog ignore empty strings by default, also on related keys
2304 2305 2306 2307 2308
    region_with_empty_description = self.portal.portal_categories.region.newContent(
                                        portal_type='Category', description='')
    doc_with_empty_region_description = self._makeOrganisation(
                            region_value=region_with_empty_description)
    doc_without_region = self._makeOrganisation()
2309 2310 2311 2312 2313
    ctool = self.getCatalogTool()
    def searchResults(**kw):
      kw['portal_type'] = 'Organisation'
      return set([x.getObject() for x in ctool.searchResults(**kw)])
    
2314 2315 2316 2317
    self.assertEquals(set([doc_with_empty_region_description, doc_without_region]),
                      searchResults(region_description=''))
    self.assertEquals(set([doc_with_empty_region_description]),
        searchResults(ignore_empty_string=0, region_description=''))
2318

Yusei Tahara's avatar
Yusei Tahara committed
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
  def test_complex_query(self, quiet=quiet, run=run_all_test):
    # Make sure that complex query works on real environment.
    if not run: return

    catalog = self.getCatalogTool()
    person_module = self.getPersonModule()

    # Add categories
    portal_category = self.getCategoryTool()
    africa = portal_category.region.newContent(id='africa')
    asia = portal_category.region.newContent(id='asia')
    europe = portal_category.region.newContent(id='europe')

    # A from Africa
    person_module.newContent(id='A', first_name='A', last_name='ERP5',
                             region='africa')

    # B from Asia
    person_module.newContent(id='B', first_name='B', last_name='ZOPE',
                             region='asia')

    # C from Europe
    person_module.newContent(id='C', first_name='C', last_name='PYTHON',
                             region='europe')

    # D from ????
    person_module.newContent(id='D', first_name='D', last_name='ERP5')

    get_transaction().commit()
    self.tic()

    # simple query
    query = Query(portal_type='Person')
    self.assertEqual(len(catalog(query=query)), 4)

    # complex query
    query = ComplexQuery(Query(portal_type='Person'),
                         Query(region_uid=asia.getUid()),
                         operator='AND')
    self.assertEqual(len(catalog(query=query)), 1)

    # complex query
    query = ComplexQuery(Query(portal_type='Person'),
                         Query(region_uid=(africa.getUid(), asia.getUid())),
                         operator='AND')
    self.assertEqual(len(catalog(query=query)), 2)

    # more complex query
    query_find_european = ComplexQuery(Query(portal_type='Person'),
                                       Query(region_uid=europe.getUid()),
                                       operator='AND')
    self.assertEqual(len(catalog(query=query_find_european)), 1)
    
    query_find_name_erp5 = ComplexQuery(Query(portal_type='Person'),
                                        Query(title='%ERP5'),
                                        operator='AND')
    self.assertEqual(len(catalog(query=query_find_name_erp5)), 2)

Yusuke Muraoka's avatar
Yusuke Muraoka committed
2377
    self.assertRaises(NotImplementedError, ComplexQuery, query_find_european, query_find_name_erp5, operator='OR')
2378
 
2379 2380 2381 2382
  def test_check_security_table_content(self, quiet=quiet, run=run_all_test):
    sql_connection = self.getSQLConnection()
    portal = self.getPortalObject()
    portal_types = portal.portal_types
2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393

    uf = self.getPortal().acl_users
    uf._doAddUser('foo', 'foo', ['Member', ], [])
    uf._doAddUser('ERP5TypeTestCase', 'ERP5TypeTestCase', ['Member', ], [])
    get_transaction().commit()
    portal_catalog = self.getCatalogTool()
    portal_catalog.manage_catalogClear()
    self.getPortal().ERP5Site_reindexAll()
    get_transaction().commit()
    self.tic()

2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 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 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481
    
    # Person stuff
    person_module = portal.person_module
    person = 'Person'
    person_portal_type = portal_types._getOb(person)
    person_portal_type.acquire_local_roles = False
    # Organisation stuff
    organisation_module = portal.organisation_module
    organisation = 'Organisation'
    organisation_portal_type = portal_types._getOb(organisation)
    organisation_portal_type.acquire_local_roles = True
    
    self.portal.portal_caches.clearAllCache()
    
    def newContent(container, portal_type, acquire_view_permission, view_role_list, local_role_dict):
      document = container.newContent(portal_type=portal_type)
      document.manage_permission('View', roles=view_role_list, acquire=acquire_view_permission)
      for user, role_list in local_role_dict.iteritems():
        document.manage_setLocalRoles(userid=user, roles=role_list)
      return document

    # Create documents for all combinations
    object_dict = {}

    def getObjectDictKey():
      """
        Get values from enclosing environment.
        Uggly, but makes calls less verbose.
      """
      return (portal_type, acquire_view_permission,
              tuple(view_role_list),
              tuple([(x, tuple(y))
                     for x, y in local_role_dict.iteritems()])
             )
    
    for container, portal_type in ((person_module, person),
                                   (organisation_module, organisation)):
      for acquire_view_permission in (True, False):
        for view_role_list in ([],
                               ['Owner'],
                               ['Owner', 'Author'],
                               ['Author']):
          for local_role_dict in ({},
                                  {'foo': ['Owner']},
                                  {'foo': ['Author']},
                                  {'foo': ['Owner'],
                                   'bar': ['Author']},
                                  {'foo': ['Owner', 'Author'],
                                   'bar': ['Whatever']},
                                  {'foo': ['Owner', 'Author'],
                                   'bar': ['Whatever', 'Author']}):
            object_dict[getObjectDictKey()] = \
              newContent(container, portal_type, acquire_view_permission,
                         view_role_list, local_role_dict)
    get_transaction().commit()
    self.tic()

    def query(sql):
      result = sql_connection.manage_test(sql)
      return result.dictionaries()
    
    # Check that there is no Owner role in security table
    # Note: this tests *all* lines from security table. Not just the ones
    # inserted in this test.
    result = query('SELECT * FROM roles_and_users WHERE allowedRolesAndUsers LIKE "%:Owner"')
    self.assertEqual(len(result), 0, repr(result))
    
    # Check that for each "user:<user>:<role>" line there is exactly one
    # "user:<user>" line with the same uid.
    # Also, check that for each "user:<user>" there is at least one
    # "user:<user>:<role>" line with same uid.
    # Also, check if "user:..." lines are well-formed.
    # Note: this tests *all* lines from security table. Not just the ones
    # inserted in this test.
    line_list = query('SELECT * FROM roles_and_users WHERE allowedRolesAndUsers LIKE "user:%"')
    for line in line_list:
      role_list = line['allowedRolesAndUsers'].split(':')
      uid = line['uid']
      if len(role_list) == 3:
        stripped_role = ':'.join(role_list[:-1])
        result = query('SELECT * FROM roles_and_users WHERE allowedRolesAndUsers = "%s" AND uid = %i' % (stripped_role, uid) )
        self.assertEqual(len(result), 1, repr(result))
      elif len(role_list) == 2:
        result = query('SELECT * FROM roles_and_users WHERE allowedRolesAndUsers LIKE "%s:%%" AND uid = %i' % (line['allowedRolesAndUsers'], uid) )
        self.assertNotEqual(len(result), 0, 'No line found for allowedRolesAndUsers=%r and uid=%i' % (line['allowedRolesAndUsers'], uid))
      else:
        raise Exception, 'Malformed allowedRolesAndUsers value: %r' % (line['allowedRolesAndUsers'], )

2482 2483
    # Check that object that 'bar' can view because of 'Author' role can *not*
    # be found when searching for his other 'Whatever' role.
2484 2485 2486 2487 2488 2489 2490 2491 2492
    local_role_dict = {'foo': ['Owner', 'Author'],
                       'bar': ['Whatever', 'Author']}
    for container, portal_type in ((person_module, person),
                                   (organisation_module, organisation)):
      for acquire_view_permission in (True, False):
        for view_role_list in (['Owner', 'Author'],
                               ['Author']):
          object = object_dict[getObjectDictKey()]
          result = query('SELECT roles_and_users.uid FROM roles_and_users, catalog WHERE roles_and_users.uid = catalog.security_uid AND catalog.uid = %i AND allowedRolesAndUsers = "user:bar:Whatever"' % (object.uid, ))
2493
          self.assertEqual(len(result), 0, '%r: len(%r) != 0' % (getObjectDictKey(), result))
2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506

    # Check that no 'bar' role are in security table when 'foo' has local
    # roles allowing him to view an object but 'bar' can't.
    local_role_dict = {'foo': ['Owner', 'Author'],
                       'bar': ['Whatever']}
    for container, portal_type in ((person_module, person),
                                   (organisation_module, organisation)):
      for acquire_view_permission in (True, False):
        for view_role_list in (['Owner', 'Author'],
                               ['Author']):
          object = object_dict[getObjectDictKey()]
          result = query('SELECT roles_and_users.uid, roles_and_users.allowedRolesAndUsers FROM roles_and_users, catalog WHERE roles_and_users.uid = catalog.security_uid AND catalog.uid = %i AND roles_and_users.allowedRolesAndUsers LIKE "user:bar%%"' % (object.uid, ))
          self.assertEqual(len(result), 0, '%r: len(%r) != 0' % (getObjectDictKey(), result))
2507

2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
  def test_RealOwnerIndexing(self, quiet=quiet, run=run_all_test):
    if not run: 
      return

    logout = self.logout
    user1 = 'local_foo'
    user2 = 'local_bar'
    uf = self.getPortal().acl_users
    uf._doAddUser(user1, user1, ['Member', ], [])
    uf._doAddUser(user2, user2, ['Member', ], [])

    perm = 'View'
    folder = self.getOrganisationModule()
    folder.manage_setLocalRoles(user1, ['Author', 'Auditor'])
    folder.manage_setLocalRoles(user2, ['Author', 'Auditor'])
    portal_type = 'Organisation'

    sql_connection = self.getSQLConnection()

2527
    self.login(user2)
2528 2529 2530 2531
    obj2 = folder.newContent(portal_type=portal_type)
    obj2.manage_setLocalRoles(user1, ['Auditor'])
    obj2.manage_permission(perm, ['Owner', 'Auditor'], 0)

2532
    self.login(user1)
2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698

    obj = folder.newContent(portal_type=portal_type)
    obj.manage_setLocalRoles(user1, ['Owner', 'Auditor'])

    # Check that nothing is returned when user can not view the object
    obj.manage_permission(perm, [], 0)
    obj.reindexObject()
    get_transaction().commit()
    self.tic()
    result = obj.portal_catalog(portal_type=portal_type)
    self.assertSameSet([obj2, ], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=portal_type, local_roles='Owner')
    self.assertSameSet([], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=portal_type, local_roles='Auditor')
    self.assertSameSet([obj2, ], [x.getObject() for x in result])

    # Check that object is returned when he can view the object
    obj.manage_permission(perm, ['Auditor'], 0)
    obj.reindexObject()
    get_transaction().commit()
    self.tic()
    result = obj.portal_catalog(portal_type=portal_type)
    self.assertSameSet([obj2, obj], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=portal_type, local_roles='Owner')
    self.assertSameSet([], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=portal_type, local_roles='Auditor')
    self.assertSameSet([obj2, obj], [x.getObject() for x in result])

    # Check that object is returned when he can view the object
    obj.manage_permission(perm, ['Owner'], 0)
    obj.reindexObject()
    get_transaction().commit()
    self.tic()
    result = obj.portal_catalog(portal_type=portal_type)
    self.assertSameSet([obj2, obj], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=portal_type, local_roles='Owner')
    self.assertSameSet([obj], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=portal_type, local_roles='Auditor')
    self.assertSameSet([obj2, ], [x.getObject() for x in result])

    # Add a new table to the catalog
    sql_catalog = self.portal.portal_catalog.getSQLCatalog()

    local_roles_table = "test_local_roles"

    create_local_role_table_sql = """
CREATE TABLE `%s` (
  `uid` BIGINT UNSIGNED NOT NULL,
  `owner_reference` varchar(32) NOT NULL default '',
  PRIMARY KEY  (`uid`),
  KEY `version` (`owner_reference`)
) TYPE=InnoDB;
    """ % local_roles_table
    sql_catalog.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod(
          id = 'z_create_%s' % local_roles_table,
          title = '',
          arguments = "",
          connection_id = 'erp5_sql_connection',
          template = create_local_role_table_sql)

    drop_local_role_table_sql = """
DROP TABLE IF EXISTS %s
    """ % local_roles_table
    sql_catalog.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod(
          id = 'z0_drop_%s' % local_roles_table,
          title = '',
          arguments = "",
          connection_id = 'erp5_sql_connection',
          template = drop_local_role_table_sql)

    catalog_local_role_sql = """
REPLACE INTO
  %s
VALUES
<dtml-in prefix="loop" expr="_.range(_.len(uid))">
(
  <dtml-sqlvar expr="uid[loop_item]" type="int">,  
  <dtml-sqlvar expr="Base_getOwnerId[loop_item]" type="string" optional>
)
<dtml-if sequence-end>
<dtml-else>
,
</dtml-if>
</dtml-in>
    """ % local_roles_table
    sql_catalog.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod(
          id = 'z_catalog_%s_list' % local_roles_table,
          title = '',
          connection_id = 'erp5_sql_connection',
          arguments = "\n".join(['uid',
                                 'Base_getOwnerId']),
          template = catalog_local_role_sql)

    get_transaction().commit()
    current_sql_catalog_object_list = sql_catalog.sql_catalog_object_list
    sql_catalog.sql_catalog_object_list = \
      current_sql_catalog_object_list + \
         ('z_catalog_%s_list' % local_roles_table,)
    current_sql_clear_catalog = sql_catalog.sql_clear_catalog
    sql_catalog.sql_clear_catalog = \
      current_sql_clear_catalog + \
         ('z0_drop_%s' % local_roles_table, 'z_create_%s' % local_roles_table)
    current_sql_catalog_local_role_keys = \
          sql_catalog.sql_catalog_local_role_keys
    sql_catalog.sql_catalog_local_role_keys = ('Owner | %s.owner_reference' % \
       local_roles_table,)
    current_sql_search_tables = sql_catalog.sql_search_tables
    sql_catalog.sql_search_tables = sql_catalog.sql_search_tables + \
        [local_roles_table]
    get_transaction().commit()

    try:
      # Clear catalog
      portal_catalog = self.getCatalogTool()
      portal_catalog.manage_catalogClear()
      get_transaction().commit()
      self.portal.portal_caches.clearAllCache()
      get_transaction().commit()
      obj2.reindexObject()

      # Check that nothing is returned when user can not view the object
      obj.manage_permission(perm, [], 0)
      obj.reindexObject()
      get_transaction().commit()
      self.tic()
      result = obj.portal_catalog(portal_type=portal_type)
      self.assertSameSet([obj2, ], [x.getObject() for x in result])
      method = obj.portal_catalog
      result = obj.portal_catalog(portal_type=portal_type, local_roles='Owner')
      self.assertSameSet([], [x.getObject() for x in result])
      result = obj.portal_catalog(portal_type=portal_type, local_roles='Auditor')
      self.assertSameSet([obj2, ], [x.getObject() for x in result])

      # Check that object is returned when he can view the object
      obj.manage_permission(perm, ['Auditor'], 0)
      obj.reindexObject()
      get_transaction().commit()
      self.tic()
      result = obj.portal_catalog(portal_type=portal_type)
      self.assertSameSet([obj2, obj], [x.getObject() for x in result])
      result = obj.portal_catalog(portal_type=portal_type, local_roles='Owner')
      self.assertSameSet([obj], [x.getObject() for x in result])
      result = obj.portal_catalog(portal_type=portal_type, local_roles='Auditor')
      self.assertSameSet([obj2, obj], [x.getObject() for x in result])

      # Check that object is returned when he can view the object
      obj.manage_permission(perm, ['Owner'], 0)
      obj.reindexObject()
      get_transaction().commit()
      self.tic()
      result = obj.portal_catalog(portal_type=portal_type)
      self.assertSameSet([obj2, obj], [x.getObject() for x in result])
      result = obj.portal_catalog(portal_type=portal_type, local_roles='Owner')
      self.assertSameSet([obj], [x.getObject() for x in result])
      result = obj.portal_catalog(portal_type=portal_type, local_roles='Auditor')
      self.assertSameSet([obj2, ], [x.getObject() for x in result])
    finally:
      sql_catalog.sql_catalog_object_list = \
        current_sql_catalog_object_list
      sql_catalog.sql_clear_catalog = \
        current_sql_clear_catalog
      sql_catalog.sql_catalog_local_role_keys = \
          current_sql_catalog_local_role_keys
      sql_catalog.sql_search_tables = current_sql_search_tables
      get_transaction().commit()

2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717
  def test_MonoValueAssigneeIndexing(self, quiet=quiet, run=run_all_test):
    if not run: 
      return

    logout = self.logout
    user1 = 'local_foo'
    user2 = 'local_bar'
    uf = self.getPortal().acl_users
    uf._doAddUser(user1, user1, ['Member', ], [])
    uf._doAddUser(user2, user2, ['Member', ], [])

    perm = 'View'
    folder = self.getOrganisationModule()
    folder.manage_setLocalRoles(user1, ['Author', 'Auditor'])
    folder.manage_setLocalRoles(user2, ['Author', 'Auditor'])
    portal_type = 'Organisation'

    sql_connection = self.getSQLConnection()

2718
    self.login(user2)
2719 2720 2721 2722
    obj2 = folder.newContent(portal_type=portal_type)
    obj2.manage_setLocalRoles(user1, ['Auditor'])
    obj2.manage_permission(perm, ['Assignee', 'Auditor'], 0)

2723
    self.login(user1)
2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925

    obj = folder.newContent(portal_type=portal_type)
    obj.manage_setLocalRoles(user1, ['Assignee', 'Auditor'])

    # Check that nothing is returned when user can not view the object
    obj.manage_permission(perm, [], 0)
    obj.reindexObject()
    get_transaction().commit()
    self.tic()
    result = obj.portal_catalog(portal_type=portal_type)
    self.assertSameSet([obj2, ], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=portal_type, local_roles='Assignee')
    self.assertSameSet([], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=portal_type, local_roles='Auditor')
    self.assertSameSet([obj2, ], [x.getObject() for x in result])

    # Check that object is returned when he can view the object
    obj.manage_permission(perm, ['Auditor'], 0)
    obj.reindexObject()
    get_transaction().commit()
    self.tic()
    result = obj.portal_catalog(portal_type=portal_type)
    self.assertSameSet([obj2, obj], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=portal_type, local_roles='Assignee')
    self.assertSameSet([], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=portal_type, local_roles='Auditor')
    self.assertSameSet([obj2, obj], [x.getObject() for x in result])

    # Check that object is returned when he can view the object
    obj.manage_permission(perm, ['Assignee'], 0)
    obj.reindexObject()
    get_transaction().commit()
    self.tic()
    result = obj.portal_catalog(portal_type=portal_type)
    self.assertSameSet([obj2, obj], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=portal_type, local_roles='Assignee')
    self.assertSameSet([obj], [x.getObject() for x in result])
    result = obj.portal_catalog(portal_type=portal_type, local_roles='Auditor')
    self.assertSameSet([obj2, ], [x.getObject() for x in result])

    # Add a new table to the catalog
    sql_catalog = self.portal.portal_catalog.getSQLCatalog()

    local_roles_table = "test_assignee_local_roles"

    create_local_role_table_sql = """
CREATE TABLE `%s` (
  `uid` BIGINT UNSIGNED NOT NULL,
  `assignee_reference` varchar(32) NOT NULL default '',
  `viewable_assignee_reference` varchar(32) NOT NULL default '',
  PRIMARY KEY  (`uid`),
  KEY `assignee_reference` (`assignee_reference`),
  KEY `viewable_assignee_reference` (`viewable_assignee_reference`)
) TYPE=InnoDB;
    """ % local_roles_table
    sql_catalog.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod(
          id = 'z_create_%s' % local_roles_table,
          title = '',
          arguments = "",
          connection_id = 'erp5_sql_connection',
          template = create_local_role_table_sql)

    drop_local_role_table_sql = """
DROP TABLE IF EXISTS %s
    """ % local_roles_table
    sql_catalog.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod(
          id = 'z0_drop_%s' % local_roles_table,
          title = '',
          arguments = "",
          connection_id = 'erp5_sql_connection',
          template = drop_local_role_table_sql)

    catalog_local_role_sql = """
REPLACE INTO
  %s
VALUES
<dtml-in prefix="loop" expr="_.range(_.len(uid))">
(
  <dtml-sqlvar expr="uid[loop_item]" type="int">,  
  <dtml-sqlvar expr="getAssignee[loop_item] or ''" type="string" optional>,
  <dtml-sqlvar expr="getViewPermissionAssignee[loop_item] or ''" type="string" optional>
)
<dtml-if sequence-end>
<dtml-else>
,
</dtml-if>
</dtml-in>
    """ % local_roles_table
    sql_catalog.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod(
          id = 'z_catalog_%s_list' % local_roles_table,
          title = '',
          connection_id = 'erp5_sql_connection',
          arguments = "\n".join(['uid',
                                 'getAssignee',
                                 'getViewPermissionAssignee']),
          template = catalog_local_role_sql)

    get_transaction().commit()
    current_sql_catalog_object_list = sql_catalog.sql_catalog_object_list
    sql_catalog.sql_catalog_object_list = \
      current_sql_catalog_object_list + \
         ('z_catalog_%s_list' % local_roles_table,)
    current_sql_clear_catalog = sql_catalog.sql_clear_catalog
    sql_catalog.sql_clear_catalog = \
      current_sql_clear_catalog + \
         ('z0_drop_%s' % local_roles_table, 'z_create_%s' % local_roles_table)
    current_sql_catalog_local_role_keys = \
          sql_catalog.sql_catalog_local_role_keys
    sql_catalog.sql_catalog_local_role_keys = ('Assignee | %s.assignee_reference' % \
       local_roles_table,)

    current_sql_catalog_role_keys = \
          sql_catalog.sql_catalog_role_keys
    sql_catalog.sql_catalog_role_keys = (
        'Assignee | %s.viewable_assignee_reference' % \
       local_roles_table,)

    current_sql_search_tables = sql_catalog.sql_search_tables
    sql_catalog.sql_search_tables = sql_catalog.sql_search_tables + \
        [local_roles_table]
    get_transaction().commit()

    try:
      # Clear catalog
      portal_catalog = self.getCatalogTool()
      portal_catalog.manage_catalogClear()
      get_transaction().commit()
      self.portal.portal_caches.clearAllCache()
      get_transaction().commit()
      obj2.reindexObject()

      # Check that nothing is returned when user can not view the object
      obj.manage_permission(perm, [], 0)
      obj.reindexObject()
      get_transaction().commit()
      self.tic()
      result = obj.portal_catalog(portal_type=portal_type)
      self.assertSameSet([obj2, ], [x.getObject() for x in result])
      method = obj.portal_catalog
      result = obj.portal_catalog(portal_type=portal_type, local_roles='Assignee')
      self.assertSameSet([], [x.getObject() for x in result])
      result = obj.portal_catalog(portal_type=portal_type, local_roles='Auditor')
      self.assertSameSet([obj2, ], [x.getObject() for x in result])

      # Check that object is returned when he can view the object
      obj.manage_permission(perm, ['Auditor'], 0)
      obj.reindexObject()
      get_transaction().commit()
      self.tic()
      result = obj.portal_catalog(portal_type=portal_type)
      self.assertSameSet([obj2, obj], [x.getObject() for x in result])
      result = obj.portal_catalog(portal_type=portal_type, local_roles='Assignee')
      self.assertSameSet([obj], [x.getObject() for x in result])
      result = obj.portal_catalog(portal_type=portal_type, local_roles='Auditor')
      self.assertSameSet([obj2, obj], [x.getObject() for x in result])

      # Check that object is returned when he can view the object
      obj.manage_permission(perm, ['Assignee'], 0)
      obj.reindexObject()
      get_transaction().commit()
      self.tic()
      result = obj.portal_catalog(portal_type=portal_type)
      self.assertSameSet([obj2, obj], [x.getObject() for x in result])
      result = obj.portal_catalog(portal_type=portal_type, local_roles='Assignee')
      self.assertSameSet([obj], [x.getObject() for x in result])
      result = obj.portal_catalog(portal_type=portal_type, local_roles='Auditor')
      self.assertSameSet([obj2, ], [x.getObject() for x in result])
    finally:
      sql_catalog.sql_catalog_object_list = \
        current_sql_catalog_object_list
      sql_catalog.sql_clear_catalog = \
        current_sql_clear_catalog
      sql_catalog.sql_catalog_local_role_keys = \
          current_sql_catalog_local_role_keys
      sql_catalog.sql_catalog_role_keys = \
          current_sql_catalog_role_keys
      sql_catalog.sql_search_tables = current_sql_search_tables
      get_transaction().commit()

  def test_UserOrGroupRoleIndexing(self, quiet=quiet, run=run_all_test):
    if not run: 
      return

    logout = self.logout
    user1 = 'a_great_user_name'
    user1_group = 'a_great_user_group'
    uf = self.getPortal().acl_users
    uf._doAddUser(user1, user1, ['Member', ], [])
    uf.zodb_groups.addGroup( user1_group, user1_group, user1_group)
    new = uf.zodb_groups.addPrincipalToGroup( user1, user1_group )

    perm = 'View'
    folder = self.getOrganisationModule()
    folder.manage_setLocalRoles(user1, ['Author', 'Auditor'])
    portal_type = 'Organisation'
    organisation = folder.newContent(portal_type=portal_type)

    sql_connection = self.getSQLConnection()
    def query(sql):
      result = sql_connection.manage_test(sql)
      return result.dictionaries()

2926
    self.login(user1)
2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183

    # Add a new table to the catalog
    sql_catalog = self.portal.portal_catalog.getSQLCatalog()

    local_roles_table = "test_user_or_group_local_roles"

    create_local_role_table_sql = """
CREATE TABLE `%s` (
  `uid` BIGINT UNSIGNED NOT NULL,
  `assignee_reference` varchar(32) NOT NULL default '',
  `viewable_assignee_reference` varchar(32) NOT NULL default '',
  PRIMARY KEY  (`uid`),
  KEY `assignee_reference` (`assignee_reference`),
  KEY `viewable_assignee_reference` (`viewable_assignee_reference`)
) TYPE=InnoDB;
    """ % local_roles_table
    sql_catalog.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod(
          id = 'z_create_%s' % local_roles_table,
          title = '',
          arguments = "",
          connection_id = 'erp5_sql_connection',
          template = create_local_role_table_sql)

    drop_local_role_table_sql = """
DROP TABLE IF EXISTS %s
    """ % local_roles_table
    sql_catalog.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod(
          id = 'z0_drop_%s' % local_roles_table,
          title = '',
          arguments = "",
          connection_id = 'erp5_sql_connection',
          template = drop_local_role_table_sql)

    catalog_local_role_sql = """
REPLACE INTO
  %s
VALUES
<dtml-in prefix="loop" expr="_.range(_.len(uid))">
(
  <dtml-sqlvar expr="uid[loop_item]" type="int">,  
  <dtml-sqlvar expr="getAssignee[loop_item] or ''" type="string" optional>,
  <dtml-sqlvar expr="getViewPermissionAssignee[loop_item] or ''" type="string" optional>
)
<dtml-if sequence-end>
<dtml-else>
,
</dtml-if>
</dtml-in>
    """ % local_roles_table
    sql_catalog.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod(
          id = 'z_catalog_%s_list' % local_roles_table,
          title = '',
          connection_id = 'erp5_sql_connection',
          arguments = "\n".join(['uid',
                                 'getAssignee',
                                 'getViewPermissionAssignee']),
          template = catalog_local_role_sql)

    get_transaction().commit()
    current_sql_catalog_object_list = sql_catalog.sql_catalog_object_list
    sql_catalog.sql_catalog_object_list = \
      current_sql_catalog_object_list + \
         ('z_catalog_%s_list' % local_roles_table,)
    current_sql_clear_catalog = sql_catalog.sql_clear_catalog
    sql_catalog.sql_clear_catalog = \
      current_sql_clear_catalog + \
         ('z0_drop_%s' % local_roles_table, 'z_create_%s' % local_roles_table)
    current_sql_catalog_local_role_keys = \
          sql_catalog.sql_catalog_local_role_keys
    sql_catalog.sql_catalog_local_role_keys = (
        'Owner | viewable_owner',
        'Assignee | %s.assignee_reference' % \
       local_roles_table,)

    current_sql_catalog_role_keys = \
          sql_catalog.sql_catalog_role_keys
    sql_catalog.sql_catalog_role_keys = (
        'Assignee | %s.viewable_assignee_reference' % \
       local_roles_table,)

    current_sql_search_tables = sql_catalog.sql_search_tables
    sql_catalog.sql_search_tables = sql_catalog.sql_search_tables + \
        [local_roles_table]

    portal = self.getPortal()
    get_transaction().commit()

    try:
      # Clear catalog
      portal_catalog = self.getCatalogTool()
      portal_catalog.manage_catalogClear()
      get_transaction().commit()
      self.portal.portal_caches.clearAllCache()
      get_transaction().commit()

      organisation_relative_url = organisation.getRelativeUrl()
      countResults = organisation.portal_catalog.countResults
      count_result_kw = {'relative_url': organisation_relative_url}

      use_case_number = 0
      for view_permission_role_list, security_group_list, \
          global_view, associate_view, assignee_view, both_view in \
          [
              # No view permission
              ([], [], 0, 0, 0, 0),
              ([], [(user1, ['Associate'])], 0, 0, 0, 0),
              ([], [(user1, ['Assignee'])], 0, 0, 0, 0),
              ([], [(user1, ['Assignee', 'Associate'])], 0, 0, 0, 0),
              ([], [(user1_group, ['Assignee'])], 0, 0, 0, 0),
              ([], [(user1_group, ['Assignee', 'Associate'])], 0, 0, 0, 0),
              ([], [(user1, ['Assignee']),
                    (user1_group, ['Assignee'])], 0, 0, 0, 0),
              ([], [(user1, ['Assignee']),
                    (user1_group, ['Assignee', 'Associate'])], 0, 0, 0, 0),

              # View permission for Assignee
              (['Assignee'], [], 0, 0, 0, 0),
              (['Assignee'], [(user1, ['Associate'])], 0, 0, 0, 0),
              (['Assignee'], [(user1, ['Assignee'])], 1, 0, 1, 1),
              (['Assignee'], [(user1, ['Assignee', 'Associate'])], 1, 0, 1, 1),
              (['Assignee'], [(user1_group, ['Assignee'])], 1, 0, 0, 0),
              (['Assignee'], [(user1_group, ['Assignee', 'Associate'])],
                              1, 0, 0, 0),
              (['Assignee'], [(user1, ['Assignee']),
                              (user1_group, ['Assignee'])], 1, 0, 1, 1),
              (['Assignee'], [(user1, ['Assignee']),
                              (user1_group, ['Assignee', 'Associate'])], 
                               1, 0, 1, 1),

              # View permission for Associate
              (['Associate'], [], 0, 0, 0, 0),
              (['Associate'], [(user1, ['Associate'])], 1, 1, 0, 0),
              (['Associate'], [(user1, ['Assignee'])], 0, 0, 0, 0),
              (['Associate'], [(user1, ['Assignee', 'Associate'])], 1, 1, 1, 1),
              (['Associate'], [(user1_group, ['Assignee'])], 0, 0, 0, 0),
              (['Associate'], [(user1_group, ['Assignee', 'Associate'])], 
                               1, 1, 0, 0),
              (['Associate'], [(user1, ['Assignee']),
                              (user1_group, ['Assignee'])], 0, 0, 0, 0),
              (['Associate'], [(user1, ['Assignee']),
                              (user1_group, ['Assignee', 'Associate'])], 
                               1, 1, 1, 1),

              # View permission for Associate and Assignee
              (['Associate', 'Assignee'], [], 0, 0, 0, 0),
              (['Associate', 'Assignee'], [(user1, ['Associate'])], 1, 1, 0, 0),
              (['Associate', 'Assignee'], [(user1, ['Assignee'])], 1, 0, 1, 1),
              (['Associate', 'Assignee'], 
                     [(user1, ['Assignee', 'Associate'])], 1, 1, 1, 1),
              (['Associate', 'Assignee'], 
                     [(user1_group, ['Assignee'])], 1, 0, 0, 0),
              (['Associate', 'Assignee'], 
                     [(user1_group, ['Assignee', 'Associate'])], 1, 1, 0, 0),
              (['Associate', 'Assignee'], [(user1, ['Assignee']),
                              (user1_group, ['Assignee'])], 1, 0, 1, 1),
              (['Associate', 'Assignee'], [(user1, ['Assignee']),
                              (user1_group, ['Assignee', 'Associate'])], 
                               1, 1, 1, 1),
              ]:

        use_case_number += 1
        organisation.manage_permission(perm, view_permission_role_list, 0)
        organisation.manage_delLocalRoles([user1, user1_group])
        for security_group, local_role_list in security_group_list:
          organisation.manage_setLocalRoles(security_group, local_role_list)
        organisation.reindexObject()
        get_transaction().commit()
        self.tic()

        for expected_result, local_roles in \
            [
                (global_view, None),
                (associate_view, 'Associate'),
                (assignee_view, 'Assignee'),
                (both_view, ['Associate', 'Assignee']),
                ]:

          object_security_uid = query(
            'SELECT security_uid FROM catalog WHERE relative_url="%s"' % \
            organisation_relative_url
              )[0]['security_uid']

          if object_security_uid is not None:
            roles_and_users = query(
              'SELECT allowedRolesAndUsers FROM roles_and_users WHERE uid="%s"' % \
              object_security_uid
                )
          else:
            roles_and_users = ''

          monovalue_references = query(
              'SELECT * FROM test_user_or_group_local_roles WHERE uid="%s"' % \
                  organisation.getUid())[0]
          assignee_reference = monovalue_references['assignee_reference']
          viewable_assignee_reference = \
            monovalue_references['viewable_assignee_reference']

          result = countResults(local_roles=local_roles, **count_result_kw)[0][0]
          if result != expected_result:
            countResults(local_roles=local_roles, src__=1,
                         **count_result_kw)
            self.fail('Use case %s\n\tView permission is given to: %s\n\t' \
                      'Local roles are: %s\n\t' \
                      'local_roles parameter is: %s\n\t' \
                      'Object IS %s returned by portal_catalog!\n\t' \
                      '\n\tSecurity uid is: %s\n\t'
                      'Roles and users:  %s\n\t'
                      'assignee_reference:  %s\n\t'
                      'viewable_assignee_reference:  %s\n\t'
                      '\n\tSQL generated: \n\n%s' \
                      '' % \
                      (use_case_number,
                       view_permission_role_list, 
                       organisation.__ac_local_roles__,
                       local_roles, ['NOT', ''][result],
                       object_security_uid,
                       str([x['allowedRolesAndUsers'] for x in roles_and_users]),
                       assignee_reference,
                       viewable_assignee_reference,
                       countResults(local_roles=local_roles, src__=1,
                                    **count_result_kw)))

    finally:
      sql_catalog.sql_catalog_object_list = \
        current_sql_catalog_object_list
      sql_catalog.sql_clear_catalog = \
        current_sql_clear_catalog
      sql_catalog.sql_catalog_local_role_keys = \
          current_sql_catalog_local_role_keys
      sql_catalog.sql_catalog_role_keys = \
          current_sql_catalog_role_keys
      sql_catalog.sql_search_tables = current_sql_search_tables
      get_transaction().commit()

  def test_UserOrGroupLocalRoleIndexing(self, quiet=quiet, run=run_all_test):
    if not run: 
      return

    logout = self.logout
    user1 = 'another_great_user_name'
    user1_group = 'another_great_user_group'
    uf = self.getPortal().acl_users
    uf._doAddUser(user1, user1, ['Member', ], [])
    uf.zodb_groups.addGroup( user1_group, user1_group, user1_group)
    new = uf.zodb_groups.addPrincipalToGroup( user1, user1_group )

    perm = 'View'
    folder = self.getOrganisationModule()
    folder.manage_setLocalRoles(user1, ['Author', 'Auditor'])
    portal_type = 'Organisation'
    organisation = folder.newContent(portal_type=portal_type)

    sql_connection = self.getSQLConnection()
    def query(sql):
      result = sql_connection.manage_test(sql)
      return result.dictionaries()

3184
    self.login(user1)
3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399

    # Add a new table to the catalog
    sql_catalog = self.portal.portal_catalog.getSQLCatalog()

    local_roles_table = "another_test_user_or_group_local_roles"

    create_local_role_table_sql = """
CREATE TABLE `%s` (
  `uid` BIGINT UNSIGNED NOT NULL,
  `viewable_assignee_reference` varchar(32) NOT NULL default '',
  PRIMARY KEY  (`uid`),
  KEY `viewable_assignee_reference` (`viewable_assignee_reference`)
) TYPE=InnoDB;
    """ % local_roles_table
    sql_catalog.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod(
          id = 'z_create_%s' % local_roles_table,
          title = '',
          arguments = "",
          connection_id = 'erp5_sql_connection',
          template = create_local_role_table_sql)

    drop_local_role_table_sql = """
DROP TABLE IF EXISTS %s
    """ % local_roles_table
    sql_catalog.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod(
          id = 'z0_drop_%s' % local_roles_table,
          title = '',
          arguments = "",
          connection_id = 'erp5_sql_connection',
          template = drop_local_role_table_sql)

    catalog_local_role_sql = """
REPLACE INTO
  %s
VALUES
<dtml-in prefix="loop" expr="_.range(_.len(uid))">
(
  <dtml-sqlvar expr="uid[loop_item]" type="int">,  
  <dtml-sqlvar expr="getViewPermissionAssignee[loop_item] or ''" type="string" optional>
)
<dtml-if sequence-end>
<dtml-else>
,
</dtml-if>
</dtml-in>
    """ % local_roles_table
    sql_catalog.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod(
          id = 'z_catalog_%s_list' % local_roles_table,
          title = '',
          connection_id = 'erp5_sql_connection',
          arguments = "\n".join(['uid',
                                 'getViewPermissionAssignee']),
          template = catalog_local_role_sql)

    get_transaction().commit()
    current_sql_catalog_object_list = sql_catalog.sql_catalog_object_list
    sql_catalog.sql_catalog_object_list = \
      current_sql_catalog_object_list + \
         ('z_catalog_%s_list' % local_roles_table,)
    current_sql_clear_catalog = sql_catalog.sql_clear_catalog
    sql_catalog.sql_clear_catalog = \
      current_sql_clear_catalog + \
         ('z0_drop_%s' % local_roles_table, 'z_create_%s' % local_roles_table)

    current_sql_catalog_role_keys = \
          sql_catalog.sql_catalog_role_keys
    sql_catalog.sql_catalog_role_keys = (
        'Owner | viewable_owner',
        'Assignee | %s.viewable_assignee_reference' % \
       local_roles_table,)

    current_sql_search_tables = sql_catalog.sql_search_tables
    sql_catalog.sql_search_tables = sql_catalog.sql_search_tables + \
        [local_roles_table]

    portal = self.getPortal()
    get_transaction().commit()

    try:
      # Clear catalog
      portal_catalog = self.getCatalogTool()
      portal_catalog.manage_catalogClear()
      get_transaction().commit()
      self.portal.portal_caches.clearAllCache()
      get_transaction().commit()

      organisation_relative_url = organisation.getRelativeUrl()
      countResults = organisation.portal_catalog.countResults
      count_result_kw = {'relative_url': organisation_relative_url}

      use_case_number = 0
      for view_permission_role_list, security_group_list, \
          associate_view, assignee_view in \
          [
              # No view permission
              ([], [], 0, 0),
              ([], [(user1, ['Associate'])], 0, 0),
              ([], [(user1, ['Assignee'])], 0, 0),
              ([], [(user1, ['Assignee', 'Associate'])], 0, 0),
              ([], [(user1_group, ['Assignee'])], 0, 0),
              ([], [(user1_group, ['Assignee', 'Associate'])], 0, 0),
              ([], [(user1, ['Assignee']),
                    (user1_group, ['Assignee'])], 0, 0),
              ([], [(user1, ['Assignee']),
                    (user1_group, ['Assignee', 'Associate'])], 0, 0),

              # View permission for Assignee
              (['Assignee'], [], 0, 0),
              (['Assignee'], [(user1, ['Associate'])], 0, 0),
              (['Assignee'], [(user1, ['Assignee'])], 0, 1),
              (['Assignee'], [(user1, ['Assignee', 'Associate'])], 0, 1),
              (['Assignee'], [(user1_group, ['Assignee'])], 0, 1),
              (['Assignee'], [(user1_group, ['Assignee', 'Associate'])], 0, 1),
              (['Assignee'], [(user1, ['Assignee']),
                              (user1_group, ['Assignee'])], 0, 1),
              (['Assignee'], [(user1, ['Assignee']),
                              (user1_group, ['Assignee', 'Associate'])], 0, 1),

              # View permission for Associate
              (['Associate'], [], 0, 0),
              (['Associate'], [(user1, ['Associate'])], 1, 0),
              (['Associate'], [(user1, ['Assignee'])], 0, 0),
              (['Associate'], [(user1, ['Assignee', 'Associate'])], 1, 0),
              (['Associate'], [(user1_group, ['Assignee'])], 0, 0),
              (['Associate'], [(user1_group, ['Assignee', 'Associate'])], 1, 0),
              (['Associate'], [(user1, ['Assignee']),
                              (user1_group, ['Assignee'])], 0, 0),
              (['Associate'], [(user1, ['Assignee']),
                              (user1_group, ['Assignee', 'Associate'])], 1, 0),

              # View permission for Associate and Assignee
              (['Associate', 'Assignee'], [], 0, 0),
              (['Associate', 'Assignee'], [(user1, ['Associate'])], 1, 0),
              (['Associate', 'Assignee'], [(user1, ['Assignee'])], 0, 1),
              (['Associate', 'Assignee'], 
                     [(user1, ['Assignee', 'Associate'])], 1, 1),
              (['Associate', 'Assignee'], 
                     [(user1_group, ['Assignee'])], 0, 1),
              (['Associate', 'Assignee'], 
                     [(user1_group, ['Assignee', 'Associate'])], 1, 1),
              (['Associate', 'Assignee'], [(user1, ['Assignee']),
                              (user1_group, ['Assignee'])], 0, 1),
              (['Associate', 'Assignee'], [(user1, ['Assignee']),
                              (user1_group, ['Assignee', 'Associate'])], 1, 1),
              ]:

        use_case_number += 1
        organisation.manage_permission(perm, view_permission_role_list, 0)
        organisation.manage_delLocalRoles([user1, user1_group])
        for security_group, local_role_list in security_group_list:
          organisation.manage_setLocalRoles(security_group, local_role_list)
        organisation.reindexObject()
        get_transaction().commit()
        self.tic()

        for expected_result, local_roles in \
            [
                (associate_view or assignee_view, None),
                (associate_view, 'Associate'),
                (assignee_view, 'Assignee'),
                (associate_view or assignee_view, ['Associate', 'Assignee']),
                ]:

          object_security_uid = query(
            'SELECT security_uid FROM catalog WHERE relative_url="%s"' % \
            organisation_relative_url
              )[0]['security_uid']

          if object_security_uid is not None:
            roles_and_users = query(
              'SELECT allowedRolesAndUsers FROM roles_and_users WHERE uid="%s"' % \
              object_security_uid
                )
          else:
            roles_and_users = ''

          monovalue_references = query(
              'SELECT * FROM %s WHERE uid="%s"' % \
                 (local_roles_table, organisation.getUid()))[0]
          viewable_assignee_reference = \
            monovalue_references['viewable_assignee_reference']

          result = countResults(local_roles=local_roles, **count_result_kw)[0][0]
          if result != expected_result:
            countResults(local_roles=local_roles, src__=1,
                         **count_result_kw)
            self.fail('Use case %s\n\tView permission is given to: %s\n\t' \
                      'Local roles are: %s\n\t' \
                      'local_roles parameter is: %s\n\t' \
                      'Object IS %s returned by portal_catalog!\n\t' \
                      '\n\tSecurity uid is: %s\n\t'
                      'Roles and users:  %s\n\t'
                      'viewable_assignee_reference:  %s\n\t'
                      '\n\tSQL generated: \n\n%s' \
                      '' % \
                      (use_case_number,
                       view_permission_role_list, 
                       organisation.__ac_local_roles__,
                       local_roles, ['NOT', ''][result],
                       object_security_uid,
                       str([x['allowedRolesAndUsers'] for x in roles_and_users]),
                       viewable_assignee_reference,
                       countResults(local_roles=local_roles, src__=1,
                                    **count_result_kw)))

    finally:
      sql_catalog.sql_catalog_object_list = \
        current_sql_catalog_object_list
      sql_catalog.sql_clear_catalog = \
        current_sql_clear_catalog
      sql_catalog.sql_catalog_role_keys = \
          current_sql_catalog_role_keys
      sql_catalog.sql_search_tables = current_sql_search_tables
      get_transaction().commit()

3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499
  def test_ObjectReindexationConcurency(self, quiet=quiet, run=run_all_test):
    if not run:
      return

    portal = self.getPortalObject()

    portal_activities = getattr(portal, 'portal_activities', None)
    if portal_activities is None:
      ZopeTestCase._print('\n Skipping test_ObjectReindexatoinConcurency (portal_activities not found)')
      return

    container = organisation_module = portal.organisation_module
    document_1 = container.newContent()
    document_1_1 = document_1.newContent()
    document_1_2 = document_1.newContent()
    document_2 = container.newContent()
    get_transaction().commit()
    self.tic()
    # First case: parent, then child
    document_1.reindexObject()
    self.assertEqual(len(portal_activities.getMessageList()), 0)
    get_transaction().commit()
    self.assertEqual(len(portal_activities.getMessageList()), 1)
    portal_activities.distribute()
    self.assertEqual(len([x for x in portal_activities.getMessageList() if x.processing_node == 0]), 1)
    document_1_1.reindexObject()
    get_transaction().commit()
    self.assertEqual(len(portal_activities.getMessageList()), 2)
    portal_activities.distribute()
    self.assertEqual(len([x for x in portal_activities.getMessageList() if x.processing_node == 0]), 1)
    self.tic()
    # Variation of first case: parent's borther along
    document_1.reindexObject()
    document_2.reindexObject()
    self.assertEqual(len(portal_activities.getMessageList()), 0)
    get_transaction().commit()
    self.assertEqual(len(portal_activities.getMessageList()), 2)
    portal_activities.distribute()
    self.assertEqual(len([x for x in portal_activities.getMessageList() if x.processing_node == 0]), 2)
    document_1_1.reindexObject()
    get_transaction().commit()
    self.assertEqual(len(portal_activities.getMessageList()), 3)
    portal_activities.distribute()
    self.assertEqual(len([x for x in portal_activities.getMessageList() if x.processing_node == 0]), 2)
    self.tic()
    # Second case: child, then parent
    document_1_1.reindexObject()
    self.assertEqual(len(portal_activities.getMessageList()), 0)
    get_transaction().commit()
    self.assertEqual(len(portal_activities.getMessageList()), 1)
    portal_activities.distribute()
    self.assertEqual(len([x for x in portal_activities.getMessageList() if x.processing_node == 0]), 1)
    document_1.reindexObject()
    get_transaction().commit()
    self.assertEqual(len(portal_activities.getMessageList()), 2)
    portal_activities.distribute()
    self.assertEqual(len([x for x in portal_activities.getMessageList() if x.processing_node == 0]), 1)
    self.tic()
    # Variation of second case: parent's borther along
    document_1_1.reindexObject()
    document_2.reindexObject()
    self.assertEqual(len(portal_activities.getMessageList()), 0)
    get_transaction().commit()
    self.assertEqual(len(portal_activities.getMessageList()), 2)
    portal_activities.distribute()
    self.assertEqual(len([x for x in portal_activities.getMessageList() if x.processing_node == 0]), 2)
    document_1.reindexObject()
    get_transaction().commit()
    self.assertEqual(len(portal_activities.getMessageList()), 3)
    portal_activities.distribute()
    self.assertEqual(len([x for x in portal_activities.getMessageList() if x.processing_node == 0]), 2)
    self.tic()
    # Third case: child 1, then child 2
    document_1_1.reindexObject()
    self.assertEqual(len(portal_activities.getMessageList()), 0)
    get_transaction().commit()
    self.assertEqual(len(portal_activities.getMessageList()), 1)
    portal_activities.distribute()
    self.assertEqual(len([x for x in portal_activities.getMessageList() if x.processing_node == 0]), 1)
    document_1_2.reindexObject()
    get_transaction().commit()
    self.assertEqual(len(portal_activities.getMessageList()), 2)
    portal_activities.distribute()
    self.assertEqual(len([x for x in portal_activities.getMessageList() if x.processing_node == 0]), 1)
    self.tic()
    # Variation of third case: parent's borther along
    document_1_1.reindexObject()
    document_2.reindexObject()
    self.assertEqual(len(portal_activities.getMessageList()), 0)
    get_transaction().commit()
    self.assertEqual(len(portal_activities.getMessageList()), 2)
    portal_activities.distribute()
    self.assertEqual(len([x for x in portal_activities.getMessageList() if x.processing_node == 0]), 2)
    document_1_2.reindexObject()
    get_transaction().commit()
    self.assertEqual(len(portal_activities.getMessageList()), 3)
    portal_activities.distribute()
    self.assertEqual(len([x for x in portal_activities.getMessageList() if x.processing_node == 0]), 2)
    self.tic()

3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523
  def test_PercentCharacter(self, quiet=quiet, run=run_all_test):
    """
    Check expected behaviour of % character for simple query
    """
    if not run: 
      return

    portal_type = 'Organisation'
    folder = self.getOrganisationModule()
    folder.newContent(portal_type=portal_type, title='foo_organisation_1')
    folder.newContent(portal_type=portal_type, title='foo_organisation_2')
    get_transaction().commit()
    self.tic()
    self.assertEquals(1, len(folder.portal_catalog(portal_type=portal_type,
                                                   title='foo_organisation_1')))
    self.assertEquals(1, len(folder.portal_catalog(portal_type=portal_type,
                                                   title='foo_organisation_2')))
    self.assertEquals(1, len(folder.portal_catalog(portal_type=portal_type,
                                                   title='%organisation_1')))
    self.assertEquals(2, len(folder.portal_catalog(portal_type=portal_type,
                                                   title='foo_organisation%')))
    self.assertEquals(1, len(folder.portal_catalog(portal_type=portal_type,
                                                   title='foo_org%ion_1')))

3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542
  def test_SearchedStringIsNotStripped(self, quiet=quiet, run=run_all_test):
    """
      Check that extra spaces in lookup values are preserved
    """
    if not run:
      return

    portal_type = 'Organisation'
    folder = self.getOrganisationModule()
    first_doc = folder.newContent(portal_type=portal_type, reference="foo")
    second_doc = folder.newContent(portal_type=portal_type, reference=" foo")
    get_transaction().commit()
    self.tic()
    def compareSet(reference, document_list):
      result = folder.portal_catalog(portal_type=portal_type,
                                     reference=reference)
      self.assertSameSet(document_list, [x.getObject() for x in result])
    compareSet('foo', [first_doc])
    compareSet(' foo', [second_doc])
3543 3544 3545 3546 3547
    # XXX: Those will hardly work, and it probably not the responsability of python code:
    # MySQL ignores trailing spaces in conditions.
    # So it's probably not really part of this test.
    #compareSet('foo ', [])
    #compareSet(' foo ', [])
3548

3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564
  def test_WildcardMatchesUnsetValue(self, quiet=quiet, run=run_all_test):
    """
      Check that the "%" wildcard matches unset values.
    """
    if not run:
      return
    
    portal_type = 'Organisation'
    folder = self.getOrganisationModule()
    first_doc = folder.newContent(portal_type=portal_type, reference="doc 1")
    second_doc = folder.newContent(portal_type=portal_type, reference="doc 2", description="test")
    get_transaction().commit()
    self.tic()
    result = folder.portal_catalog(portal_type=portal_type, reference='doc %', description='%')
    self.assertEqual(len(result), 2)

3565
  @todo_erp5
3566 3567 3568 3569 3570
  def test_sortOnRelatedKeyWithUnsetRelation(self, quiet=quiet, run=run_all_test):
    """
      Check that sorting on a related key does not filter out objects for
      which the relation is not set.
    """
3571 3572 3573
    if not run:
      return
  
3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585
    portal = self.getPortalObject()
    organisation = portal.organisation_module.\
                   newContent(portal_type="Organisation")
    person_module = portal.person_module
    person_1 = person_module.newContent(portal_type="Person")
    person_2 = person_module.newContent(portal_type="Person",
                 career_subordination_value=organisation)
    get_transaction().commit()
    self.tic()
    self.assertEqual(len(person_module.searchFolder()),
                     len(person_module.searchFolder(sort_on=[('subordination_title', 'ascending')])))

3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596
  def test_multipleRelatedKeyDoMultipleJoins(self, quiet=quiet, run=run_all_test):
    """
      Check that when multiple related keys are present in the same query,
      each one does a separate join.
      ie:
        Searching for an object whose site_title is "foo" and
        site_description is "bar" will yeld a result set which is the union
        of:
          - objects whose site_title is foo
          - objects whose site_description is bar
    """
3597 3598 3599
    if not run:
      return

3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659
    portal = self.getPortalObject()
    def _create(**kw):
      return portal.organisation_module.newContent(portal_type='Organisation', **kw)
    def create(id, related_obect_list):
      return _create(id=id,
        site_value_list=related_obect_list,
        function_value_list=related_obect_list)
    def check(expected_result, description, query):
      result = [x.getObject() for x in portal.portal_catalog(portal_type='Organisation', query=query)]
      self.assertSameSet(expected_result, result,
        '%s:\nExpected: %r\nGot: %r' % (description,
           [x.getId() for x in expected_result],
           [x.getId() for x in result]))
    # completely artificial example, we just need relations
    related_1 = _create(title='foo1', reference='foo', description='bar')
    related_2 = _create(title='foo2', reference='foo'                   )
    related_3 = _create(                               description='bar')
    related_4 = _create()
    object_1  = create('object_1',  [related_1])
    object_2  = create('object_2',  [related_2])
    object_3  = create('object_3',  [related_3])
    object_4  = create('object_4',  [related_4])
    object_12 = create('object_12', [related_1, related_2])
    object_13 = create('object_13', [related_1, related_3])
    object_14 = create('object_14', [related_1, related_4])
    object_23 = create('object_23', [related_2, related_3])
    object_24 = create('object_24', [related_2, related_4])
    object_34 = create('object_34', [related_3, related_4])
    reference_object_list =   [object_1, object_2,                     object_12, object_13, object_14, object_23, object_24           ]
    description_object_list = [object_1,           object_3,           object_12, object_13, object_14, object_23,            object_34]
    both_object_list =        [object_1,                               object_12, object_13, object_14, object_23                      ]
    title_object_list =       [                                        object_12                                                       ]
    get_transaction().commit()
    self.tic()
    # Single join
    check(reference_object_list,
          'site_reference="foo"',
          Query(site_reference='foo'))
    check(description_object_list,
          'site_description="bar"',
          Query(site_description='bar'))
    # Double join on different relations
    check(both_object_list,
          'site_reference="foo" AND function_description="bar"',
          ComplexQuery(Query(site_reference='foo'),
                       Query(function_description='bar'),
                       operator='AND'))
    # Double join on same relation
    check(both_object_list,
          'site_reference="foo" AND site_description="bar"',
          ComplexQuery(Query(site_reference='foo'),
                       Query(site_description='bar'),
                       operator='AND'))
    # Double join on same related key
    check(title_object_list,
          'site_title="foo1" AND site_title="foo2"',
          ComplexQuery(Query(site_title='=foo1'),
                       Query(site_title='=foo2'),
                       operator='AND'))

3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797
  def test_SearchFolderWithRelatedDynamicRelatedKey(self,
                                  quiet=quiet, run=run_all_test):
    if not run: return
    if not quiet:
      message = 'Search Folder With Related Dynamic Related Key'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    # Create some objects
    portal = self.getPortal()
    portal_category = self.getCategoryTool()
    portal_category.group.manage_delObjects([x for x in
        portal_category.group.objectIds()])
    group_nexedi_category = portal_category.group\
                                .newContent( id = 'nexedi', title='Nexedi',
                                             description='a')
    group_nexedi_category2 = portal_category.group\
                                .newContent( id = 'storever', title='Storever',
                                             description='b')
    module = portal.getDefaultModule('Organisation')
    organisation = module.newContent(portal_type='Organisation',
                                     title='Nexedi Orga',
                                     description='c')
    organisation.setGroup('nexedi')
    self.assertEquals(organisation.getGroupValue(), group_nexedi_category)
    organisation2 = module.newContent(portal_type='Organisation',
                                      title='Storever Orga',
                                      description='d')
    organisation2.setGroup('storever')
    organisation2.setTitle('Organisation 2')
    self.assertEquals(organisation2.getGroupValue(), group_nexedi_category2)
    # Flush message queue
    get_transaction().commit()
    self.tic()

    base_category = portal_category.group
    # Try to get the category with the group related organisation title Nexedi
    # Orga
    category_list = [x.getObject() for x in 
                         base_category.searchFolder(
                           group_related_title='Nexedi Orga')]
    self.assertEquals(category_list, [group_nexedi_category])
    category_list = [x.getObject() for x in 
                         base_category.searchFolder(
                           default_group_related_title='Nexedi Orga')]
    self.assertEquals(category_list, [group_nexedi_category])
    # Try to get the category with the group related organisation id
    category_list = [x.getObject() for x in 
                         base_category.searchFolder(group_related_id='storever')]
    self.assertEquals(category_list,[group_nexedi_category2])
    # Try to get the category with the group related organisation description 'd'
    category_list = [x.getObject() for x in 
                         base_category.searchFolder(group_related_description='d')]
    self.assertEquals(category_list,[group_nexedi_category2])
    # Try to get the category with the group related organisation description
    # 'e'
    category_list = [x.getObject() for x in 
                         base_category.searchFolder(group_related_description='e')]
    self.assertEquals(category_list,[])
    # Try to get the category with the default group related organisation description
    # 'e'
    category_list = [x.getObject() for x in 
                         base_category.searchFolder(default_group_related_description='e')]
    self.assertEquals(category_list,[])
    # Try to get the category with the group related organisation relative_url
    organisation_relative_url = organisation.getRelativeUrl()
    category_list = [x.getObject() for x in 
                 base_category.searchFolder(group_related_relative_url=organisation_relative_url)]
    self.assertEquals(category_list, [group_nexedi_category])
    # Try to get the category with the group related organisation uid
    category_list = [x.getObject() for x in 
                 base_category.searchFolder(group_related_uid=organisation.getUid())]
    self.assertEquals(category_list, [group_nexedi_category])
    # Try to get the category with the group related organisation id and title
    # of the category
    category_list = [x.getObject() for x in 
                         base_category.searchFolder(group_related_id=organisation2.getId(),
                                             title='Storever')]
    self.assertEquals(category_list,[group_nexedi_category2])

  def test_SearchFolderWithRelatedDynamicStrictRelatedKey(self,
                                  quiet=quiet, run=run_all_test):
    if not run: return
    if not quiet:
      message = 'Search Folder With Related Strict Dynamic Related Key'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    # Create some objects
    portal = self.getPortal()
    portal_category = self.getCategoryTool()
    portal_category.group.manage_delObjects([x for x in
        portal_category.group.objectIds()])
    group_nexedi_category = portal_category.group\
                                .newContent( id = 'nexedi', title='Nexedi',
                                             description='a')
    sub_group_nexedi = group_nexedi_category\
                                .newContent( id = 'erp5', title='ERP5',
                                             description='b')
    module = portal.getDefaultModule('Organisation')
    organisation = module.newContent(portal_type='Organisation',
                                     title='ERP5 Orga',
                                     description='c')
    organisation.setGroup('nexedi/erp5')
    self.assertEquals(organisation.getGroupValue(), sub_group_nexedi)
    organisation2 = module.newContent(portal_type='Organisation',
                                     title='Nexedi Orga',
                                     description='d')
    organisation2.setGroup('nexedi')
    # Flush message queue
    get_transaction().commit()
    self.tic()

    base_category = portal_category.group

    # Try to get the category with the group related organisation title Nexedi
    # Orga
    category_list = [x.getObject() for x in 
                         base_category.portal_catalog(
                             strict_group_related_title='Nexedi Orga')]
    self.assertEquals(category_list,[group_nexedi_category])
    # Try to get the category with the group related organisation title ERP5
    # Orga
    category_list = [x.getObject() for x in 
                         base_category.portal_catalog(
                           strict_group_related_title='ERP5 Orga')]
    self.assertEquals(category_list,[sub_group_nexedi])
    # Try to get the category with the group related organisation description d
    category_list = [x.getObject() for x in 
                         base_category.portal_catalog(
                           strict_group_related_description='d')]
    self.assertEquals(category_list,[group_nexedi_category])
    # Try to get the category with the group related organisation description c
    category_list = [x.getObject() for x in 
                         base_category.portal_catalog(
                           strict_group_related_description='c')]
    self.assertEquals(category_list,[sub_group_nexedi])

3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814
  def test_EscapingLoginInSescurityQuery(self,
                                  quiet=quiet, run=run_all_test):
    if not run: return
    if not quiet:
      message = 'Test that login are escaped when call security_query'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    # Create some objects
    reference = "aaa.o'connor@fake.ie"
    portal = self.getPortal()
    uf = self.portal.acl_users
    uf._doAddUser(reference, 'secret', ['Member'], [])
    user = uf.getUserById(reference).__of__(uf)
    newSecurityManager(None, user)
    portal.view()

3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827
  def test_IndexationContextIndependence(self, quiet=quiet, run=run_all_test):
    if not run: return
    if not quiet:
      message = 'Test that indexation is context-independent'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    def doCatalog(catalog, document):
      catalog.catalogObjectList([document], check_uid=0)
      result = catalog(select_expression='reference', uid=document.getUid())
      self.assertEqual(len(result), 1)
      return result[0].reference

3828
    # Create some dummy documents
3829 3830 3831
    portal = self.getPortalObject()
    portal.foo = FooDocument()
    portal.bar = BarDocument()
3832

3833 3834 3835 3836
    # Get instances, wrapping them in acquisition context implicitely.
    foo = portal.foo
    bar = portal.bar

3837
    # Consistency checks
3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864
    self.assertTrue(getattr(foo, 'getReference', None) is not None)
    self.assertTrue(getattr(bar, 'getReference', None) is None)

    # Clean indexing
    portal_catalog = portal.portal_catalog
    self.assertEqual(doCatalog(portal_catalog, foo), 'foo')
    self.assertEqual(doCatalog(portal_catalog, bar), None)

    # Index an object wrapped in a "poisoned" acquisition chain
    bar_on_foo = portal.foo.bar
    self.assertTrue(getattr(bar_on_foo, 'getReference', None) is not None)
    self.assertEqual(bar_on_foo.getReference(), 'foo')
    self.assertEqual(doCatalog(portal_catalog, bar_on_foo), None)

    # Index an object with catalog wrapped in a "poisoned" acquisition chain
    portal_catalog_on_foo = portal.foo.portal_catalog
    self.assertTrue(getattr(portal_catalog_on_foo, 'getReference', None) is not None)
    self.assertEqual(portal_catalog_on_foo.getReference(), 'foo')
    self.assertEqual(doCatalog(portal_catalog_on_foo, foo), 'foo')
    self.assertEqual(doCatalog(portal_catalog_on_foo, bar), None)

    # Poison everything
    self.assertEqual(doCatalog(portal_catalog_on_foo, bar_on_foo), None)

    delattr(portal, 'foo')
    delattr(portal, 'bar')

3865 3866 3867 3868 3869
  def test_distinct_select_expression(self, quiet=quiet, run=run_all_test):
    if not run: return
    portal_catalog = self.getCatalogTool()
    res = portal_catalog.searchResults(
      select_expression='count(DISTINCT catalog.reference) AS count_reference',
3870
      group_by_expression='catalog.reference',
3871 3872 3873
    )
    self.assertEquals(1, len(res))

3874
  def test_CatalogUidDuplicates(self, quiet=quiet, run=run_all_test):
3875 3876 3877 3878 3879 3880
    """
    Initially, the catalog was changing uids when a duplicate was found.

    This operation was really too dangerous, so now we raise errors in this
    case. Here we now check that the error is raised
    """
3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913
    if not run: return
    if not quiet:
      message = 'Catalog Uid Duplicates'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    # Create an object just to allocate a new valid uid.
    person_module = self.getPersonModule()
    person = person_module.newContent(portal_type='Person')
    get_transaction().commit()
    self.tic()

    # Make sure that the new object is catalogued.
    portal_catalog = self.getPortalObject().portal_catalog
    self.assertEquals(person, portal_catalog(uid=person.uid)[0].getObject())

    # Delete the new object to free the uid.
    available_uid = person.uid
    person_module.manage_delObjects(uids=[available_uid])
    get_transaction().commit()
    self.tic()

    # Make sure that the uid is not used any longer.
    self.assertEquals(0, len(portal_catalog(uid=person.uid)))

    # Now, we create two new objects without indexing, so the catalog
    # will not know anything about these objects.
    person1 = person_module.newContent(portal_type='Person', is_indexable=False)
    person2 = person_module.newContent(portal_type='Person', is_indexable=False)

    # Force to assign the same uid, and catalog them.
    person1.uid = person2.uid = available_uid
    person1.is_indexable = person2.is_indexable = True
3914
    self.assertRaises(ValueError, portal_catalog.catalogObjectList,[person1, person2])
3915

3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934
  def test_SearchFolderWithParenthesis(self, quiet=quiet):
    if not quiet:
      message = 'Search Folder With Parenthesis'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()

    # Make sure that the catalog will not split it with such research :
    # title=foo AND title=bar
    title='foo (bar)'
    person = person_module.newContent(portal_type='Person',title=title)
    person_id = person.getId()
    person.immediateReindexObject()
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertTrue(person_id in folder_object_list)
    folder_object_list = [x.getObject().getId() for x in 
                              person_module.searchFolder(title=title)]
    self.assertEquals([person_id],folder_object_list)
3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957
 
  def test_SearchFolderWithMultipleSpaces(self, quiet=quiet):
    if not quiet:
      message = 'Search Folder With Multiple Spaces'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()

    # Make sure that the catalog will not split it with such research :
    # title=foo AND title=bar
    title='foo bar'
    person_module.newContent(portal_type='Person',title=title).immediateReindexObject()
    title = title.replace(' ', '  ')
    person = person_module.newContent(portal_type='Person',title=title)
    person_id = person.getId()
    person.immediateReindexObject()
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertTrue(person_id in folder_object_list)
    folder_object_list = [x.getObject().getId() for x in 
                              person_module.searchFolder(title=title)]
    self.assertEquals([person_id],folder_object_list)
 
3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977
  def test_SearchFolderWithSingleQuote(self, quiet=quiet):
    if not quiet:
      message = 'Search Folder With Single Quote'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()

    # Make sure that the catalog will not split it with such research :
    # title=foo AND title=bar
    title="foo 'bar"
    person = person_module.newContent(portal_type='Person',title=title)
    person_id = person.getId()
    person.immediateReindexObject()
    folder_object_list = [x.getObject().getId() for x in person_module.searchFolder()]
    self.assertTrue(person_id in folder_object_list)
    folder_object_list = [x.getObject().getId() for x in 
                              person_module.searchFolder(title=title)]
    self.assertEquals([person_id],folder_object_list)

3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988
  def test_ParameterSelectDict(self, quiet=quiet):
    if not quiet:
      message = 'Check Parameter Select Dict'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()

    # Make sure that we are able to retrieve data directly from mysql
    # without retrieving real objects
    title="foo"
3989 3990 3991
    description = "foobar"
    person = person_module.newContent(portal_type='Person',title=title,
                                      description=description)
3992 3993 3994 3995
    person_uid = person.getUid()
    person.immediateReindexObject()
    folder_object_list = person_module.searchFolder(uid=person_uid, select_dict={'title': None})
    new_title = 'bar'
3996
    new_description = 'foobarfoo'
3997
    person.setTitle(new_title)
3998
    person.setDescription(new_description)
3999 4000
    self.assertEquals(new_title, person.getTitle())
    expected_sql_title_list = [title]
4001 4002 4003 4004 4005 4006 4007
    self.assertEquals([x.title for x in folder_object_list],
                      expected_sql_title_list)
    self.assertEquals([x.getProperty('title') for x in
                      folder_object_list], expected_sql_title_list)
    expected_sql_description_list = [new_description]
    self.assertEquals([x.getProperty('description') for x in
                      folder_object_list], expected_sql_description_list)
4008
    real_title_list = [new_title]
4009 4010
    self.assertEquals([x.getTitle() for x in
                      folder_object_list], real_title_list)
4011

4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040
  def test_countResultsUsesFromExpression(self, quiet=quiet):
    if not quiet:
      message = 'countResults uses from_expression'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    person_module = self.getPersonModule()
    module_len = len(person_module)
    if module_len == 0:
      person = person_module.newContent(portal_type='Person')
      module_len = len(person_module)
    module_uid = person_module.getUid()

    get_transaction().commit()
    self.tic()
    catalog = self.getCatalogTool()

    # Test sanity checks
    self.assertEqual(len(catalog.searchResults(parent_uid=module_uid)),
      module_len)
    self.assertEqual(catalog.countResults(parent_uid=module_uid)[0][0],
      module_len)

    self.assertEquals(catalog.countResults(from_expression={
      'catalog': '(SELECT sub_catalog.* FROM catalog AS sub_catalog' \
        ' WHERE sub_catalog.parent_uid=%i)' \
        ' AS catalog' % (module_uid, ),
    })[0][0], module_len)

Jérome Perrin's avatar
Jérome Perrin committed
4041 4042 4043 4044
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestERP5Catalog))
  return suite
4045