testBase.py 55.3 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
37 38
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase,\
                                                       _getConversionServerDict
Jérome Perrin's avatar
Jérome Perrin committed
39 40
from AccessControl.SecurityManagement import newSecurityManager
from Products.ERP5Type.tests.Sequence import SequenceList
41
from Products.ERP5Type.Base import Base
42
from zExceptions import BadRequest
43
from Products.ERP5Type.tests.backportUnittest import skip
44
from Products.ERP5Type.Workflow import addWorkflowByType
Nicolas Delaby's avatar
Nicolas Delaby committed
45
from Products.CMFCore.WorkflowCore import WorkflowException
Romain Courteaud's avatar
Romain Courteaud committed
46

47 48 49 50 51 52 53 54 55 56 57
def getDummyTypeBaseMethod(self):
  """ Use a type Base method
  """
  script = self._getTypeBasedMethod('getDummyTypeBaseMethod')
  if script is not None:
    return script()
  return "Script Not Found"

Base.getDummyTypeBaseMethod = getDummyTypeBaseMethod


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

Romain Courteaud's avatar
Romain Courteaud committed
60
  run_all_test = 1
Jérome Perrin's avatar
Jérome Perrin committed
61 62
  quiet = 1

Romain Courteaud's avatar
Romain Courteaud committed
63
  object_portal_type = "Organisation"
64 65
  not_defined_property_id = "azerty_qwerty"
  not_defined_property_value = "qwerty_azerty"
Romain Courteaud's avatar
Romain Courteaud committed
66

67 68 69
  temp_class = "Amount"
  defined_property_id = "title"
  defined_property_value = "a_wonderful_title"
70
  not_related_to_temp_object_property_id = "string_index"
71
  not_related_to_temp_object_property_value = "a_great_index"
72 73
  
  username = 'rc'
74

Romain Courteaud's avatar
Romain Courteaud committed
75 76 77 78 79 80
  def getTitle(self):
    return "Base"

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

83
  def login(self):
Romain Courteaud's avatar
Romain Courteaud committed
84
    uf = self.getPortal().acl_users
85 86
    uf._doAddUser(self.username, '', ['Manager'], [])
    user = uf.getUserById(self.username).__of__(uf)
Romain Courteaud's avatar
Romain Courteaud committed
87 88
    newSecurityManager(None, user)

89
  def afterSetUp(self):
Romain Courteaud's avatar
Romain Courteaud committed
90 91 92 93 94 95
    self.login()
    portal = self.getPortal()
    self.category_tool = self.getCategoryTool()
    portal_catalog = self.getCatalogTool()
    #portal_catalog.manage_catalogClear()
    self.createCategories()
96
    self.setDefaultSitePreference()
Romain Courteaud's avatar
Romain Courteaud committed
97

98 99 100 101 102 103 104 105 106 107 108 109 110
    #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
111 112 113 114 115
  def createCategories(self):
    """ 
      Light install create only base categories, so we create 
      some categories for testing them
    """
Romain Courteaud's avatar
Romain Courteaud committed
116
    category_list = ['testGroup1', 'testGroup2']
117
    if 'testGroup1' not in self.category_tool.group.contentIds():
Romain Courteaud's avatar
Romain Courteaud committed
118 119 120
      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
121

122 123 124 125 126 127 128 129 130
  def setDefaultSitePreference(self):
    default_pref = self.portal.portal_preferences.default_site_preference
    conversion_dict = _getConversionServerDict()
    default_pref.setPreferredOoodocServerAddress(conversion_dict['hostname'])
    default_pref.setPreferredOoodocServerPortNumber(conversion_dict['port'])
    if self.portal.portal_workflow.isTransitionPossible(default_pref, 'enable'):
      default_pref.enable()
    return default_pref

Romain Courteaud's avatar
Romain Courteaud committed
131 132
  def stepRemoveWorkflowsRelated(self, sequence=None, sequence_list=None, 
                                 **kw):
133 134 135 136 137
    """
      Remove workflow related to the portal type
    """
    self.getWorkflowTool().setChainForPortalTypes(
        ['Organisation'], ())
138 139

    transaction.commit()
140 141 142 143 144 145 146

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

    transaction.commit()
149

Romain Courteaud's avatar
Romain Courteaud committed
150 151
  def stepAssociateWorkflowsExcludingEdit(self, sequence=None, 
                                          sequence_list=None, **kw):
152 153 154 155 156
    """
      Associate workflow to the portal type
    """
    self.getWorkflowTool().setChainForPortalTypes(
        ['Organisation'], ('validation_workflow',))
157 158

    transaction.commit()
159

Romain Courteaud's avatar
Romain Courteaud committed
160 161
  def stepCreateObject(self, sequence=None, sequence_list=None, **kw):
    """
Romain Courteaud's avatar
Romain Courteaud committed
162
      Create a object_instance which will be tested.
Romain Courteaud's avatar
Romain Courteaud committed
163 164 165
    """
    portal = self.getPortal()
    module = portal.getDefaultModule(self.object_portal_type)
Romain Courteaud's avatar
Romain Courteaud committed
166
    object_instance = module.newContent(portal_type=self.object_portal_type)
Romain Courteaud's avatar
Romain Courteaud committed
167
    sequence.edit(
Romain Courteaud's avatar
Romain Courteaud committed
168
        object_instance=object_instance,
169
        current_title=object_instance.getId(), # title defaults to id
Romain Courteaud's avatar
Romain Courteaud committed
170
        current_group_value=None
Romain Courteaud's avatar
Romain Courteaud committed
171 172 173 174 175 176
    )

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

Romain Courteaud's avatar
Romain Courteaud committed
181 182
  def stepSetDifferentTitleValueWithEdit(self, sequence=None, 
                                         sequence_list=None, **kw):
Romain Courteaud's avatar
Romain Courteaud committed
183 184 185
    """
      Set a different title value
    """
Romain Courteaud's avatar
Romain Courteaud committed
186
    object_instance = sequence.get('object_instance')
Romain Courteaud's avatar
Romain Courteaud committed
187 188
    current_title = sequence.get('current_title')
    new_title_value = '%s_a' % current_title
Romain Courteaud's avatar
Romain Courteaud committed
189
    object_instance.edit(title=new_title_value)
Romain Courteaud's avatar
Romain Courteaud committed
190 191 192 193 194 195 196 197 198 199
    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()
200
    transaction.commit()
Romain Courteaud's avatar
Romain Courteaud committed
201
    message_list = portal.portal_activities.getMessageList()
202 203 204 205 206 207 208 209
    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
210

Romain Courteaud's avatar
Romain Courteaud committed
211 212
  def stepSetSameTitleValueWithEdit(self, sequence=None, sequence_list=None, 
                                    **kw):
Romain Courteaud's avatar
Romain Courteaud committed
213 214 215
    """
      Set a different title value
    """
Romain Courteaud's avatar
Romain Courteaud committed
216 217
    object_instance = sequence.get('object_instance')
    object_instance.edit(title=object_instance.getTitle())
Romain Courteaud's avatar
Romain Courteaud committed
218 219 220 221 222 223 224 225 226 227

  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
228
  def test_01_areActivitiesWellLaunchedByPropertyEdit(self, quiet=quiet,
Romain Courteaud's avatar
Romain Courteaud committed
229
                                                      run=run_all_test):
Romain Courteaud's avatar
Romain Courteaud committed
230
    """
231 232
      Test if setter does not call a activity if the attribute 
      value is not changed.
Romain Courteaud's avatar
Romain Courteaud committed
233 234 235
    """
    if not run: return
    sequence_list = SequenceList()
236 237 238 239
    # Test without workflows associated to the portal type
    sequence_string = '\
              RemoveWorkflowsRelated \
              CreateObject \
Romain Courteaud's avatar
Romain Courteaud committed
240
              Tic \
241
              CheckTitleValue \
Romain Courteaud's avatar
Romain Courteaud committed
242
              SetDifferentTitleValueWithEdit \
243 244 245 246
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
Romain Courteaud's avatar
Romain Courteaud committed
247
              SetSameTitleValueWithEdit \
248
              CheckTitleValue \
249
              CheckIfMessageQueueIsEmpty \
Romain Courteaud's avatar
Romain Courteaud committed
250
              SetDifferentTitleValueWithEdit \
251 252 253 254 255 256 257 258 259 260
              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
261
              Tic \
Romain Courteaud's avatar
Romain Courteaud committed
262
              CheckTitleValue \
Romain Courteaud's avatar
Romain Courteaud committed
263
              SetDifferentTitleValueWithEdit \
Romain Courteaud's avatar
Romain Courteaud committed
264 265 266 267
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
Romain Courteaud's avatar
Romain Courteaud committed
268
              SetSameTitleValueWithEdit \
269 270 271
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
Romain Courteaud's avatar
Romain Courteaud committed
272
              CheckIfMessageQueueIsEmpty \
Romain Courteaud's avatar
Romain Courteaud committed
273
              SetDifferentTitleValueWithEdit \
Romain Courteaud's avatar
Romain Courteaud committed
274 275 276 277 278 279
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              '
    sequence_list.addSequenceString(sequence_string)
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
    # 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
301
    sequence_list.play(self, quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
302

Romain Courteaud's avatar
Romain Courteaud committed
303 304 305 306
  def stepCheckGroupValue(self, sequence=None, sequence_list=None, **kw):
    """
      Check if getTitle return a correect value
    """
Romain Courteaud's avatar
Romain Courteaud committed
307
    object_instance = sequence.get('object_instance')
Romain Courteaud's avatar
Romain Courteaud committed
308
    current_group_value = sequence.get('current_group_value')
Romain Courteaud's avatar
Romain Courteaud committed
309
    self.assertEquals(object_instance.getGroupValue(), current_group_value)
Romain Courteaud's avatar
Romain Courteaud committed
310 311 312 313 314 315

  def stepSetDifferentGroupValueWithEdit(self, sequence=None, 
                                         sequence_list=None, **kw):
    """
      Set a different title value
    """
Romain Courteaud's avatar
Romain Courteaud committed
316
    object_instance = sequence.get('object_instance')
Romain Courteaud's avatar
Romain Courteaud committed
317
    current_group_value = sequence.get('current_group_value')
Romain Courteaud's avatar
Romain Courteaud committed
318 319 320 321
    group1 = object_instance.portal_categories.\
                       restrictedTraverse('group/testGroup1')
    group2 = object_instance.portal_categories.\
                       restrictedTraverse('group/testGroup2')
Romain Courteaud's avatar
Romain Courteaud committed
322 323 324 325 326 327
    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
328
    object_instance.edit(group_value=new_group_value)
Romain Courteaud's avatar
Romain Courteaud committed
329 330 331 332 333 334 335 336 337
    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
338 339
    object_instance = sequence.get('object_instance')
    object_instance.edit(group_value=object_instance.getGroupValue())
Romain Courteaud's avatar
Romain Courteaud committed
340 341


Jérome Perrin's avatar
Jérome Perrin committed
342
  def test_02_areActivitiesWellLaunchedByCategoryEdit(self, quiet=quiet,
Romain Courteaud's avatar
Romain Courteaud committed
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
                                                      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 \
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
              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
399 400 401 402 403 404 405 406 407 408 409 410 411 412
              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
413
    sequence_list.play(self, quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
414 415 416 417 418 419

  def stepSetDifferentTitleValueWithSetter(self, sequence=None, 
                                           sequence_list=None, **kw):
    """
      Set a different title value
    """
Romain Courteaud's avatar
Romain Courteaud committed
420
    object_instance = sequence.get('object_instance')
Romain Courteaud's avatar
Romain Courteaud committed
421 422
    current_title = sequence.get('current_title')
    new_title_value = '%s_a' % current_title
Romain Courteaud's avatar
Romain Courteaud committed
423
    object_instance.setTitle(new_title_value)
Romain Courteaud's avatar
Romain Courteaud committed
424 425 426 427 428 429 430 431 432
    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
433 434
    object_instance = sequence.get('object_instance')
    object_instance.setTitle(object_instance.getTitle())
Romain Courteaud's avatar
Romain Courteaud committed
435

Jérome Perrin's avatar
Jérome Perrin committed
436
  def test_03_areActivitiesWellLaunchedByPropertySetter(self, quiet=quiet,
Romain Courteaud's avatar
Romain Courteaud committed
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
                                                        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 \
456 457 458
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
Romain Courteaud's avatar
Romain Courteaud committed
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
              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 \
479 480 481
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
Romain Courteaud's avatar
Romain Courteaud committed
482 483 484 485 486 487 488 489
              CheckIfMessageQueueIsEmpty \
              SetDifferentTitleValueWithSetter \
              CheckIfActivitiesAreCreated \
              CheckTitleValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              '
    sequence_list.addSequenceString(sequence_string)
Jérome Perrin's avatar
Jérome Perrin committed
490
    sequence_list.play(self, quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
491 492 493 494 495 496

  def stepSetDifferentGroupValueWithSetter(self, sequence=None, 
                                           sequence_list=None, **kw):
    """
      Set a different title value
    """
Romain Courteaud's avatar
Romain Courteaud committed
497
    object_instance = sequence.get('object_instance')
Romain Courteaud's avatar
Romain Courteaud committed
498
    current_group_value = sequence.get('current_group_value')
Romain Courteaud's avatar
Romain Courteaud committed
499 500 501 502
    group1 = object_instance.portal_categories.\
                                   restrictedTraverse('group/testGroup1')
    group2 = object_instance.portal_categories.\
                                   restrictedTraverse('group/testGroup2')
Romain Courteaud's avatar
Romain Courteaud committed
503 504 505 506 507 508
    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
509
    object_instance.setGroupValue(new_group_value)
Romain Courteaud's avatar
Romain Courteaud committed
510 511 512 513 514 515 516 517 518
    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
519 520
    object_instance = sequence.get('object_instance')
    object_instance.setGroupValue(object_instance.getGroupValue())
Romain Courteaud's avatar
Romain Courteaud committed
521

Jérome Perrin's avatar
Jérome Perrin committed
522
  def test_04_areActivitiesWellLaunchedByCategorySetter(self, quiet=quiet,
Romain Courteaud's avatar
Romain Courteaud committed
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
                                                        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 \
542 543 544
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
Romain Courteaud's avatar
Romain Courteaud committed
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
              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 \
565 566 567
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
Romain Courteaud's avatar
Romain Courteaud committed
568 569 570 571 572 573 574 575
              CheckIfMessageQueueIsEmpty \
              SetDifferentGroupValueWithSetter \
              CheckIfActivitiesAreCreated \
              CheckGroupValue \
              Tic \
              CheckIfMessageQueueIsEmpty \
              '
    sequence_list.addSequenceString(sequence_string)
Jérome Perrin's avatar
Jérome Perrin committed
576
    sequence_list.play(self, quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
577

578 579 580
  def stepSetObjectNotDefinedProperty(self, sequence=None, 
                                      sequence_list=None, **kw):
    """
Romain Courteaud's avatar
Romain Courteaud committed
581
    Set a not defined property on the object_instance.
582
    """
Romain Courteaud's avatar
Romain Courteaud committed
583 584
    object_instance = sequence.get('object_instance')
    object_instance.setProperty(self.not_defined_property_id,
585 586 587 588 589
                       self.not_defined_property_value)

  def stepCheckNotDefinedPropertySaved(self, sequence=None, 
                                       sequence_list=None, **kw):
    """
Romain Courteaud's avatar
Romain Courteaud committed
590
    Check if a not defined property is stored on the object_instance.
591
    """
Romain Courteaud's avatar
Romain Courteaud committed
592
    object_instance = sequence.get('object_instance')
593
    self.assertEquals(self.not_defined_property_value,
Romain Courteaud's avatar
Romain Courteaud committed
594
                      getattr(object_instance, self.not_defined_property_id))
595 596 597 598 599 600

  def stepCheckGetNotDefinedProperty(self, sequence=None, 
                                     sequence_list=None, **kw):
    """
    Check getProperty with a not defined property.
    """
Romain Courteaud's avatar
Romain Courteaud committed
601
    object_instance = sequence.get('object_instance')
602
    self.assertEquals(self.not_defined_property_value,
Romain Courteaud's avatar
Romain Courteaud committed
603
                    object_instance.getProperty(self.not_defined_property_id))
604 605 606 607

  def stepCheckObjectPortalType(self, sequence=None, 
                                sequence_list=None, **kw):
    """
Romain Courteaud's avatar
Romain Courteaud committed
608
    Check the portal type of the object_instance.
609
    """
Romain Courteaud's avatar
Romain Courteaud committed
610 611
    object_instance = sequence.get('object_instance')
    object_instance.getPortalType()
612
    self.assertEquals(self.object_portal_type,
Romain Courteaud's avatar
Romain Courteaud committed
613
                      object_instance.getPortalType())
614 615 616

  def stepCreateTempObject(self, sequence=None, sequence_list=None, **kw):
    """
Romain Courteaud's avatar
Romain Courteaud committed
617
      Create a temp object_instance which will be tested.
618 619 620 621 622
    """
    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
623
        object_instance=tmp_object,
624 625 626 627
        current_title='',
        current_group_value=None
    )

Jérome Perrin's avatar
Jérome Perrin committed
628
  def test_05_getPropertyWithoutPropertySheet(self, quiet=quiet, run=run_all_test):
629 630 631 632 633
    """
    Test if set/getProperty work without any property sheet.
    """
    if not run: return
    sequence_list = SequenceList()
Romain Courteaud's avatar
Romain Courteaud committed
634
    # Test on object_instance.
635 636 637 638 639 640 641
    sequence_string = '\
              CreateObject \
              SetObjectNotDefinedProperty \
              CheckNotDefinedPropertySaved \
              CheckGetNotDefinedProperty \
              '
    sequence_list.addSequenceString(sequence_string)
Romain Courteaud's avatar
Romain Courteaud committed
642
    # Test on temp object_instance.
643 644 645 646 647 648 649 650
    sequence_string = '\
              CreateTempObject \
              CheckObjectPortalType \
              SetObjectNotDefinedProperty \
              CheckNotDefinedPropertySaved \
              CheckGetNotDefinedProperty \
              '
    sequence_list.addSequenceString(sequence_string)
Jérome Perrin's avatar
Jérome Perrin committed
651
    sequence_list.play(self, quiet=quiet)
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 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
  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.
    """
    object_instance = sequence.get('object_instance')
    object_instance.getPortalType()
    self.assertEquals(self.temp_class,
                      object_instance.getPortalType())

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

733
  def test_06_getPropertyOnTempClass(self, quiet=quiet, run=1):
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
    """
    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
755
    sequence_list.play(self, quiet=quiet)
756

757 758 759 760 761 762
  def stepCheckEditMethod(self, sequence=None, 
                          sequence_list=None, **kw):
    """
    Check if edit method works.
    """
    object_instance = sequence.get('object_instance')
763 764 765 766
    object_instance.edit(title='toto')
    self.assertEquals(object_instance.getTitle(),'toto')
    object_instance.edit(title='tutu')
    self.assertEquals(object_instance.getTitle(),'tutu')
767 768 769 770 771 772 773

  def stepSetEditProperty(self, sequence=None, 
                          sequence_list=None, **kw):
    """
    Check if edit method works.
    """
    object_instance = sequence.get('object_instance')
774 775
    # can't override a method:
    self.assertRaises(BadRequest, object_instance.setProperty, 'edit',
776
                      "now this object is 'read only !!!'")
777 778 779 780 781 782 783 784
    # 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__', {})

785

Jérome Perrin's avatar
Jérome Perrin committed
786
  def test_07_setEditProperty(self, quiet=quiet, run=run_all_test):
787 788 789 790 791 792 793 794 795 796 797 798
    """
    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
799
    sequence_list.play(self, quiet=quiet)
800

801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
  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
844
  def test_07_setEditTalesExpression(self, quiet=quiet, run=run_all_test):
845 846 847 848 849 850 851 852 853 854 855 856 857
    """
    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
858
    sequence_list.play(self, quiet=quiet)
859
  
860 861 862 863
  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.
864 865 866 867 868
    """
    if not run: return
    portal = self.getPortal()
    portal_type = "Organisation"
    module = portal.getDefaultModule(portal_type=portal_type)
869 870 871
    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 ''
872 873 874 875
    self.assertEquals(obj.title, '')
    self.assertEquals(obj.getProperty("title"), obj.getId())
    self.assertEquals(obj._baseGetTitle(), obj.getId())
    self.assertEquals(obj.getTitle(), obj.getId())
876

877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
  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)
  
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
  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)
  
931
  def test_12_editTempObject(self, quiet=quiet, run=run_all_test):
932 933
    """Simple t
    est to edit a temp object.
934 935 936 937 938 939 940
    """
    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())

941 942 943 944 945 946 947 948 949 950 951 952 953
  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'
954
    addWorkflowByType(pw, 'erp5_workflow', dummy_worlflow_id)
955 956 957

    transaction.commit()

958 959 960 961 962 963 964 965 966
    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])

967
    transaction.commit()
968 969

    try:
970 971
      self.assertRaises(AttributeError, getattr, obj,
                        'thisMethodShouldNotBePresent')
972 973 974 975 976 977 978 979 980 981 982 983
    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)

984 985
      transaction.commit()

986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
  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()
1001 1002
    dummy_simulation_worlflow_id = 'fake_simulation_workflow'
    dummy_validation_worlflow_id = 'fake_validation_workflow'
1003
    #Assume that erp5_styles workflow Manage permissions with acquired Role by default
1004 1005
    addWorkflowByType(pw, 'erp5_workflow', dummy_simulation_worlflow_id)
    addWorkflowByType(pw, 'erp5_workflow', dummy_validation_worlflow_id)
1006 1007 1008
    dummy_simulation_worlflow = pw[dummy_simulation_worlflow_id]
    dummy_validation_worlflow = pw[dummy_validation_worlflow_id]
    dummy_validation_worlflow.variables.setStateVar('validation_state')
1009 1010 1011 1012
    cbt = pw._chains_by_type
    props = {}
    for id, wf_ids in cbt.iteritems():
      if id == portal_type:
1013 1014
        old_wf_ids = wf_ids
      props['chain_%s' % id] = ','.join([dummy_validation_worlflow_id, dummy_simulation_worlflow_id])
1015
    pw.manage_changeWorkflows('', props=props)
1016 1017 1018 1019 1020 1021 1022
    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] = ()
1023 1024 1025 1026

    from AccessControl import getSecurityManager
    user = getSecurityManager().getUser()
    try:
1027 1028 1029
      self.assertTrue(permission_list)
      self.assertFalse(dummy_simulation_worlflow.states.draft.permission_roles)
      #1
1030
      obj = module.newContent(portal_type=portal_type)
1031 1032 1033
      #No role is defined by default on workflow
      for permission in permission_list:
        self.assertTrue(user.has_permission(permission, module)) 
1034
      #then check permission is acquired
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
      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:
1055 1056 1057 1058 1059 1060 1061 1062
        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.
1063
          wf_ids = old_wf_ids
1064 1065
        props['chain_%s' % id] = ','.join(wf_ids)
      pw.manage_changeWorkflows('', props=props)
1066
      pw.manage_delObjects([dummy_simulation_worlflow_id, dummy_validation_worlflow_id])
1067

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
  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())

1088 1089
  def test_Member_Base_download(self):
    # tests that members can download files
1090 1091 1092 1093
    class DummyFile(file):
      def __init__(self, filename):
        self.filename = os.path.basename(filename)
        file.__init__(self, filename)
1094
    f = self.portal.newContent(portal_type='File', id='f')
1095
    f._edit(content_type='text/plain', file=DummyFile(__file__))
1096 1097 1098 1099 1100 1101 1102
    # 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
1103 1104
    response = self.publish('%s/Base_download' % f.getPath())
    self.assertEquals(file(__file__).read(), response.body)
1105
    self.assertEquals('text/plain',
1106
                      response.getHeader('content-type').split(';')[0])
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1107
    self.assertEquals('attachment; filename="%s"' % os.path.basename(__file__),
1108
                      response.getHeader('content-disposition'))
1109

Nicolas Delaby's avatar
Nicolas Delaby committed
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
  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'
1122
                        'return context.getId()' )
Nicolas Delaby's avatar
Nicolas Delaby committed
1123 1124 1125 1126
    xml_object_script = createZODBPythonScript(portal.portal_skins.custom,
                        'XMLObject_dummyMethod',
                        'scripts_params=None',
                        '# Script body\n'
1127
                        'return context.getId()' )
Nicolas Delaby's avatar
Nicolas Delaby committed
1128 1129 1130 1131
    person_script = createZODBPythonScript(portal.portal_skins.custom,
                        'Person_dummyMethod',
                        'scripts_params=None',
                        '# Script body\n'
1132
                        'return context.getId()' )
Nicolas Delaby's avatar
Nicolas Delaby committed
1133 1134 1135 1136
    copy_container_script = createZODBPythonScript(portal.portal_skins.custom,
                        'CopyContainer_dummyFooMethod',
                        'scripts_params=None',
                        '# Script body\n'
1137
                        'return context.getId()' )
Nicolas Delaby's avatar
Nicolas Delaby committed
1138
    cmfbtree_folder_script = createZODBPythonScript(portal.portal_skins.custom,
Nicolas Delaby's avatar
Nicolas Delaby committed
1139
                        'CMFBTreeFolder_dummyFoo2Method',
Nicolas Delaby's avatar
Nicolas Delaby committed
1140 1141
                        'scripts_params=None',
                        '# Script body\n'
1142
                        'return context.getId()' )
Nicolas Delaby's avatar
Nicolas Delaby committed
1143 1144 1145 1146 1147 1148 1149 1150
    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
1151
    self.assertEqual(org._getTypeBasedMethod('dummyFoo2Method'), None)
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
    
    # Call the scripts to make sure the context are appropriated.
    self.assertEqual(org._getTypeBasedMethod('dummyMethod')(), org.getId())
    self.assertEqual(pers._getTypeBasedMethod('dummyMethod')(), pers.getId())
    self.assertEqual(org._getTypeBasedMethod('fooMethod')(), org.getId())
    self.assertEqual(pers._getTypeBasedMethod('fooMethod')(), pers.getId())

    self.assertEqual(pers.getDummyTypeBaseMethod(), "Script Not Found")

    person_dummy_script = createZODBPythonScript(portal.portal_skins.custom,
                        'Person_getDummyTypeBaseMethod',
                        'scripts_params=None',
                        '# Script body\n'
                        'return context.getId()' )

    dummy_script_by_activity = createZODBPythonScript(portal.portal_skins.custom,
                        'Person_getDummyTypeBaseMethodByActivity',
                        'scripts_params=None',
                        '# Script body\n'
                        'context.getDummyTypeBaseMethod()\n'
                        'return context.getDummyTypeBaseMethod()' )
1173

1174 1175 1176 1177 1178 1179 1180 1181 1182

    transaction.commit() # Flush transactional cache.
    self.assertEqual(pers.getDummyTypeBaseMethod(), pers.getId())
    # Call once more to check cache.
    self.assertEqual(pers.getDummyTypeBaseMethod(), pers.getId())

    pers.activate().Person_getDummyTypeBaseMethodByActivity()
    self.stepTic()
    
1183 1184 1185 1186 1187 1188
  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')
1189
    transaction.commit()
1190 1191 1192 1193 1194 1195
    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')))

1196 1197 1198 1199 1200 1201 1202 1203
  def test_TempBasePublicMethods(self):
    # make sure TempBase methods 'edit' and 'setProperty' are actually public
    self.logout()
    from Products.ERP5Type.Document import newTempBase
    from OFS.Traversable import guarded_getattr
    tb = newTempBase(self.portal, '_temp_base')
    for name in ('edit', 'setProperty'):
      # should not raise Unauthorized
1204
      edit = guarded_getattr(tb, name)
1205

1206 1207
  @skip("isIndexable is not designed to work like tested here, this test \
      must be rewritten once we know how to handle correctly templates")
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
  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())))

1218 1219
  @skip("isIndexable is not designed to work like tested here, this test \
      must be rewritten once we know how to handle correctly templates")
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
  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())))

1238 1239
  @skip("isIndexable is not designed to work like tested here, this test \
      must be rewritten once we know how to handle correctly templates")
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
  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())))

Nicolas Delaby's avatar
Nicolas Delaby committed
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
  def test_metaWorkflowTransition(self):
    """Test Meta Transtion, jump from state to another without explicitely
    transtion defined.
    """
    module = self.portal.person_module
    person = module.newContent(portal_type='Person')
    self.assertEquals(person.getValidationState(), 'draft')
    self.assertFalse(self.portal.portal_workflow.isTransitionPossible(person,
                                                                 'invalidate'))
    # test low-level implementation
    self.portal.portal_workflow.validation_workflow._executeMetaTransition(
                                                         person, 'invalidated')
    self.assertEquals(person.getValidationState(), 'invalidated')
    validation_history = person.workflow_history['validation_workflow']
    self.assertEquals(len(validation_history), 2)
    self.assertEquals(validation_history[-1]['comment'],
                                      'Jump from \'draft\' to \'invalidated\'')
    person = module.newContent(portal_type='Person')
    self.assertEquals(person.getValidationState(), 'draft')

    # test high-level implementation
    self.portal.portal_workflow._jumpToStateFor(person, 'invalidated')
    self.assertEquals(person.getValidationState(), 'invalidated')

    person = module.newContent(portal_type='Person')
    self.assertEquals(person.getValidationState(), 'draft')
    self.portal.portal_workflow._jumpToStateFor(person, 'invalidated',
                                               wf_id='validation_workflow')
    self.assertEquals(person.getValidationState(), 'invalidated')
    person = module.newContent(portal_type='Person')
    self.assertEquals(person.getValidationState(), 'draft')
    self.assertRaises(WorkflowException,
                      self.portal.portal_workflow._jumpToStateFor,
                      person, 'invalidated', wf_id='edit_workflow')
    self.assertEquals(person.getValidationState(), 'draft')


1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
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)

1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
  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()))

1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
  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'))

1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
  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
1408 1409 1410 1411 1412
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestBase))
  suite.addTest(unittest.makeSuite(TestERP5PropertyManager))
  return suite