testBase.py 51 KB
Newer Older
1
# -*- coding: utf-8 -*-
Romain Courteaud's avatar
Romain Courteaud committed
2 3
##############################################################################
#
4 5
# Copyright (c) 2004, 2005, 2006 Nexedi SARL and Contributors. 
# All Rights Reserved.
Romain Courteaud's avatar
Romain Courteaud committed
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
#          Romain Courteaud <romain@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.
#
##############################################################################

31
import unittest
32
import os
Romain Courteaud's avatar
Romain Courteaud committed
33

34 35
import transaction

36
from Testing import ZopeTestCase
Romain Courteaud's avatar
Romain Courteaud committed
37
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
Jérome Perrin's avatar
Jérome Perrin committed
38 39
from AccessControl.SecurityManagement import newSecurityManager
from Products.ERP5Type.tests.Sequence import SequenceList
40
from zExceptions import BadRequest
41
from Products.ERP5Type.tests.backportUnittest import skip
42
from Products.ERP5Type.Tool.ClassTool import _aq_reset
Romain Courteaud's avatar
Romain Courteaud committed
43

44
class TestBase(ERP5TypeTestCase, ZopeTestCase.Functional):
Romain Courteaud's avatar
Romain Courteaud committed
45

Romain Courteaud's avatar
Romain Courteaud committed
46
  run_all_test = 1
Jérome Perrin's avatar
Jérome Perrin committed
47 48
  quiet = 1

Romain Courteaud's avatar
Romain Courteaud committed
49
  object_portal_type = "Organisation"
50 51
  not_defined_property_id = "azerty_qwerty"
  not_defined_property_value = "qwerty_azerty"
Romain Courteaud's avatar
Romain Courteaud committed
52

53 54 55
  temp_class = "Amount"
  defined_property_id = "title"
  defined_property_value = "a_wonderful_title"
56
  not_related_to_temp_object_property_id = "string_index"
57
  not_related_to_temp_object_property_value = "a_great_index"
58 59
  
  username = 'rc'
60

Romain Courteaud's avatar
Romain Courteaud committed
61 62 63 64 65 66
  def getTitle(self):
    return "Base"

  def getBusinessTemplateList(self):
    """
    """
Sebastien Robin's avatar
Sebastien Robin committed
67
    return ('erp5_base',)
Romain Courteaud's avatar
Romain Courteaud committed
68

69
  def login(self):
Romain Courteaud's avatar
Romain Courteaud committed
70
    uf = self.getPortal().acl_users
71 72
    uf._doAddUser(self.username, '', ['Manager'], [])
    user = uf.getUserById(self.username).__of__(uf)
Romain Courteaud's avatar
Romain Courteaud committed
73 74
    newSecurityManager(None, user)

75
  def afterSetUp(self):
Romain Courteaud's avatar
Romain Courteaud committed
76 77 78 79 80 81 82
    self.login()
    portal = self.getPortal()
    self.category_tool = self.getCategoryTool()
    portal_catalog = self.getCatalogTool()
    #portal_catalog.manage_catalogClear()
    self.createCategories()

83 84 85 86 87 88 89 90 91 92 93 94 95
    #Overwrite immediateReindexObject() with a crashing method
    def crashingMethod(self):
      self.ImmediateReindexObjectIsCalled()
    from Products.ERP5Type.Document.Organisation import Organisation
    Organisation.immediateReindexObject = crashingMethod
    Organisation.recursiveImmediateReindexObject = crashingMethod

  def beforeTearDown(self):
    # Remove crashing method
    from Products.ERP5Type.Document.Organisation import Organisation
    del Organisation.immediateReindexObject
    del Organisation.recursiveImmediateReindexObject

Romain Courteaud's avatar
Romain Courteaud committed
96 97 98 99 100
  def createCategories(self):
    """ 
      Light install create only base categories, so we create 
      some categories for testing them
    """
Romain Courteaud's avatar
Romain Courteaud committed
101
    category_list = ['testGroup1', 'testGroup2']
102
    if 'testGroup1' not in self.category_tool.group.contentIds():
Romain Courteaud's avatar
Romain Courteaud committed
103 104 105
      for category_id in category_list:
        o = self.category_tool.group.newContent(portal_type='Category',
                                                id=category_id)
Romain Courteaud's avatar
Romain Courteaud committed
106

Romain Courteaud's avatar
Romain Courteaud committed
107 108
  def stepRemoveWorkflowsRelated(self, sequence=None, sequence_list=None, 
                                 **kw):
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    """
      Remove workflow related to the portal type
    """
    self.getWorkflowTool().setChainForPortalTypes(
        ['Organisation'], ())
    _aq_reset()

  def stepAssociateWorkflows(self, sequence=None, sequence_list=None, **kw):
    """
      Associate workflow to the portal type
    """
    self.getWorkflowTool().setChainForPortalTypes(
        ['Organisation'], ('validation_workflow', 'edit_workflow'))
    _aq_reset()

Romain Courteaud's avatar
Romain Courteaud committed
124 125
  def stepAssociateWorkflowsExcludingEdit(self, sequence=None, 
                                          sequence_list=None, **kw):
126 127 128 129 130 131 132
    """
      Associate workflow to the portal type
    """
    self.getWorkflowTool().setChainForPortalTypes(
        ['Organisation'], ('validation_workflow',))
    _aq_reset()

Romain Courteaud's avatar
Romain Courteaud committed
133 134
  def stepCreateObject(self, sequence=None, sequence_list=None, **kw):
    """
Romain Courteaud's avatar
Romain Courteaud committed
135
      Create a object_instance which will be tested.
Romain Courteaud's avatar
Romain Courteaud committed
136 137 138
    """
    portal = self.getPortal()
    module = portal.getDefaultModule(self.object_portal_type)
Romain Courteaud's avatar
Romain Courteaud committed
139
    object_instance = module.newContent(portal_type=self.object_portal_type)
Romain Courteaud's avatar
Romain Courteaud committed
140
    sequence.edit(
Romain Courteaud's avatar
Romain Courteaud committed
141
        object_instance=object_instance,
142
        current_title=object_instance.getId(), # title defaults to id
Romain Courteaud's avatar
Romain Courteaud committed
143
        current_group_value=None
Romain Courteaud's avatar
Romain Courteaud committed
144 145 146 147 148 149
    )

  def stepCheckTitleValue(self, sequence=None, sequence_list=None, **kw):
    """
      Check if getTitle return a correect value
    """
Romain Courteaud's avatar
Romain Courteaud committed
150
    object_instance = sequence.get('object_instance')
Romain Courteaud's avatar
Romain Courteaud committed
151
    current_title = sequence.get('current_title')
Romain Courteaud's avatar
Romain Courteaud committed
152
    self.assertEquals(object_instance.getTitle(), current_title)
Romain Courteaud's avatar
Romain Courteaud committed
153

Romain Courteaud's avatar
Romain Courteaud committed
154 155
  def stepSetDifferentTitleValueWithEdit(self, sequence=None, 
                                         sequence_list=None, **kw):
Romain Courteaud's avatar
Romain Courteaud committed
156 157 158
    """
      Set a different title value
    """
Romain Courteaud's avatar
Romain Courteaud committed
159
    object_instance = sequence.get('object_instance')
Romain Courteaud's avatar
Romain Courteaud committed
160 161
    current_title = sequence.get('current_title')
    new_title_value = '%s_a' % current_title
Romain Courteaud's avatar
Romain Courteaud committed
162
    object_instance.edit(title=new_title_value)
Romain Courteaud's avatar
Romain Courteaud committed
163 164 165 166 167 168 169 170 171 172
    sequence.edit(
        current_title=new_title_value
    )

  def stepCheckIfActivitiesAreCreated(self, sequence=None, sequence_list=None,
                                      **kw):
    """
      Check if there is a activity in activity queue.
    """
    portal = self.getPortal()
173
    transaction.commit()
Romain Courteaud's avatar
Romain Courteaud committed
174
    message_list = portal.portal_activities.getMessageList()
175 176 177 178 179 180 181 182
    method_id_list = [x.method_id for x in message_list]
    # XXX FIXME: how many activities should be created normally ?
    # Sometimes it's one, sometimes 2...
    self.failUnless(len(message_list) > 0)
    self.failUnless(len(message_list) < 3)
    for method_id in method_id_list:
      self.failUnless(method_id in ["immediateReindexObject", 
                                    "recursiveImmediateReindexObject"])
Romain Courteaud's avatar
Romain Courteaud committed
183

Romain Courteaud's avatar
Romain Courteaud committed
184 185
  def stepSetSameTitleValueWithEdit(self, sequence=None, sequence_list=None, 
                                    **kw):
Romain Courteaud's avatar
Romain Courteaud committed
186 187 188
    """
      Set a different title value
    """
Romain Courteaud's avatar
Romain Courteaud committed
189 190
    object_instance = sequence.get('object_instance')
    object_instance.edit(title=object_instance.getTitle())
Romain Courteaud's avatar
Romain Courteaud committed
191 192 193 194 195 196 197 198 199 200

  def stepCheckIfMessageQueueIsEmpty(self, sequence=None, 
                                     sequence_list=None, **kw):
    """
      Check if there is no activity in activity queue.
    """
    portal = self.getPortal()
    message_list = portal.portal_activities.getMessageList()
    self.assertEquals(len(message_list), 0)

Jérome Perrin's avatar
Jérome Perrin committed
201
  def test_01_areActivitiesWellLaunchedByPropertyEdit(self, quiet=quiet,
Romain Courteaud's avatar
Romain Courteaud committed
202
                                                      run=run_all_test):
Romain Courteaud's avatar
Romain Courteaud committed
203
    """
204 205
      Test if setter does not call a activity if the attribute 
      value is not changed.
Romain Courteaud's avatar
Romain Courteaud committed
206 207 208
    """
    if not run: return
    sequence_list = SequenceList()
209 210 211 212
    # Test without workflows associated to the portal type
    sequence_string = '\
              RemoveWorkflowsRelated \
              CreateObject \
Romain Courteaud's avatar
Romain Courteaud committed
213
              Tic \
214
              CheckTitleValue \
Romain Courteaud's avatar
Romain Courteaud committed
215
              SetDifferentTitleValueWithEdit \
216 217 218 219
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
Romain Courteaud's avatar
Romain Courteaud committed
220
              SetSameTitleValueWithEdit \
221
              CheckTitleValue \
222
              CheckIfMessageQueueIsEmpty \
Romain Courteaud's avatar
Romain Courteaud committed
223
              SetDifferentTitleValueWithEdit \
224 225 226 227 228 229 230 231 232 233
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              '
    sequence_list.addSequenceString(sequence_string)
    # Test with workflows associated to the portal type
    sequence_string = '\
              AssociateWorkflows \
              CreateObject \
Romain Courteaud's avatar
Romain Courteaud committed
234
              Tic \
Romain Courteaud's avatar
Romain Courteaud committed
235
              CheckTitleValue \
Romain Courteaud's avatar
Romain Courteaud committed
236
              SetDifferentTitleValueWithEdit \
Romain Courteaud's avatar
Romain Courteaud committed
237 238 239 240
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
Romain Courteaud's avatar
Romain Courteaud committed
241
              SetSameTitleValueWithEdit \
242 243 244
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
Romain Courteaud's avatar
Romain Courteaud committed
245
              CheckIfMessageQueueIsEmpty \
Romain Courteaud's avatar
Romain Courteaud committed
246
              SetDifferentTitleValueWithEdit \
Romain Courteaud's avatar
Romain Courteaud committed
247 248 249 250 251 252
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              '
    sequence_list.addSequenceString(sequence_string)
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
    # Test with workflows associated to the portal type, excluding edit_workflow
    sequence_string = '\
              AssociateWorkflowsExcludingEdit \
              CreateObject \
              Tic \
              CheckTitleValue \
              SetDifferentTitleValueWithEdit \
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              SetSameTitleValueWithEdit \
              CheckIfMessageQueueIsEmpty \
              CheckTitleValue \
              SetDifferentTitleValueWithEdit \
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              '
    sequence_list.addSequenceString(sequence_string)
Jérome Perrin's avatar
Jérome Perrin committed
274
    sequence_list.play(self, quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
275

Romain Courteaud's avatar
Romain Courteaud committed
276 277 278 279
  def stepCheckGroupValue(self, sequence=None, sequence_list=None, **kw):
    """
      Check if getTitle return a correect value
    """
Romain Courteaud's avatar
Romain Courteaud committed
280
    object_instance = sequence.get('object_instance')
Romain Courteaud's avatar
Romain Courteaud committed
281
    current_group_value = sequence.get('current_group_value')
Romain Courteaud's avatar
Romain Courteaud committed
282
    self.assertEquals(object_instance.getGroupValue(), current_group_value)
Romain Courteaud's avatar
Romain Courteaud committed
283 284 285 286 287 288

  def stepSetDifferentGroupValueWithEdit(self, sequence=None, 
                                         sequence_list=None, **kw):
    """
      Set a different title value
    """
Romain Courteaud's avatar
Romain Courteaud committed
289
    object_instance = sequence.get('object_instance')
Romain Courteaud's avatar
Romain Courteaud committed
290
    current_group_value = sequence.get('current_group_value')
Romain Courteaud's avatar
Romain Courteaud committed
291 292 293 294
    group1 = object_instance.portal_categories.\
                       restrictedTraverse('group/testGroup1')
    group2 = object_instance.portal_categories.\
                       restrictedTraverse('group/testGroup2')
Romain Courteaud's avatar
Romain Courteaud committed
295 296 297 298 299 300
    if (current_group_value is None) or \
       (current_group_value == group2) :
      new_group_value = group1
    else:
      new_group_value = group2
#     new_group_value = '%s_a' % current_title
Romain Courteaud's avatar
Romain Courteaud committed
301
    object_instance.edit(group_value=new_group_value)
Romain Courteaud's avatar
Romain Courteaud committed
302 303 304 305 306 307 308 309 310
    sequence.edit(
        current_group_value=new_group_value
    )

  def stepSetSameGroupValueWithEdit(self, sequence=None, sequence_list=None, 
                                    **kw):
    """
      Set a different title value
    """
Romain Courteaud's avatar
Romain Courteaud committed
311 312
    object_instance = sequence.get('object_instance')
    object_instance.edit(group_value=object_instance.getGroupValue())
Romain Courteaud's avatar
Romain Courteaud committed
313 314


Jérome Perrin's avatar
Jérome Perrin committed
315
  def test_02_areActivitiesWellLaunchedByCategoryEdit(self, quiet=quiet,
Romain Courteaud's avatar
Romain Courteaud committed
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 345 346 347 348
                                                      run=run_all_test):
    """
      Test if setter does not call a activity if the attribute 
      value is not changed.
    """
    if not run: return
    sequence_list = SequenceList()
    # Test without workflows associated to the portal type
    sequence_string = '\
              RemoveWorkflowsRelated \
              CreateObject \
              Tic \
              CheckGroupValue \
              SetDifferentGroupValueWithEdit \
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              SetSameGroupValueWithEdit \
              CheckIfMessageQueueIsEmpty \
              SetDifferentGroupValueWithEdit \
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              '
    sequence_list.addSequenceString(sequence_string)
    # Test with workflows associated to the portal type
    sequence_string = '\
              AssociateWorkflows \
              CreateObject \
              Tic \
              CheckGroupValue \
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
              SetDifferentGroupValueWithEdit \
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              SetSameGroupValueWithEdit \
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              SetDifferentGroupValueWithEdit \
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              '
    sequence_list.addSequenceString(sequence_string)
    # Test with workflows associated to the portal type, excluding edit_workflow
    sequence_string = '\
              AssociateWorkflowsExcludingEdit \
              CreateObject \
              Tic \
              CheckGroupValue \
Romain Courteaud's avatar
Romain Courteaud committed
372 373 374 375 376 377 378 379 380 381 382 383 384 385
              SetDifferentGroupValueWithEdit \
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              SetSameGroupValueWithEdit \
              CheckIfMessageQueueIsEmpty \
              SetDifferentGroupValueWithEdit \
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              '
    sequence_list.addSequenceString(sequence_string)
Jérome Perrin's avatar
Jérome Perrin committed
386
    sequence_list.play(self, quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
387 388 389 390 391 392

  def stepSetDifferentTitleValueWithSetter(self, sequence=None, 
                                           sequence_list=None, **kw):
    """
      Set a different title value
    """
Romain Courteaud's avatar
Romain Courteaud committed
393
    object_instance = sequence.get('object_instance')
Romain Courteaud's avatar
Romain Courteaud committed
394 395
    current_title = sequence.get('current_title')
    new_title_value = '%s_a' % current_title
Romain Courteaud's avatar
Romain Courteaud committed
396
    object_instance.setTitle(new_title_value)
Romain Courteaud's avatar
Romain Courteaud committed
397 398 399 400 401 402 403 404 405
    sequence.edit(
        current_title=new_title_value
    )

  def stepSetSameTitleValueWithSetter(self, sequence=None, 
                                      sequence_list=None, **kw):
    """
      Set a different title value
    """
Romain Courteaud's avatar
Romain Courteaud committed
406 407
    object_instance = sequence.get('object_instance')
    object_instance.setTitle(object_instance.getTitle())
Romain Courteaud's avatar
Romain Courteaud committed
408

Jérome Perrin's avatar
Jérome Perrin committed
409
  def test_03_areActivitiesWellLaunchedByPropertySetter(self, quiet=quiet,
Romain Courteaud's avatar
Romain Courteaud committed
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
                                                        run=run_all_test):
    """
      Test if setter does not call a activity if the attribute 
      value is not changed.
    """
    if not run: return
    sequence_list = SequenceList()
    # Test without workflows associated to the portal type
    sequence_string = '\
              RemoveWorkflowsRelated \
              CreateObject \
              Tic \
              CheckTitleValue \
              SetDifferentTitleValueWithSetter \
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              SetSameTitleValueWithSetter \
429 430 431
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
Romain Courteaud's avatar
Romain Courteaud committed
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
              CheckIfMessageQueueIsEmpty \
              SetDifferentTitleValueWithSetter \
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              '
    sequence_list.addSequenceString(sequence_string)
    # Test with workflows associated to the portal type
    sequence_string = '\
              AssociateWorkflows \
              CreateObject \
              Tic \
              CheckTitleValue \
              SetDifferentTitleValueWithSetter \
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              SetSameTitleValueWithSetter \
452 453 454
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
Romain Courteaud's avatar
Romain Courteaud committed
455 456 457 458 459 460 461 462
              CheckIfMessageQueueIsEmpty \
              SetDifferentTitleValueWithSetter \
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              '
    sequence_list.addSequenceString(sequence_string)
Jérome Perrin's avatar
Jérome Perrin committed
463
    sequence_list.play(self, quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
464 465 466 467 468 469

  def stepSetDifferentGroupValueWithSetter(self, sequence=None, 
                                           sequence_list=None, **kw):
    """
      Set a different title value
    """
Romain Courteaud's avatar
Romain Courteaud committed
470
    object_instance = sequence.get('object_instance')
Romain Courteaud's avatar
Romain Courteaud committed
471
    current_group_value = sequence.get('current_group_value')
Romain Courteaud's avatar
Romain Courteaud committed
472 473 474 475
    group1 = object_instance.portal_categories.\
                                   restrictedTraverse('group/testGroup1')
    group2 = object_instance.portal_categories.\
                                   restrictedTraverse('group/testGroup2')
Romain Courteaud's avatar
Romain Courteaud committed
476 477 478 479 480 481
    if (current_group_value is None) or \
       (current_group_value == group2) :
      new_group_value = group1
    else:
      new_group_value = group2
#     new_group_value = '%s_a' % current_title
Romain Courteaud's avatar
Romain Courteaud committed
482
    object_instance.setGroupValue(new_group_value)
Romain Courteaud's avatar
Romain Courteaud committed
483 484 485 486 487 488 489 490 491
    sequence.edit(
        current_group_value=new_group_value
    )

  def stepSetSameGroupValueWithSetter(self, sequence=None, 
                                      sequence_list=None, **kw):
    """
      Set a different title value
    """
Romain Courteaud's avatar
Romain Courteaud committed
492 493
    object_instance = sequence.get('object_instance')
    object_instance.setGroupValue(object_instance.getGroupValue())
Romain Courteaud's avatar
Romain Courteaud committed
494

Jérome Perrin's avatar
Jérome Perrin committed
495
  def test_04_areActivitiesWellLaunchedByCategorySetter(self, quiet=quiet,
Romain Courteaud's avatar
Romain Courteaud committed
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
                                                        run=run_all_test):
    """
      Test if setter does not call a activity if the attribute 
      value is not changed.
    """
    if not run: return
    sequence_list = SequenceList()
    # Test without workflows associated to the portal type
    sequence_string = '\
              RemoveWorkflowsRelated \
              CreateObject \
              Tic \
              CheckGroupValue \
              SetDifferentGroupValueWithSetter \
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              SetSameGroupValueWithSetter \
515 516 517
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
Romain Courteaud's avatar
Romain Courteaud committed
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
              CheckIfMessageQueueIsEmpty \
              SetDifferentGroupValueWithSetter \
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              '
    sequence_list.addSequenceString(sequence_string)
    # Test with workflows associated to the portal type
    sequence_string = '\
              AssociateWorkflows \
              CreateObject \
              Tic \
              CheckGroupValue \
              SetDifferentGroupValueWithSetter \
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              SetSameGroupValueWithSetter \
538 539 540
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
Romain Courteaud's avatar
Romain Courteaud committed
541 542 543 544 545 546 547 548
              CheckIfMessageQueueIsEmpty \
              SetDifferentGroupValueWithSetter \
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              '
    sequence_list.addSequenceString(sequence_string)
Jérome Perrin's avatar
Jérome Perrin committed
549
    sequence_list.play(self, quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
550

551 552 553
  def stepSetObjectNotDefinedProperty(self, sequence=None, 
                                      sequence_list=None, **kw):
    """
Romain Courteaud's avatar
Romain Courteaud committed
554
    Set a not defined property on the object_instance.
555
    """
Romain Courteaud's avatar
Romain Courteaud committed
556 557
    object_instance = sequence.get('object_instance')
    object_instance.setProperty(self.not_defined_property_id,
558 559 560 561 562
                       self.not_defined_property_value)

  def stepCheckNotDefinedPropertySaved(self, sequence=None, 
                                       sequence_list=None, **kw):
    """
Romain Courteaud's avatar
Romain Courteaud committed
563
    Check if a not defined property is stored on the object_instance.
564
    """
Romain Courteaud's avatar
Romain Courteaud committed
565
    object_instance = sequence.get('object_instance')
566
    self.assertEquals(self.not_defined_property_value,
Romain Courteaud's avatar
Romain Courteaud committed
567
                      getattr(object_instance, self.not_defined_property_id))
568 569 570 571 572 573

  def stepCheckGetNotDefinedProperty(self, sequence=None, 
                                     sequence_list=None, **kw):
    """
    Check getProperty with a not defined property.
    """
Romain Courteaud's avatar
Romain Courteaud committed
574
    object_instance = sequence.get('object_instance')
575
    self.assertEquals(self.not_defined_property_value,
Romain Courteaud's avatar
Romain Courteaud committed
576
                    object_instance.getProperty(self.not_defined_property_id))
577 578 579 580

  def stepCheckObjectPortalType(self, sequence=None, 
                                sequence_list=None, **kw):
    """
Romain Courteaud's avatar
Romain Courteaud committed
581
    Check the portal type of the object_instance.
582
    """
Romain Courteaud's avatar
Romain Courteaud committed
583 584
    object_instance = sequence.get('object_instance')
    object_instance.getPortalType()
585
    self.assertEquals(self.object_portal_type,
Romain Courteaud's avatar
Romain Courteaud committed
586
                      object_instance.getPortalType())
587 588 589

  def stepCreateTempObject(self, sequence=None, sequence_list=None, **kw):
    """
Romain Courteaud's avatar
Romain Courteaud committed
590
      Create a temp object_instance which will be tested.
591 592 593 594 595
    """
    portal = self.getPortal()
    from Products.ERP5Type.Document import newTempOrganisation
    tmp_object = newTempOrganisation(portal, "a_wonderful_id")
    sequence.edit(
Romain Courteaud's avatar
Romain Courteaud committed
596
        object_instance=tmp_object,
597 598 599 600
        current_title='',
        current_group_value=None
    )

Jérome Perrin's avatar
Jérome Perrin committed
601
  def test_05_getPropertyWithoutPropertySheet(self, quiet=quiet, run=run_all_test):
602 603 604 605 606
    """
    Test if set/getProperty work without any property sheet.
    """
    if not run: return
    sequence_list = SequenceList()
Romain Courteaud's avatar
Romain Courteaud committed
607
    # Test on object_instance.
608 609 610 611 612 613 614
    sequence_string = '\
              CreateObject \
              SetObjectNotDefinedProperty \
              CheckNotDefinedPropertySaved \
              CheckGetNotDefinedProperty \
              '
    sequence_list.addSequenceString(sequence_string)
Romain Courteaud's avatar
Romain Courteaud committed
615
    # Test on temp object_instance.
616 617 618 619 620 621 622 623
    sequence_string = '\
              CreateTempObject \
              CheckObjectPortalType \
              SetObjectNotDefinedProperty \
              CheckNotDefinedPropertySaved \
              CheckGetNotDefinedProperty \
              '
    sequence_list.addSequenceString(sequence_string)
Jérome Perrin's avatar
Jérome Perrin committed
624
    sequence_list.play(self, quiet=quiet)
625

626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 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 695 696 697 698 699 700 701 702 703 704 705 706 707 708
  def stepCreateTempClass(self, sequence=None, sequence_list=None, **kw):
    """
    Create a temp object_instance which will be tested.
    """
    portal = self.getPortal()
    from Products.ERP5Type.Document import newTempAmount
    tmp_object = newTempAmount(portal, "another_wonderful_id")
    sequence.edit(
        object_instance=tmp_object,
        current_title='',
        current_group_value=None
    )

  def stepCheckTempClassPortalType(self, sequence=None, 
                                   sequence_list=None, **kw):
    """
    Check the portal type of the object_instance.
    Check that the portal type does not exist.
    """
    object_instance = sequence.get('object_instance')
    object_instance.getPortalType()
    self.assertEquals(self.temp_class,
                      object_instance.getPortalType())
    self.assertFalse(self.temp_class in \
                       object_instance.portal_types.listContentTypes())

  def stepSetObjectDefinedProperty(self, sequence=None, 
                                      sequence_list=None, **kw):
    """
    Set a defined property on the object_instance.
    """
    object_instance = sequence.get('object_instance')
    object_instance.setProperty(self.defined_property_id,
                       self.defined_property_value)

  def stepCheckDefinedPropertySaved(self, sequence=None, 
                                       sequence_list=None, **kw):
    """
    Check if a defined property is stored on the object_instance.
    """
    object_instance = sequence.get('object_instance')
    self.assertEquals(self.defined_property_value,
                      getattr(object_instance, self.defined_property_id))

  def stepCheckGetDefinedProperty(self, sequence=None, 
                                     sequence_list=None, **kw):
    """
    Check getProperty with a defined property.
    """
    object_instance = sequence.get('object_instance')
    self.assertEquals(self.defined_property_value,
                    object_instance.getProperty(self.defined_property_id))

  def stepSetObjectNotRelatedProperty(self, sequence=None, 
                                      sequence_list=None, **kw):
    """
    Set a defined property on the object_instance.
    """
    object_instance = sequence.get('object_instance')
    object_instance.setProperty(
                       self.not_related_to_temp_object_property_id,
                       self.not_related_to_temp_object_property_value)

  def stepCheckNotRelatedPropertySaved(self, sequence=None, 
                                       sequence_list=None, **kw):
    """
    Check if a defined property is stored on the object_instance.
    """
    object_instance = sequence.get('object_instance')
    self.assertEquals(self.not_related_to_temp_object_property_value,
                      getattr(object_instance, 
                              self.not_related_to_temp_object_property_id))

  def stepCheckGetNotRelatedProperty(self, sequence=None, 
                                  sequence_list=None, **kw):
    """
    Check getProperty with a defined property.
    """
    object_instance = sequence.get('object_instance')
    self.assertEquals(self.not_related_to_temp_object_property_value,
                    object_instance.getProperty(
                         self.not_related_to_temp_object_property_id))

709
  def test_06_getPropertyOnTempClass(self, quiet=quiet, run=1):
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    """
    Test if set/getProperty work in temp object without 
    a portal type with the same name.
    """
    if not run: return
    sequence_list = SequenceList()
    # Test on temp tempAmount.
    sequence_string = '\
              CreateTempClass \
              CheckTempClassPortalType \
              SetObjectDefinedProperty \
              CheckDefinedPropertySaved \
              CheckGetDefinedProperty \
              SetObjectNotDefinedProperty \
              CheckNotDefinedPropertySaved \
              CheckGetNotDefinedProperty \
              SetObjectNotRelatedProperty \
              CheckNotRelatedPropertySaved \
              CheckGetNotRelatedProperty \
              '
    sequence_list.addSequenceString(sequence_string)
Jérome Perrin's avatar
Jérome Perrin committed
731
    sequence_list.play(self, quiet=quiet)
732

733 734 735 736 737 738
  def stepCheckEditMethod(self, sequence=None, 
                          sequence_list=None, **kw):
    """
    Check if edit method works.
    """
    object_instance = sequence.get('object_instance')
739 740 741 742
    object_instance.edit(title='toto')
    self.assertEquals(object_instance.getTitle(),'toto')
    object_instance.edit(title='tutu')
    self.assertEquals(object_instance.getTitle(),'tutu')
743 744 745 746 747 748 749

  def stepSetEditProperty(self, sequence=None, 
                          sequence_list=None, **kw):
    """
    Check if edit method works.
    """
    object_instance = sequence.get('object_instance')
750 751
    # can't override a method:
    self.assertRaises(BadRequest, object_instance.setProperty, 'edit',
752
                      "now this object is 'read only !!!'")
753 754 755 756 757 758 759 760
    # can't change the portal type and other internal instance attributes
    self.assertRaises(BadRequest, object_instance.setProperty,
                      'portal_type', "Other")
    self.assertRaises(BadRequest, object_instance.setProperty,
                      'workflow_history', {})
    self.assertRaises(BadRequest, object_instance.setProperty,
                      '__dict__', {})

761

Jérome Perrin's avatar
Jérome Perrin committed
762
  def test_07_setEditProperty(self, quiet=quiet, run=run_all_test):
763 764 765 766 767 768 769 770 771 772 773 774
    """
    Test if setProperty erase existing accessors/methods.
    """
    if not run: return
    sequence_list = SequenceList()
    sequence_string = '\
              CreateObject \
              CheckEditMethod \
              SetEditProperty \
              CheckEditMethod \
              '
    sequence_list.addSequenceString(sequence_string)
Jérome Perrin's avatar
Jérome Perrin committed
775
    sequence_list.play(self, quiet=quiet)
776

777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
  def stepCreateBaseCategory(self, sequence=None, sequence_list=None, **kw):
    """
    Create a base category.
    """
    portal = self.getPortal()
    module = portal.portal_categories
    object_instance = module.newContent(portal_type="Base Category")
    sequence.edit(
        object_instance=object_instance,
    )

  def stepSetBadTalesExpression(self, sequence=None, sequence_list=None, **kw):
    """
    Set a wrong tales expression
    """
    object_instance = sequence.get('object_instance')
    tales_expression = "python: 1 + 'a'"
    object_instance.edit(acquisition_portal_type_list=tales_expression)
    sequence.edit(
        tales_expression=tales_expression,
    )

  def stepCheckTalesExpression(self, sequence=None, sequence_list=None, **kw):
    """
    Set a wrong tales expression
    """
    object_instance = sequence.get('object_instance')
    tales_expression = sequence.get('tales_expression')
    self.assertEquals(object_instance.getAcquisitionPortalTypeList(evaluate=0),
                      tales_expression)

  def stepSetGoodTalesExpression(self, sequence=None, 
                                 sequence_list=None, **kw):
    """
    Set a wrong tales expression
    """
    object_instance = sequence.get('object_instance')
    tales_expression = "python: 1 + 1"
    object_instance.edit(acquisition_portal_type_list=tales_expression)
    sequence.edit(
        tales_expression=tales_expression,
    )

Jérome Perrin's avatar
Jérome Perrin committed
820
  def test_07_setEditTalesExpression(self, quiet=quiet, run=run_all_test):
821 822 823 824 825 826 827 828 829 830 831 832 833
    """
    Test if edit update a tales expression.
    """
    if not run: return
    sequence_list = SequenceList()
    sequence_string = '\
              CreateBaseCategory \
              SetBadTalesExpression \
              CheckTalesExpression \
              SetGoodTalesExpression \
              CheckTalesExpression \
              '
    sequence_list.addSequenceString(sequence_string)
Jérome Perrin's avatar
Jérome Perrin committed
834
    sequence_list.play(self, quiet=quiet)
835
  
836 837 838 839
  def test_08_emptyObjectAcquiresTitle(self, quiet=quiet, run=run_all_test):
    """
    Test that an empty object has no title, and that getTitle on it acquires a
    value form the object's id.
840 841 842 843 844
    """
    if not run: return
    portal = self.getPortal()
    portal_type = "Organisation"
    module = portal.getDefaultModule(portal_type=portal_type)
845 846 847
    obj = module.newContent(portal_type=portal_type)
    # XXX title is an empty string by default, but it's still unsure wether it
    # should be None or ''
848 849 850 851
    self.assertEquals(obj.title, '')
    self.assertEquals(obj.getProperty("title"), obj.getId())
    self.assertEquals(obj._baseGetTitle(), obj.getId())
    self.assertEquals(obj.getTitle(), obj.getId())
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
  def test_09_setPropertyDefinedProperty(self, quiet=quiet, run=run_all_test):
    """Test for setProperty on Base, when the property is defined.
    """
    if not run: return
    portal = self.getPortal()
    portal_type = "Organisation"
    module = portal.getDefaultModule(portal_type=portal_type)
    obj = module.newContent(portal_type=portal_type)
    title = 'Object title'
    obj.setProperty('title', title)
    self.assertEquals(obj.getProperty('title'), title)
    obj.setProperty('title', title)
    self.assertEquals(obj.getProperty('title'), title)
    obj.edit(title=title)
    self.assertEquals(obj.getProperty('title'), title)

  def test_10_setPropertyNotDefinedProperty(self, quiet=quiet,
                                            run=run_all_test):
    """Test for setProperty on Base, when the property is not defined.
    """
    if not run: return
    portal = self.getPortal()
    portal_type = "Organisation"
    module = portal.getDefaultModule(portal_type=portal_type)
    obj = module.newContent(portal_type=portal_type)
    property_value = 'Object title'
    property_name = 'a_dummy_not_exising_property'
    obj.setProperty(property_name, property_value)
    self.assertEquals(obj.getProperty(property_name), property_value)
    obj.setProperty(property_name, property_value)
    self.assertEquals(obj.getProperty(property_name), property_value)
    obj.edit(**{property_name: property_value})
    self.assertEquals(obj.getProperty(property_name), property_value)
  
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
  def test_11_setPropertyPropertyDefinedOnInstance(self,
                                        quiet=quiet, run=run_all_test):
    """Test for setProperty on Base, when the property is defined on the
    instance, the typical example is 'workflow_history' property.
    """
    if not run: return
    portal = self.getPortal()
    portal_type = "Organisation"
    module = portal.getDefaultModule(portal_type=portal_type)
    obj = module.newContent(portal_type=portal_type)
    
    property_value = 'Property value'
    property_name = 'a_dummy_object_property'
    setattr(obj, property_name, property_value)
    self.assertRaises(BadRequest, obj.setProperty,
                     property_name, property_value)

    self.assertRaises(BadRequest, obj.setProperty,
                     'workflow_history', property_value)
  
907
  def test_12_editTempObject(self, quiet=quiet, run=run_all_test):
908 909
    """Simple t
    est to edit a temp object.
910 911 912 913 914 915 916
    """
    portal = self.getPortal()
    from Products.ERP5Type.Document import newTempOrganisation
    tmp_object = newTempOrganisation(portal, "a_wonderful_id")
    tmp_object.edit(title='new title')
    self.assertEquals('new title', tmp_object.getTitle())

917 918 919 920 921 922 923 924 925 926 927 928 929
  def test_13_aqDynamicWithNonExistentWorkflow(self, quiet=quiet, run=run_all_test):
    """Test if _aq_dynamic still works even if an associated workflow
    is not present in the portal. This may cause an infinite recursion."""
    if not run: return

    portal = self.getPortal()
    portal_type = "Organisation"
    module = portal.getDefaultModule(portal_type = portal_type)
    obj = module.newContent(portal_type = portal_type)

    # Add a non-existent workflow.
    pw = self.getWorkflowTool()
    dummy_worlflow_id = 'never_existent_workflow'
930
    pw.manage_addWorkflow('dc_workflow (Web-configurable workflow)',
931 932 933 934 935 936 937 938 939 940 941 942 943 944
                          dummy_worlflow_id)
    cbt = pw._chains_by_type
    props = {}
    for id, wf_ids in cbt.iteritems():
      if id == portal_type:
        wf_ids = list(wf_ids) + [dummy_worlflow_id]
      props['chain_%s' % id] = ','.join(wf_ids)
    pw.manage_changeWorkflows('', props = props)
    pw.manage_delObjects([dummy_worlflow_id])

    # Make sure that _aq_dynamic will be called again.
    _aq_reset()

    try:
945 946
      self.assertRaises(AttributeError, getattr, obj,
                        'thisMethodShouldNotBePresent')
947 948 949 950 951 952 953 954 955 956 957 958
    finally:
      # Make sure that the artificial workflow is not referred to any longer.
      cbt = pw._chains_by_type
      props = {}
      for id, wf_ids in cbt.iteritems():
        if id == portal_type:
          # Remove the non-existent workflow.
          wf_ids = [wf_id for wf_id in wf_ids \
                    if wf_id != dummy_worlflow_id]
        props['chain_%s' % id] = ','.join(wf_ids)
      pw.manage_changeWorkflows('', props = props)

959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
  def test_14_UpdateRoleMappingwithNoDefinedRoleAndAcquisitionActivatedOnWorkflow(self, quiet=quiet, run=run_all_test):
    """updateRoleMappingsFor does a logical AND between all workflow defining security,
    if a workflow defines no permission and is set to acquire permissions,
    and another workflow defines permission and is set not to acquire perm,
    then user have no permissions.
    It may depends on which workflow pass the last transition.
    """
    if not run: return

    portal = self.getPortal()
    portal_type = "Organisation"
    module = portal.getDefaultModule(portal_type=portal_type)

    # Add a non-existent workflow.
    pw = self.getWorkflowTool()
974 975
    dummy_simulation_worlflow_id = 'fake_simulation_workflow'
    dummy_validation_worlflow_id = 'fake_validation_workflow'
976 977
    #Assume that erp5_styles workflow Manage permissions with acquired Role by default
    pw.manage_addWorkflow('erp5_workflow (ERP5-style empty workflow)',
978 979 980 981 982 983
                          dummy_simulation_worlflow_id)
    pw.manage_addWorkflow('erp5_workflow (ERP5-style empty workflow)',
                          dummy_validation_worlflow_id)
    dummy_simulation_worlflow = pw[dummy_simulation_worlflow_id]
    dummy_validation_worlflow = pw[dummy_validation_worlflow_id]
    dummy_validation_worlflow.variables.setStateVar('validation_state')
984 985 986 987
    cbt = pw._chains_by_type
    props = {}
    for id, wf_ids in cbt.iteritems():
      if id == portal_type:
988 989
        old_wf_ids = wf_ids
      props['chain_%s' % id] = ','.join([dummy_validation_worlflow_id, dummy_simulation_worlflow_id])
990
    pw.manage_changeWorkflows('', props=props)
991 992 993 994 995 996 997
    permission_list = list(dummy_simulation_worlflow.permissions)
    manager_has_permission = {}
    for permission in permission_list:
      manager_has_permission[permission] = ('Manager',)
    manager_has_no_permission = {}
    for permission in permission_list:
      manager_has_no_permission[permission] = ()
998 999 1000 1001

    from AccessControl import getSecurityManager
    user = getSecurityManager().getUser()
    try:
1002 1003 1004
      self.assertTrue(permission_list)
      self.assertFalse(dummy_simulation_worlflow.states.draft.permission_roles)
      #1
1005
      obj = module.newContent(portal_type=portal_type)
1006 1007 1008
      #No role is defined by default on workflow
      for permission in permission_list:
        self.assertTrue(user.has_permission(permission, module)) 
1009
      #then check permission is acquired
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
      for permission in permission_list:
        self.assertTrue(user.has_permission(permission, obj))
      #2 Now configure both workflow with same configuration
      dummy_simulation_worlflow.states.draft.permission_roles = manager_has_permission.copy()
      dummy_validation_worlflow.states.draft.permission_roles = manager_has_permission.copy()
      dummy_simulation_worlflow.updateRoleMappingsFor(obj)
      dummy_validation_worlflow.updateRoleMappingsFor(obj)

      for permission in permission_list:
        self.assertTrue(user.has_permission(permission, obj))
      #3 change only dummy_simulation_worlflow
      dummy_simulation_worlflow.states.draft.permission_roles = manager_has_no_permission.copy()
      dummy_simulation_worlflow.updateRoleMappingsFor(obj)

      for permission in permission_list:
        self.assertFalse(user.has_permission(permission, obj))
      #4 enable acquisition for dummy_simulation_worlflow
      dummy_simulation_worlflow.states.draft.permission_roles = None
      dummy_simulation_worlflow.updateRoleMappingsFor(obj)
      for permission in permission_list:
1030 1031 1032 1033 1034 1035 1036 1037
        self.assertTrue(user.has_permission(permission, obj))
    finally:
      # Make sure that the artificial workflow is not referred to any longer.
      cbt = pw._chains_by_type
      props = {}
      for id, wf_ids in cbt.iteritems():
        if id == portal_type:
          # Remove the non-existent workflow.
1038
          wf_ids = old_wf_ids
1039 1040
        props['chain_%s' % id] = ','.join(wf_ids)
      pw.manage_changeWorkflows('', props=props)
1041
      pw.manage_delObjects([dummy_simulation_worlflow_id, dummy_validation_worlflow_id])
1042

1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
  def test_getViewPermissionOwnerDefault(self):
    """Test getViewPermissionOwner method behaviour"""
    portal = self.getPortal()
    obj = portal.organisation_module.newContent(portal_type='Organisation')
    self.assertEquals(self.username, obj.getViewPermissionOwner())

  def test_getViewPermissionOwnerNoOwnerLocalRole(self):
    # the actual owner doesn't have Owner local role
    portal = self.getPortal()
    obj = portal.organisation_module.newContent(portal_type='Organisation')
    obj.manage_delLocalRoles(self.username)
    self.assertEquals(self.username, obj.getViewPermissionOwner())

  def test_getViewPermissionOwnerNoViewPermission(self):
    # the owner cannot view the object
    portal = self.getPortal()
    obj = portal.organisation_module.newContent(portal_type='Organisation')
    obj.manage_permission('View', [], 0)
    self.assertEquals(None, obj.getViewPermissionOwner())

1063 1064
  def test_Member_Base_download(self):
    # tests that members can download files
1065 1066 1067 1068
    class DummyFile(file):
      def __init__(self, filename):
        self.filename = os.path.basename(filename)
        file.__init__(self, filename)
1069
    f = self.portal.newContent(portal_type='File', id='f')
1070
    f._edit(content_type='text/plain', file=DummyFile(__file__))
1071 1072 1073 1074 1075 1076 1077
    # login as a member
    uf = self.portal.acl_users
    uf._doAddUser('member_user', 'secret', ['Member'], [])
    user = uf.getUserById('member_user').__of__(uf)
    newSecurityManager(None, user)

    # if it didn't raise Unauthorized, Ok
1078 1079
    response = self.publish('%s/Base_download' % f.getPath())
    self.assertEquals(file(__file__).read(), response.body)
1080 1081
    self.assertEquals('text/plain',
                      response.headers['content-type'].split(';')[0])
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1082
    self.assertEquals('attachment; filename="%s"' % os.path.basename(__file__),
1083
                      response.headers['content-disposition'])
1084

Nicolas Delaby's avatar
Nicolas Delaby committed
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
  def test_getTypeBasedMethod(self):
    """
    Test that getTypeBasedMethod look up at ancestor classes
    and stop after Base and Folder Classes
    """
    from Products.ERP5Type.tests.utils import createZODBPythonScript
    portal = self.getPortal()

    base_script = createZODBPythonScript(portal.portal_skins.custom,
                        'Base_fooMethod',
                        'scripts_params=None',
                        '# Script body\n'
                        'return "something"' )
    xml_object_script = createZODBPythonScript(portal.portal_skins.custom,
                        'XMLObject_dummyMethod',
                        'scripts_params=None',
                        '# Script body\n'
                        'return "something"' )
    person_script = createZODBPythonScript(portal.portal_skins.custom,
                        'Person_dummyMethod',
                        'scripts_params=None',
                        '# Script body\n'
                        'return "something"' )
    copy_container_script = createZODBPythonScript(portal.portal_skins.custom,
                        'CopyContainer_dummyFooMethod',
                        'scripts_params=None',
                        '# Script body\n'
                        'return "something"' )
    cmfbtree_folder_script = createZODBPythonScript(portal.portal_skins.custom,
Nicolas Delaby's avatar
Nicolas Delaby committed
1114
                        'CMFBTreeFolder_dummyFoo2Method',
Nicolas Delaby's avatar
Nicolas Delaby committed
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
                        'scripts_params=None',
                        '# Script body\n'
                        'return "something"' )
    org = portal.organisation_module.newContent(portal_type='Organisation')
    pers = portal.person_module.newContent(portal_type='Person')

    self.assertEqual(org._getTypeBasedMethod('dummyMethod'), xml_object_script)
    self.assertEqual(pers._getTypeBasedMethod('dummyMethod'), person_script)
    self.assertEqual(org._getTypeBasedMethod('fooMethod'), base_script)
    self.assertEqual(pers._getTypeBasedMethod('fooMethod'), base_script)
    self.assertEqual(org._getTypeBasedMethod('dummyFooMethod'), None)
Nicolas Delaby's avatar
Nicolas Delaby committed
1126
    self.assertEqual(org._getTypeBasedMethod('dummyFoo2Method'), None)
1127

1128 1129 1130 1131 1132 1133
  def test_translate_table(self):
    """check if Person portal type that is installed in erp5_base is
    well indexed in translate table or not.
    """
    self.getPortal().person_module.newContent(portal_type='Person',
                                         title='translate_table_test')
1134
    transaction.commit()
1135 1136 1137 1138 1139 1140
    self.tic()
    self.assertEquals(1, len(self.getPortal().portal_catalog(
      portal_type='Person', title='translate_table_test')))
    self.assertEquals(1, len(self.getPortal().portal_catalog(
      translated_portal_type='Person', title='translate_table_test')))

1141 1142
  @skip("isIndexable is not designed to work like tested here, this test \
      must be rewritten once we know how to handle correctly templates")
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
  def test_NonIndexable(self):
    """check if a document is not indexed where we set isIndexable=0 in the same transaction of newContent().
    """
    person = self.portal.person_module.newContent(portal_type='Person')
    person.isIndexable = 0
    transaction.commit()
    self.tic()
    self.assertFalse(person.isIndexable)
    self.assertEquals(0, len(self.portal.portal_catalog(uid=person.getUid())))

1153 1154
  @skip("isIndexable is not designed to work like tested here, this test \
      must be rewritten once we know how to handle correctly templates")
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
  def test_NonIndexable2(self):
    """check if a document is not indexed where we call edit() and set isIndexable=0 after it is already indexed.
    """
    person = self.portal.person_module.newContent(portal_type='Person')
    transaction.commit()
    self.tic()
    self.assertTrue(person.isIndexable)
    self.assertEquals(1, len(self.portal.portal_catalog(uid=person.getUid())))

    # edit() will register a reindex activity because isIndexable is
    # not yet False when edit() is called.
    person.edit()
    person.isIndexable = 0
    transaction.commit()
    self.tic()
    self.assertFalse(person.isIndexable)
    self.assertEquals(0, len(self.portal.portal_catalog(uid=person.getUid())))

1173 1174
  @skip("isIndexable is not designed to work like tested here, this test \
      must be rewritten once we know how to handle correctly templates")
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
  def test_NonIndexable3(self):
    """check if a document is not indexed where we set isIndexable=0 and call edit() after it is already indexed.
    """
    person = self.portal.person_module.newContent(portal_type='Person')
    transaction.commit()
    self.tic()
    self.assertTrue(person.isIndexable)
    self.assertEquals(1, len(self.portal.portal_catalog(uid=person.getUid())))

    # edit() will not register a reindex activity because isIndexable
    # is already False when edit() is called.
    person.isIndexable = 0
    person.edit()
    transaction.commit()
    self.tic()
    self.assertFalse(person.isIndexable)
    self.assertEquals(0, len(self.portal.portal_catalog(uid=person.getUid())))

1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
class TestERP5PropertyManager(unittest.TestCase):
  """Tests for ERP5PropertyManager.
  """
  def _makeOne(self, *args, **kw):
    from Products.ERP5Type.patches.PropertyManager import ERP5PropertyManager
    ob = ERP5PropertyManager(*args, **kw)
    # add missing methods for createExpressionContext
    ob.getPortalObject = lambda : None
    ob.absolute_url = lambda: ''
    return ob

  def test_setProperty(self):
    """_setProperty adds a new property if not present."""
    ob = self._makeOne('ob')
    dummy_property_value = 'test string value'
    ob._setProperty('a_dummy_property', dummy_property_value)

    # the property appears in property map
    self.failUnless('a_dummy_property' in [x['id'] for x in ob.propertyMap()])
    # the value and can be retrieved using getProperty
    self.assertEquals(ob.getProperty('a_dummy_property'), dummy_property_value)
    # the value is also stored as a class attribute
    self.assertEquals(ob.a_dummy_property, dummy_property_value)

  def test_setPropertyExistingProperty(self):
    """_setProperty raises an error if the property already exists."""
    ob = self._makeOne('ob')
    # make sure that title property exists
    self.failUnless('title' in [x['id'] for x in ob.propertyMap()])
    # trying to call _setProperty will with an existing property raises:
    #         BadRequest: Invalid or duplicate property id: title
    self.assertRaises(BadRequest, ob._setProperty, 'title', 'property value')

  def test_updatePropertyExistingProperty(self):
    """_updateProperty should be used if the existing property already exists.
    """
    ob = self._makeOne('ob')
    # make sure that title property exists
    self.failUnless('title' in [x['id'] for x in ob.propertyMap()])
    prop_value = 'title value'
    ob._updateProperty('title', prop_value)
    self.assertEquals(ob.getProperty('title'), prop_value)
    self.assertEquals(ob.title, prop_value)

  def test_setPropertyTypeInt(self):
    """You can specify the type of the property in _setProperty"""
    ob = self._makeOne('ob')
    dummy_property_value = 3
    ob._setProperty('a_dummy_property', dummy_property_value, type='int')
    self.assertEquals(['int'], [x['type'] for x in ob.propertyMap()
                                        if x['id'] == 'a_dummy_property'])
    self.assertEquals(type(ob.getProperty('a_dummy_property')), type(1))

  def test_setPropertyTALESType(self):
    """ERP5PropertyManager can use TALES Type for properties, TALES will then
    be evaluated in getProperty.
    """
    ob = self._makeOne('ob')
    dummy_property_value = 'python: 1+2'
    ob._setProperty('a_dummy_property', dummy_property_value, type='tales')
    self.assertEquals(ob.getProperty('a_dummy_property'), 1+2)

1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
  def test_setPropertyTypeDate(self):
    """You can specify the type of the property in _setProperty"""
    ob = self._makeOne('ob')
    from DateTime import DateTime
    dummy_property_value = DateTime()
    ob._setProperty('a_dummy_property', dummy_property_value, type='date')
    self.assertEquals(['date'], [x['type'] for x in ob.propertyMap()
                                        if x['id'] == 'a_dummy_property'])
    self.assertEquals(type(ob.getProperty('a_dummy_property')), type(DateTime()))
    #Set Property without type argument
    ob._setProperty('a_second_dummy_property', dummy_property_value)
    self.assertEquals(['date'], [x['type'] for x in ob.propertyMap()
                                        if x['id'] == 'a_second_dummy_property'])
    self.assertEquals(type(ob.getProperty('a_second_dummy_property')),
                      type(DateTime()))

1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
  def test_setPropertyTypeLines(self):
    ob = self._makeOne('ob')
    ob._setProperty('a_dummy_list_property', ('1', '2'), type='lines')
    self.assertEquals(['lines'], [x['type'] for x in ob.propertyMap()
                                        if x['id'] == 'a_dummy_list_property'])
    self.assertEquals(ob.getProperty('a_dummy_list_property'), ('1', '2'))

    #Set Property without type argument
    ob._setProperty('a_second_dummy_property_list', ('3', '4'))
    self.assertEquals(['lines'], [x['type'] for x in ob.propertyMap()
                                if x['id'] == 'a_second_dummy_property_list'])
    self.assertEquals(ob.getProperty('a_second_dummy_property_list'),
                                    ('3', '4'))
    # same, but passing a list, not a tuple
    ob._setProperty('a_third_dummy_property_list', ['5', '6'])
    self.assertEquals(['lines'], [x['type'] for x in ob.propertyMap()
                                if x['id'] == 'a_third_dummy_property_list'])
    self.assertEquals(ob.getProperty('a_third_dummy_property_list'),
                                    ('5', '6'))

1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
  def test_getPropertyNonExistantProps(self):
    """getProperty return None if the value is not found.
    """
    ob = self._makeOne('ob')
    self.assertEquals(ob.getProperty('a_dummy_property'), None)

  def test_getPropertyDefaultValue(self):
    """getProperty accepts a default value, if the property is not defined.
    """
    ob = self._makeOne('ob')
    self.assertEquals(ob.getProperty('a_dummy_property', 100), 100)
    prop_value = 3
    ob._setProperty('a_dummy_property', prop_value)
    self.assertEquals(ob.getProperty('a_dummy_property', 100), prop_value)

Jérome Perrin's avatar
Jérome Perrin committed
1306 1307 1308 1309 1310
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestBase))
  suite.addTest(unittest.makeSuite(TestERP5PropertyManager))
  return suite