testPredicate.py 27.9 KB
Newer Older
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 29 30 31 32 33
#############################################################################
#
# Copyright (c) 2004 Nexedi SARL and Contributors. All Rights Reserved.
#          Jerome Perrin <jerome@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.
#
##############################################################################

"""
  Tests Predicates

"""

Jérome Perrin's avatar
Jérome Perrin committed
34
import unittest
35 36

from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
37
from Products.ERP5Type.tests.utils import createZODBPythonScript
38
from AccessControl.SecurityManagement import newSecurityManager
39
from Products.ERP5Type.tests.Sequence import Sequence
40 41 42 43 44 45 46

REGION_FRANCE_PATH = 'region/europe/western_europe/france'
REGION_GERMANY_PATH = 'region/europe/western_europe/germany'
GROUP_STOREVER_PATH = 'group/nexedi/storever'
GROUP_OTHER_PATH = 'group/other'

RUN_ALL_TESTS = 1
47
QUIET = 1
48 49
PREDICATE_FOLDER_NAME = "predicate_unit_test_folder"

50
class TestPredicateMixIn(ERP5TypeTestCase):
51
  """Test Predicates. """
52

53 54
  def getTitle(self):
    return "Predicates"
55

56 57 58 59 60 61 62
  def login(self) :
    """sets the security manager"""
    uf = self.getPortal().acl_users
    uf._doAddUser('alex', '', ['Member', 'Assignee', 'Assignor',
                               'Auditor', 'Author', 'Manager'], [])
    user = uf.getUserById('alex').__of__(uf)
    newSecurityManager(None, user)
63

64 65 66
  def afterSetUp(self) :
    self.createCategories()
    self.login()
67

68
  def playSequence(self, sequence_string, quiet=QUIET) :
69 70 71 72 73 74
    # don't commit between steps
    sequence = Sequence()
    sequence.setSequenceString(sequence_string)
    for step in sequence._step_list:
      step.play(self, sequence, quiet)

75 76 77 78 79 80 81 82 83 84 85 86 87
  # XXX ... this method is a copy / paste
  def createCategories(self):
    """Create the list of categories returned by the
    `getNeededCategoryList` Method.
    """
    # create categories
    for cat_string in self.getNeededCategoryList() :
      base_cat = cat_string.split("/")[0]
      path = self.getPortal().portal_categories[base_cat]
      for cat in cat_string.split("/")[1:] :
        if not cat in path.objectIds() :
          path = path.newContent(
            portal_type = 'Category',
88
            id = cat,)
89 90 91 92 93 94 95 96
        else :
          path = path[cat]

    # check categories have been created
    for cat_string in self.getNeededCategoryList() :
      self.assertNotEquals(None,
                self.getCategoryTool().restrictedTraverse(cat_string),
                cat_string)
97
    self.tic()
98 99 100 101 102

  def getNeededCategoryList(self):
    """return a list of categories that should be created."""
    return ( REGION_FRANCE_PATH, REGION_GERMANY_PATH,
             GROUP_STOREVER_PATH, GROUP_OTHER_PATH )
103

104 105 106
  def getBusinessTemplateList(self):
    """ """
    return ('erp5_base', )
107

108 109 110 111 112 113 114 115
  def getPredicateFolder(self):
    """Return a folder for predicates."""
    if PREDICATE_FOLDER_NAME in self.getPortal().objectIds() :
      predicate_folder = self.getPortal()[PREDICATE_FOLDER_NAME]
    else :
      predicate_folder = self.getPortal().newContent(
                                        portal_type = 'Folder',
                                        id = PREDICATE_FOLDER_NAME)
116
    self.assertTrue('Predicate' in [x.id for x in
117 118
                    predicate_folder.allowedContentTypes()])
    return predicate_folder
Jérome Perrin's avatar
Jérome Perrin committed
119 120 121 122 123

  def createPredicate(self, **kw):
    """Generic method to create a predicate"""
    return self.getPredicateFolder().newContent(
                        portal_type = 'Predicate', **kw)
124

Jérome Perrin's avatar
Jérome Perrin committed
125 126 127 128
  def createDocument(self, **kw):
    """Creates a document."""
    return self.getOrganisationModule().newContent(
                             portal_type='Organisation', **kw)
129

130 131
  def stepCreatePredicateTrueScript(self, sequence=None, **kw) :
    """Creates a script that always return true"""
132
    createZODBPythonScript(self.getPortal().portal_skins.erp5_base,
133
                           'Predicate_true', 'predicate', """return 1""")
134
    sequence.edit(test_method_id = 'Predicate_true')
135

136 137
  def stepCreatePredicateFalseScript(self, sequence=None, **kw) :
    """Creates a script that always return false"""
138
    createZODBPythonScript(self.getPortal().portal_skins.erp5_base,
139
                           'Predicate_false', '', """return 0""")
140
    sequence.edit(test_method_id = 'Predicate_false')
141

142 143 144 145
  def stepCreateTestMethodIdPredicate(self, sequence=None, **kw) :
    """Creates a predicate with a test method_id"""
    sequence.edit(predicate = self.createPredicate(
        test_method_id = sequence.get('test_method_id')))
146

147 148 149
  def stepCreateEmptyPredicate(self, sequence=None, **kw) :
    """Creates an empty predicate that is supposed to be always true"""
    sequence.edit(predicate = self.createPredicate())
150

151 152 153 154 155 156 157
  def stepCreateAlwaysFalsePredicate(self, sequence=None, **kw) :
    """Creates a predicate that is always false (membership of an non
       existant category)"""
    sequence.edit(predicate = self.createPredicate(
        membership_criterion_base_category_list = ['not_exist'],
        membership_criterion_category_list = ['not_exist/nothing']
      ))
158

159 160 161 162 163 164
  def stepCreateRegionFrancePredicate(self, sequence=None, **kw) :
    """Creates a predicate for region france category"""
    sequence.edit(predicate = self.createPredicate(
        membership_criterion_base_category_list = ['region'],
        membership_criterion_category_list = [REGION_FRANCE_PATH]
      ))
165

166 167 168 169 170 171 172 173
  def stepCreateRegionFranceTestMethodIdPredicate(
                                  self, sequence=None, **kw) :
    """Creates an region france predicate with the last test_method_id
    in the sequence"""
    sequence.edit(predicate = self.createPredicate(
        membership_criterion_base_category_list = ['region'],
        membership_criterion_category_list = [REGION_FRANCE_PATH],
        test_method_id = sequence.get('test_method_id')))
174 175


176 177 178 179 180 181
  def stepCreateGroupStoreverPredicate(self, sequence=None, **kw) :
    """Creates a predicate for group storever category"""
    sequence.edit(predicate = self.createPredicate(
        membership_criterion_base_category_list = ['group'],
        membership_criterion_category_list = [GROUP_STOREVER_PATH]
      ))
182

183 184 185 186 187 188 189 190 191
  def stepCreateGroupStoreverRegionFrancePredicate(
                                      self, sequence=None, **kw) :
    """Creates a predicate for group storever and region france
    categories"""
    sequence.edit(predicate = self.createPredicate(
        membership_criterion_base_category_list = ['group', 'region'],
        membership_criterion_category_list = [ GROUP_STOREVER_PATH,
                                               REGION_FRANCE_PATH ]
      ))
192

193 194 195 196 197 198 199 200 201 202
  def stepCreateRegionFrancePredicateTruePredicate(
                                      self, sequence=None, **kw) :
    """Creates a predicate for region france and Predicate_true script.
    """
    self.stepCreatePredicateTrueScript(sequence = sequence)
    sequence.edit(predicate = self.createPredicate(
        membership_criterion_base_category_list = ['region'],
        membership_criterion_category_list = [ REGION_FRANCE_PATH ],
        test_method_id = sequence.get('test_method_id')
      ))
203

204 205 206 207 208 209 210 211 212 213
  def stepCreateRegionFrancePredicateFalsePredicate(
                                          self, sequence=None, **kw) :
    """Creates a predicate for region france and Predicate_false script.
    """
    self.stepCreatePredicateFalseScript(sequence = sequence)
    sequence.edit(predicate = self.createPredicate(
        membership_criterion_base_category_list = ['region'],
        membership_criterion_category_list = [ REGION_FRANCE_PATH ],
        test_method_id = sequence.get('test_method_id')
      ))
214

215 216 217
  def stepSaveFirstPredicate(self, sequence=None, **kw) :
    """Save current predicate for later fusion."""
    sequence.edit(first_predicate = sequence.get('predicate'))
218

219 220 221 222 223 224 225 226
  def stepMergePredicates(self, sequence=None, **kw) :
    """Merge `first predicate` with current predicate."""
    first_predicate = sequence.get('first_predicate')
    current_predicate = sequence.get('predicate')
    first_predicate.setPredicateCategoryList(
        [ first_predicate.getRelativeUrl(),
          current_predicate.getRelativeUrl() ])
    sequence.edit(predicate = first_predicate)
227

228 229 230 231 232
  def stepCreateDocument(self, sequence=None, **kw) :
    """Creates a document."""
    doc = self.getOrganisationModule().newContent(
                                      portal_type='Organisation')
    sequence.edit(doc = doc)
233

234 235 236 237 238
  def stepSetDocumentStoreverGroupMembership(
                                self, sequence=None, **kw) :
    """Set group membership for the document."""
    doc = sequence.get('doc')
    doc.setGroup(GROUP_STOREVER_PATH.replace('group/', ''))
239

240 241 242 243
  def stepSetDocumentOtherGroupMembership(self, sequence=None, **kw) :
    """Set group membership for the document."""
    doc = sequence.get('doc')
    doc.setGroup(GROUP_OTHER_PATH.replace('group/', ''))
244

245 246 247 248
  def stepSetDocumentGermanyRegionMembership(self, sequence=None, **kw) :
    """Set region membership for the document."""
    doc = sequence.get('doc')
    doc.setRegion(REGION_GERMANY_PATH.replace('region/', ''))
249

250 251 252 253
  def stepSetDocumentFranceRegionMembership(self, sequence=None, **kw) :
    """Set region membership for the document."""
    doc = sequence.get('doc')
    doc.setRegion(REGION_FRANCE_PATH.replace('region/', ''))
254

255 256 257 258
  def stepAssertPredicateTrue(self, sequence=None, **kw) :
    """Assert the predicate is true on the document."""
    doc = sequence.get('doc')
    predicate = sequence.get('predicate')
259
    self.assertTrue(predicate.test(doc))
260

261 262 263 264 265
  def stepAssertPredicateFalse(self, sequence=None, **kw) :
    """Assert the predicate is false on the document."""
    doc = sequence.get('doc')
    predicate = sequence.get('predicate')
    self.assertFalse(predicate.test(doc))
Jérome Perrin's avatar
Jérome Perrin committed
266

267 268
class TestPredicates(TestPredicateMixIn):

269 270 271
  ############################################################################
  ## Test Methods ############################################################
  ############################################################################
272

Jérome Perrin's avatar
Jérome Perrin committed
273
  def test_Interface(self):
274
    """Test Predicate implements Predicate interface."""
275
    from Products.ERP5Type.interfaces import IPredicate
276
    from Products.ERP5Type.Core.Predicate import Predicate
277
    predicate = self.createPredicate()
278
    self.assertTrue(IPredicate.providedBy(predicate))
279
    from zope.interface.verify import verifyClass
280
    verifyClass(IPredicate, Predicate)
Jérome Perrin's avatar
Jérome Perrin committed
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302


  def test_BasicCategoryMembership(self):
    # Predicates can test that a document is member of a category
    doc = self.createDocument(region='europe/western_europe/france',)
    pred = self.createPredicate(
        membership_criterion_base_category_list=['region'],
        membership_criterion_category_list=
                      ['region/europe/western_europe/france'])
    # our document is member of france region, so the predicate is true
    self.assertTrue(pred.test(doc))


  def test_BasicCategoryMembershipNotStrict(self):
    # Predicates are not only true for strict membership, but can also be used
    # with a parent category
    doc = self.createDocument(region='europe/western_europe/france',)
    pred = self.createPredicate(
        membership_criterion_base_category_list=['region'],
        membership_criterion_category_list=['region/europe'])
    self.assertTrue(pred.test(doc))

303 304 305 306 307 308 309 310 311 312 313 314
  def test_BasicCategoryMembershipStrict(self):
    # Check that test method can take into account the strict_membership
    # parameter
    doc = self.createDocument(region='europe/western_europe/france',)
    pred = self.createPredicate(
      membership_criterion_base_category_list=['region'],
      membership_criterion_category_list=['region/europe'])
    self.assertFalse(pred.test(doc, strict_membership=1))
    pred = self.createPredicate(
      membership_criterion_base_category_list=['region'],
      membership_criterion_category_list=['region/europe/western_europe/france'])
    self.assertTrue(pred.test(doc, strict_membership=1))
Jérome Perrin's avatar
Jérome Perrin committed
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

  def test_BasicCategoryNonMembership(self):
    # if the document is not member of the category, the predicate returns
    # false
    doc = self.createDocument(region='europe/western_europe/france',)
    pred = self.createPredicate(
        membership_criterion_base_category_list=['region'],
        membership_criterion_category_list=
                ['region/europe/western_europe/germany'])
    self.assertFalse(pred.test(doc))

  def test_NonExistantCategoryMembership(self):
    # the predicate also return false for non existant category and no error is
    # raised.
    doc = self.createDocument()
    pred = self.createPredicate(
        membership_criterion_base_category_list=['not_exist'],
        membership_criterion_category_list=['not_exist/nothing'])
    self.assertFalse(pred.test(doc))

  def test_EmptyPredicates(self):
    # empty predicate are true
    doc = self.createDocument()
    pred = self.createPredicate()
    self.assertTrue(pred.test(doc))


  def test_TestMethodId(self):
    doc = self.createDocument(region='europe/western_europe/france',)
    calls = []
345
    def true_method(predicate):
Jérome Perrin's avatar
Jérome Perrin committed
346 347 348
      calls.append(True)
      return True
    doc.true_method = true_method
349
    def false_method(predicate):
Jérome Perrin's avatar
Jérome Perrin committed
350 351 352
      calls.append(False)
      return False
    doc.false_method = false_method
353

Jérome Perrin's avatar
Jérome Perrin committed
354 355 356 357 358
    # predicates can also be created with a test method id, which will be the
    # id of a method to call on the document (of course it can be a python
    # script). This method must return a boolean value.
    pred = self.createPredicate(test_method_id='true_method')
    self.assertTrue(pred.test(doc))
359
    self.assertEqual([True], calls)
Jérome Perrin's avatar
Jérome Perrin committed
360 361 362

    pred = self.createPredicate(test_method_id='false_method')
    self.assertFalse(pred.test(doc))
363
    self.assertEqual([True, False], calls)
364

Jérome Perrin's avatar
Jérome Perrin committed
365 366 367 368 369 370 371 372
    # the use of method id can be mixed with category membership, both will
    # have to be true for the predicate to be true.
    pred = self.createPredicate(
        test_method_id='true_method',
        membership_criterion_base_category_list=['region'],
        membership_criterion_category_list=
                      ['region/europe/western_europe/france'])
    self.assertTrue(pred.test(doc))
373
    self.assertEqual([True, False, True], calls)
374

Jérome Perrin's avatar
Jérome Perrin committed
375 376 377 378 379 380
    pred = self.createPredicate(
        test_method_id='false_method',
        membership_criterion_base_category_list=['region'],
        membership_criterion_category_list=
                      ['region/europe/western_europe/france'])
    self.assertFalse(pred.test(doc))
381
    self.assertEqual([True, False, True, False], calls)
382

Jérome Perrin's avatar
Jérome Perrin committed
383 384 385 386 387 388 389
    pred = self.createPredicate(
        test_method_id='true_method',
        membership_criterion_base_category_list=['region'],
        membership_criterion_category_list=['region/other'])
    self.assertFalse(pred.test(doc))
    # Note that if the document is not member of the category, the test_method
    # is not called.
390
    self.assertEqual([True, False, True, False], calls)
391

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

393 394 395 396 397 398
  def test_Predicate_getMembershipCriterionCategoryList(self):
    # Predicate_getMembershipCriterionCategoryList is a script used to show the
    # item list in Predicate_view/my_membership_criterion_category_list.
    # When called on a predicate using a simple category (like region) as
    # membership criterion base category, it will show for values the content
    # of this category.
399 400
    source_region_chile_list_before = self.portal.portal_categories.source_region.\
                                      getCategoryChildCompactLogicalPathItemList(base=1)[:]
401 402
    pred = self.createPredicate(
        membership_criterion_base_category_list=['region'], )
403
    self.assertTrue(('europe/western_europe', 'region/europe/western_europe') in
404 405
        [tuple(x) for x in pred.Predicate_getMembershipCriterionCategoryList()],
        pred.Predicate_getMembershipCriterionCategoryList(),)
406

407 408 409 410 411 412 413
    # If this category is empty, it will show values from fallback category,
    # with the path they have when they are acquired
    pred = self.createPredicate(
        membership_criterion_base_category_list=['source_region'], )
    # note that the id of the actual base category is displayed in the first
    # item too, for making it clear in the UI that it's the content of a
    # category used for another base category.
414
    self.assertTrue(('region/europe/western_europe',
415 416 417
                     'source_region/region/europe/western_europe') in
        [tuple(x) for x in pred.Predicate_getMembershipCriterionCategoryList()],
        pred.Predicate_getMembershipCriterionCategoryList(),)
418 419
    source_region_chile_list_after = self.portal.portal_categories.source_region.\
                                     getCategoryChildCompactLogicalPathItemList(base=1)[:]
420
    self.assertEqual(source_region_chile_list_before, source_region_chile_list_after)
421 422


423
  def test_PredicateFusion(self, quiet=QUIET, run=RUN_ALL_TESTS):
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    """Test simple predicates fusion.
    New predicate act as a logical AND between predicates
    """
    if not run : return
    # if both predicates are true, resulting predicate is true
    self.playSequence("""
      stepCreateDocument
      stepSetDocumentFranceRegionMembership
      stepSetDocumentStoreverGroupMembership
      stepCreateRegionFrancePredicate
      stepSaveFirstPredicate
      stepCreateGroupStoreverPredicate
      stepMergePredicates
      stepAssertPredicateTrue
    """)
    # if a predicate is false, resulting predicate is false
    self.playSequence("""
      stepCreateDocument
      stepSetDocumentGermanyRegionMembership
      stepSetDocumentStoreverGroupMembership
      stepCreateRegionFrancePredicate
      stepSaveFirstPredicate
      stepCreateGroupStoreverPredicate
      stepMergePredicates
      stepAssertPredicateFalse
    """)

451
  def test_PredicateFusionAndTestMethodId(self, quiet=QUIET, run=RUN_ALL_TESTS):
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
    """Test predicates fusion and test_method_id attribute."""
    if not run : return
    self.playSequence("""
      stepCreateDocument
      stepSetDocumentFranceRegionMembership
      stepCreateRegionFrancePredicate
      stepSaveFirstPredicate
      stepCreatePredicateTrueScript
      stepCreateTestMethodIdPredicate
      stepMergePredicates
      stepAssertPredicateTrue
    """)
    self.playSequence("""
      stepCreateDocument
      stepSetDocumentFranceRegionMembership
      stepCreateRegionFrancePredicate
      stepSaveFirstPredicate
      stepCreatePredicateFalseScript
      stepCreateTestMethodIdPredicate
      stepMergePredicates
      stepAssertPredicateFalse
    """)
    # reverse predicate order, to make sure not only the last one is
    # checked
    self.playSequence("""
      stepCreateDocument
      stepSetDocumentFranceRegionMembership
      stepCreatePredicateFalseScript
      stepCreateTestMethodIdPredicate
      stepSaveFirstPredicate
      stepCreateRegionFrancePredicate
      stepMergePredicates
      stepAssertPredicateFalse
    """)
    # if multiple scripts are defined, they must all return true.
    self.playSequence("""
      stepCreateDocument
      stepSetDocumentFranceRegionMembership
      stepCreatePredicateFalseScript
      stepCreateTestMethodIdPredicate
      stepSaveFirstPredicate
      stepCreatePredicateTrueScript
      stepCreateTestMethodIdPredicate
      stepMergePredicates
      stepAssertPredicateFalse
    """)
    # same in reverse order
    self.playSequence("""
      stepCreateDocument
      stepSetDocumentFranceRegionMembership
      stepCreatePredicateTrueScript
      stepCreateTestMethodIdPredicate
      stepSaveFirstPredicate
      stepCreatePredicateFalseScript
      stepCreateTestMethodIdPredicate
      stepMergePredicates
      stepAssertPredicateFalse
    """)

511 512 513 514 515 516
  def test_MembershipCriterion_SQLQuery(self, quiet=QUIET, run=RUN_ALL_TESTS):
    """
    Make sure that predicate generate valid sql.
    """
    if not run : return

Yusei Tahara's avatar
Yusei Tahara committed
517 518 519 520 521
    def test(function):
      """make sure that an exception is not raised"""
      function()
      return True

522 523
    predicate_without_membership_values = self.createPredicate(
      membership_criterion_base_category_list=['group'])
Yusei Tahara's avatar
Yusei Tahara committed
524
    self.assert_(test(predicate_without_membership_values.searchResults))
525 526 527 528 529

    predicate_with_membership_values = self.createPredicate(
      membership_criterion_base_category_list=['group'],
      membership_criterion_category_list=GROUP_STOREVER_PATH,
      )
Yusei Tahara's avatar
Yusei Tahara committed
530
    self.assert_(test(predicate_with_membership_values.searchResults))
531 532 533 534 535 536 537

  def test_MultiValuedMembershipCriterion_SQLQuery(self, quiet=QUIET, run=RUN_ALL_TESTS):
    """
    Make sure that predicate generate valid sql.
    """
    if not run : return

Yusei Tahara's avatar
Yusei Tahara committed
538 539 540 541 542
    def test(function):
      """make sure that an exception is not raised"""
      function()
      return True

543 544
    predicate_without_membership_values = self.createPredicate(
      multimembership_criterion_base_category_list=['group'])
Yusei Tahara's avatar
Yusei Tahara committed
545
    self.assert_(test(predicate_without_membership_values.searchResults))
546 547 548 549 550

    predicate_with_membership_values = self.createPredicate(
      multimembership_criterion_base_category_list=['group'],
      membership_criterion_category_list=GROUP_STOREVER_PATH,
      )
Yusei Tahara's avatar
Yusei Tahara committed
551
    self.assert_(test(predicate_with_membership_values.searchResults))
552

553
  def test_PropertyCriterion(self):
554
    movement = self.portal.newContent(temp_object=True, portal_type='Movement', id='tmp')
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
    predicate = self.createPredicate()
    predicate.setCriterionPropertyList(['quantity'])
    request = self.portal.REQUEST
    request.set(
      'listbox',
      {'quantity': {'max': '', 'identity': [], 'min': ''}},
    )
    predicate.Predicate_edit('Predicate_view')
    self.assertEqual(predicate._identity_criterion, {'quantity': []})
    self.assertEqual(predicate._range_criterion, {})
    self.assertTrue(predicate.test(movement))
    request.set(
      'listbox',
      {'quantity': {'max': '', 'identity': [], 'min': 1.0}},
    )
    predicate.Predicate_edit('Predicate_view')
    self.assertEqual(predicate._range_criterion, {'quantity': (1.0, None)})
    self.assertFalse(predicate.test(movement.asContext(quantity=0.5)))
    self.assertTrue(predicate.test(movement.asContext(quantity=1.0)))
    request.set(
      'listbox',
      {'quantity': {'max': 2.0, 'identity': [], 'min': ''}},
    )
    predicate.Predicate_edit('Predicate_view')
    self.assertEqual(predicate._range_criterion, {'quantity': (None, 2.0)})
    self.assertFalse(predicate.test(movement.asContext(quantity=2.0)))
    self.assertTrue(predicate.test(movement.asContext(quantity=1.5)))
    request.set(
      'listbox',
      {'quantity': {'max': 2.0, 'identity': [], 'min': 1.0}},
    )
    predicate.Predicate_edit('Predicate_view')
    self.assertEqual(predicate._range_criterion, {'quantity': (1.0, 2.0)})
    self.assertFalse(predicate.test(movement.asContext(quantity=0.5)))
    self.assertTrue(predicate.test(movement.asContext(quantity=1.0)))
    self.assertTrue(predicate.test(movement.asContext(quantity=1.5)))
    self.assertFalse(predicate.test(movement.asContext(quantity=2.0)))

Sebastien Robin's avatar
Sebastien Robin committed
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
  def test_searchResultsWithParameters(self):
    """
    Check that we can restrict filter used by predicate passing parameters to
    searchResults.
    """
    # create one person and one organisation
    person_module = self.portal.getDefaultModule('Person')
    fabien = person_module.newContent(title='Fabien')
    organisation_module = self.portal.getDefaultModule('Organisation')
    nexedi = organisation_module.newContent(title='Nexedi')

    predicate = self.createPredicate(criterion_property_list=['portal_type'])
    predicate.setCriterion('portal_type', ['Person', 'Organisation'])
    self.tic()

    # check that if we define the same filter than on predicate we get same result
609
    self.assertEqual(len(predicate.searchResults()), 2)
610 611
    self.assertEqual({fabien, nexedi}, {x.getObject()
      for x in predicate.searchResults(portal_type=('Person', 'Organisation'))})
Sebastien Robin's avatar
Sebastien Robin committed
612 613

    # check that it's possible to filter results
614
    self.assertEqual([x.getObject() for x in \
Sebastien Robin's avatar
Sebastien Robin committed
615
      predicate.searchResults(portal_type='Person')], [fabien])
616
    self.assertEqual([x.getObject() for x in \
Sebastien Robin's avatar
Sebastien Robin committed
617 618 619 620 621
        predicate.searchResults(portal_type='Organisation')], [nexedi])

    # check that if the filter define more properties, we cannot have more than
    # the one defined on the predicate
    currency_module = self.portal.getDefaultModule('Currency')
622
    currency_module.newContent(title='euro')
Sebastien Robin's avatar
Sebastien Robin committed
623

624 625
    self.assertEqual({fabien, nexedi}, {x.getObject()
      for x in predicate.searchResults(portal_type=('Person', 'Organisation'))})
Sebastien Robin's avatar
Sebastien Robin committed
626

627 628 629 630 631 632 633 634 635 636 637 638 639
  def test_TalesExpression(self):
    # Predicates can test that a document is member of a category
    doc = self.createDocument(region='europe/western_europe/france',)

    pred_false = self.createPredicate(
        test_tales_expression="python: 'japan' in here.getRegion()")
    # our document is member of france region, so the predicate is false
    self.assertFalse(pred_false.test(doc))

    pred_true = self.createPredicate(
        test_tales_expression="python: 'france' in here.getRegion()")
    self.assertTrue(pred_true.test(doc))

640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
  def testPredicateViewWithOutModification(self):
    """ Make sure Predicate_view wihout modification does not change
        the object."""
    predicate = self.createPredicate()
    # when init Predicate, they are  nothing
    self.assertTrue(getattr(predicate, '_identity_criterion', None) is None)
    self.assertTrue(getattr(predicate, '_range_criterion', None) is None)
    # just view it, does not create PersistentMapping
    predicate.Predicate_view()
    self.assertTrue(getattr(predicate, '_identity_criterion', None) is None)
    self.assertTrue(getattr(predicate, '_range_criterion', None) is None)
    # add property and view it, creates PersistentMapping
    predicate.setCriterionPropertyList(['quantity'])
    predicate.Predicate_view()
    self.assertFalse(getattr(predicate, '_identity_criterion', None) is None)
    self.assertFalse(getattr(predicate, '_range_criterion', None) is None)
Sebastien Robin's avatar
Sebastien Robin committed
656

657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
    
  def test_predicateIndexation(self):
    predicate = self.createPredicate(
      membership_criterion_base_category_list = ['region'],
      membership_criterion_category_list = [REGION_FRANCE_PATH]
    )
    # Our test document will only be a predicate if title is different
    # from 'never applies'
    createZODBPythonScript(
      self.portal.portal_skins.custom,
      'Predicate_asPredicate',
      '',
      """return None if context.getTitle() == 'never applies' else context""")
    self.tic()

    self.assertEqual(
      [predicate],
      [brain.getObject() for brain in self.portal.portal_catalog(
        **{'predicate.uid': predicate.getUid()})])
    self.assertEqual(
      [predicate],
      [brain.getObject() for brain in self.portal.portal_catalog(
        **{'predicate_category.uid': predicate.getUid()})])

    predicate.setTitle("never applies")
    # this predicate is no longer a predicate, so it no longer exist in predicate tables
    self.tic()

    self.assertEqual(
      [],
      [brain.getObject() for brain in self.portal.portal_catalog(
        **{'predicate.uid': predicate.getUid()})])
    self.assertEqual(
      [],
      [brain.getObject() for brain in self.portal.portal_catalog(
        **{'predicate_category.uid': predicate.getUid()})])


695 696
# TODO :
#  multi membership category
Jérome Perrin's avatar
Jérome Perrin committed
697
#  asPredicate scripts
698 699 700 701
#  predicate range
#  predicate + category fusion using setPredicateCategoryList
#  predicate matrix ?

Jérome Perrin's avatar
Jérome Perrin committed
702 703 704 705
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestPredicates))
  return suite
706