testResource.py 43 KB
Newer Older
Romain Courteaud's avatar
Romain Courteaud committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
##############################################################################
#
# Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved.
#          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.
#
##############################################################################

29
import unittest
30
import transaction
Romain Courteaud's avatar
Romain Courteaud committed
31 32
from Testing import ZopeTestCase
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
33
from AccessControl.SecurityManagement import newSecurityManager
34
from Products.CMFCore.utils import getToolByName
Romain Courteaud's avatar
Romain Courteaud committed
35
from zLOG import LOG
36
from Products.ERP5Type.tests.Sequence import SequenceList
37
from DateTime import DateTime
38

Romain Courteaud's avatar
Romain Courteaud committed
39 40 41 42 43 44

class TestResource(ERP5TypeTestCase):
  """
    Test ERP5 document Resource
  """
  run_all_test = 1
45
  quiet = 0
Romain Courteaud's avatar
Romain Courteaud committed
46 47 48

  # Global variables
  resource_portal_type = 'Apparel Model'
49
  product_portal_type = 'Product'
50
  node_portal_type = 'Organisation'
51
  sale_supply_portal_type = 'Sale Supply'
52
  sale_order_line_portal_type = 'Sale Order Line'
53
  sale_supply_line_portal_type = 'Sale Supply Line'
54
  purchase_supply_line_portal_type = 'Purchase Supply Line'
55
  sale_supply_cell_portal_type = 'Sale Supply Cell'
Kevin Deldycke's avatar
Kevin Deldycke committed
56
  variation_base_category_list = ['colour', 'size', 'morphology',
57
                                  'industrial_phase']
Kevin Deldycke's avatar
Kevin Deldycke committed
58
  size_list = ['size/Child','size/Man']
59
  variation_property_list = []
Romain Courteaud's avatar
Romain Courteaud committed
60 61 62 63 64

  def getBusinessTemplateList(self):
    """
      Install needed business template
    """
65
    # Trade is needeed for pricing
66
    return ('erp5_base', 'erp5_pdm', 'erp5_trade', 'erp5_apparel', )
Romain Courteaud's avatar
Romain Courteaud committed
67 68 69 70 71 72 73 74 75 76

  def getTitle(self):
    return "Resource"

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

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
  def setUpPreferences(self):
    portal = self.getPortal()
    preferences = getToolByName(portal,'portal_preferences')

    system_preference = preferences.newContent(
      portal_type = 'System Preference'
    )

    system_preference.edit(
      preferred_apparel_model_variation_base_category_list = ('colour', 'size', 'morphology', 'industrial_phase',),
      preferred_apparel_cloth_variation_base_category_list = ('size',),
      preferred_apparel_component_variation_base_category_list = ('variation',),
      preferred_apparel_colour_variation_base_category_list = ('colour',),
      priority = 1,
    )

    system_preference.enable()
    transaction.commit()
    self.tic()

Romain Courteaud's avatar
Romain Courteaud committed
97 98 99 100 101
  def afterSetUp(self):
    self.login()
    self.portal = self.getPortal()
    self.category_tool = self.getCategoryTool()
    self.createCategories()
102
    self.setUpPreferences()
Romain Courteaud's avatar
Romain Courteaud committed
103

Jérome Perrin's avatar
Jérome Perrin committed
104
  def beforeTearDown(self):
105
    transaction.abort()
Jérome Perrin's avatar
Jérome Perrin committed
106 107 108 109 110 111 112 113
    for folder in (
          self.portal.getDefaultModule(self.resource_portal_type),
          self.portal.getDefaultModule(self.sale_supply_portal_type),
          self.portal.getDefaultModule("Currency"),
          self.portal.getDefaultModule(self.node_portal_type),
          self.portal.getDefaultModule("Sale Order"),
          self.portal.getDefaultModule("Purchase Order"),):
      folder.manage_delObjects([i for i in folder.objectIds()])
114
    transaction.commit()
Jérome Perrin's avatar
Jérome Perrin committed
115 116
    self.tic()

Romain Courteaud's avatar
Romain Courteaud committed
117
  def createCategories(self):
Kevin Deldycke's avatar
Kevin Deldycke committed
118 119
    """
      Light install create only base categories, so we create
Romain Courteaud's avatar
Romain Courteaud committed
120 121 122 123 124 125 126
      some categories for testing them
    """
    size_category_list = ['Baby', 'Child', 'Man', 'Woman']
    if len(self.category_tool.size.contentValues()) == 0 :
      for category_id in size_category_list:
        o = self.category_tool.size.newContent(portal_type='Category',
                                               id=category_id)
Kevin Deldycke's avatar
Kevin Deldycke committed
127
    self.size_category_list = map(lambda x: 'size/%s' % x,
Romain Courteaud's avatar
Romain Courteaud committed
128 129 130 131 132 133 134
                                  size_category_list)

    colour_category_list = ['blue', 'green']
    if len(self.category_tool.colour.contentValues()) == 0 :
      for category_id in colour_category_list:
        o = self.category_tool.colour.newContent(portal_type='Category',
                                               id=category_id)
Kevin Deldycke's avatar
Kevin Deldycke committed
135
    self.colour_category_list = map(lambda x: 'colour/%s' % x,
Romain Courteaud's avatar
Romain Courteaud committed
136 137
                                    colour_category_list)

138 139 140 141 142 143 144
    ind_phase_category_list = ['phase1', 'phase2']
    if len(self.category_tool.industrial_phase.contentValues()) == 0:
      for category_id in ind_phase_category_list:
        o = self.category_tool.industrial_phase.newContent(
                                               portal_type='Category',
                                               id=category_id)
    self.industrial_phase_category_list = map(
Kevin Deldycke's avatar
Kevin Deldycke committed
145
                                    lambda x: 'industrial_phase/%s' % x,
146 147
                                    ind_phase_category_list)

Romain Courteaud's avatar
Romain Courteaud committed
148 149 150 151
    self.morphology_category_list = []
    self.base_category_content_list = {
      'size':self.size_category_list,
      'colour':self.colour_category_list,
152
      'morphology':self.morphology_category_list,
153
      'industrial_phase':self.industrial_phase_category_list
Romain Courteaud's avatar
Romain Courteaud committed
154 155
    }

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    quantity_unit_weight = self.portal.portal_categories.quantity_unit._getOb(
                                        'weight', None)
    if quantity_unit_weight is None:
      quantity_unit_weight = self.portal.portal_categories.quantity_unit\
                                  .newContent(id='weight',
                                              portal_type='Category')
    self.quantity_unit_gram = quantity_unit_weight._getOb('gram', None)
    if self.quantity_unit_gram is None:
      self.quantity_unit_gram = quantity_unit_weight.newContent(
                                      portal_type='Category',
                                      quantity=0.001,
                                      id='gram')
    self.quantity_unit_kilo = quantity_unit_weight._getOb('kilo', None)
    if self.quantity_unit_kilo is None:
      self.quantity_unit_kilo = quantity_unit_weight.newContent(
                                      portal_type='Category',
                                      quantity=1,
                                      id='kilo')


Romain Courteaud's avatar
Romain Courteaud committed
176 177 178 179 180 181 182 183 184 185 186 187 188
  def stepTic(self,**kw):
    self.tic()

  def stepCreateResource(self, sequence=None, sequence_list=None, **kw):
    """
      Create a resource without variation
    """
    resource_module = self.portal.getDefaultModule(self.resource_portal_type)
    resource = resource_module.newContent( \
                                 portal_type=self.resource_portal_type)
    resource.edit(
      title = "Resource"
    )
189 190
    sequence.edit(resource=resource,
                  variation_property_list=[])
Romain Courteaud's avatar
Romain Courteaud committed
191 192 193 194 195
    self.category_list = []
    # Actually, resource has no individual variation
    for base_category in resource.getVariationBaseCategoryList():
      sequence.edit(**{base_category:None})

Kevin Deldycke's avatar
Kevin Deldycke committed
196
  def stepCheckGetVariationBaseCategoryList(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
197 198 199 200 201 202 203 204
                                             sequence_list=None, **kw):
    """
      Check if getVariationBaseCategoryList returns the good result
    """
    resource = sequence.get('resource')
    vbcl = resource.getVariationBaseCategoryList()
    self.failIfDifferentSet(self.variation_base_category_list, vbcl)

Kevin Deldycke's avatar
Kevin Deldycke committed
205
  def stepCheckGetVariationRangeCategoryList(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
                                             sequence_list=None, **kw):
    """
      Check if getVariationRangeCategoryList returns the good result
    """
    resource = sequence.get('resource')
    vbcl = resource.getVariationBaseCategoryList()
    correct_variation_range_category_list = []
    for base_category in vbcl:
      # Check if resource has individual variations
      individual_variation_list = sequence.get(base_category)
      if individual_variation_list is None:
        correct_variation_range_category_list.extend(
                               self.base_category_content_list[base_category])
      else:
        correct_variation_range_category_list.extend(individual_variation_list)

    vrcl = resource.getVariationRangeCategoryList()
    self.failIfDifferentSet(correct_variation_range_category_list, vrcl)

  def stepSetCategoryVariation(self, sequence=None, sequence_list=None, **kw):
    """
      Set category variation to current resource
    """
    resource = sequence.get('resource')
    size_list = map(lambda x: x[len('size/'):], self.size_list)
Kevin Deldycke's avatar
Kevin Deldycke committed
231
    resource.setSizeList(size_list)
Romain Courteaud's avatar
Romain Courteaud committed
232 233
    self.category_list = self.size_list[:]

Kevin Deldycke's avatar
Kevin Deldycke committed
234
  def stepSetIndividualVariationWithEmptyBase(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
235 236
                                              sequence_list=None, **kw):
    """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
237 238
    Set the individual variation of the current resource to a base category
    that contains no subobjects.
Romain Courteaud's avatar
Romain Courteaud committed
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
    """
    resource = sequence.get('resource')
    morphology_list = []
    morphology_variation_count = 2
    for i in range(morphology_variation_count) :
      variation_portal_type = 'Apparel Model Morphology Variation'
      variation = resource.newContent(portal_type=variation_portal_type)
      variation.edit(
        title = 'MorphologyVariation%s' % str(i)
      )
      morphology_list.append('morphology/%s' %
                                        variation.getRelativeUrl())
    # store individual resource
    sequence.edit(morphology=morphology_list)

Kevin Deldycke's avatar
Kevin Deldycke committed
254
  def stepSetIndividualVariationWithFillBase(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
255 256
                                              sequence_list=None, **kw):
    """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
257 258
    Set the individual variation of the current resource to a base category
    that contains some subobjects.
Romain Courteaud's avatar
Romain Courteaud committed
259 260 261
    """
    resource = sequence.get('resource')
    colour_list = []
Kevin Deldycke's avatar
Kevin Deldycke committed
262
    colour_variation_count = 1
Romain Courteaud's avatar
Romain Courteaud committed
263 264 265 266 267 268 269 270 271 272
    for i in range(colour_variation_count) :
      variation_portal_type = 'Apparel Model Colour Variation'
      variation = resource.newContent(portal_type=variation_portal_type)
      variation.edit(
        title = 'ColourVariation%s' % str(i)
      )
      colour_list.append('colour/%s' % variation.getRelativeUrl())
    # store individual resource
    sequence.edit(colour=colour_list)

273
  def test_01_getVariationBaseCategoryList(self, quiet=quiet, run=run_all_test):
Romain Courteaud's avatar
Romain Courteaud committed
274 275 276 277 278 279 280 281 282 283 284
    """
      Test the method getVariationBaseCategoryList on a resource.
    """
    if not run: return
    sequence_list = SequenceList()
    # Test when resource has no variation
    sequence_string = '\
                      CreateResource \
                      CheckGetVariationBaseCategoryList \
                      '
    sequence_list.addSequenceString(sequence_string)
285
    sequence_list.play(self, quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
286

287
  def genericTest(self, test_method_name, quiet=quiet):
Romain Courteaud's avatar
Romain Courteaud committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
    """
      Generic test on a resource.
    """
    sequence_list = SequenceList()
    # Test when resource has no variation
    sequence_string = '\
                      CreateResource \
                      %s \
                      ' % test_method_name
    sequence_list.addSequenceString(sequence_string)
    # Test when resource has category variations
    sequence_string = '\
                      CreateResource \
                      SetCategoryVariation \
                      %s \
                      ' % test_method_name
    sequence_list.addSequenceString(sequence_string)
    # Test when resource has individual variation and base category
    # has no content
    sequence_string = '\
                      CreateResource \
                      SetIndividualVariationWithEmptyBase \
                      Tic \
                      %s \
                      ' % test_method_name
    sequence_list.addSequenceString(sequence_string)
    # Test when resource has individual variation and base category
    # has category content
    sequence_string = '\
                      CreateResource \
                      SetIndividualVariationWithFillBase \
                      Tic \
                      %s \
                      ' % test_method_name
    sequence_list.addSequenceString(sequence_string)
    # Test with all cases
    sequence_string = '\
                      CreateResource \
                      SetCategoryVariation \
                      SetIndividualVariationWithEmptyBase \
                      SetIndividualVariationWithFillBase \
                      Tic \
                      %s \
                      ' % test_method_name
    sequence_list.addSequenceString(sequence_string)
333
    sequence_list.play(self, quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
334

335
  def test_02_getVariationRangeCategoryList(self, quiet=quiet, run=run_all_test):
Romain Courteaud's avatar
Romain Courteaud committed
336 337 338 339
    """
      Test the method getVariationRangeCategoryList on a resource.
    """
    if not run: return
340
    self.genericTest('CheckGetVariationRangeCategoryList', quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
341

Kevin Deldycke's avatar
Kevin Deldycke committed
342
  def stepCheckGetVariationRangeCategoryItemList(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
343 344 345 346 347 348 349 350 351 352 353
                                                 sequence_list=None, **kw):
    """
      Check if getVariationRangeCategoryItemList returns the good result.
      Does not test display...
      Item are left display.
    """
    resource = sequence.get('resource')
    vrcl = resource.getVariationRangeCategoryList()
    vrcil = resource.getVariationRangeCategoryItemList()
    self.failIfDifferentSet(vrcl, map(lambda x: x[1], vrcil))

354
  def test_03_getVariationRangeCategoryItemList(self, quiet=quiet,
Romain Courteaud's avatar
Romain Courteaud committed
355 356 357 358 359
                                                run=run_all_test):
    """
      Test the method getVariationRangeCategoryItemList on a resource.
    """
    if not run: return
360
    self.genericTest('CheckGetVariationRangeCategoryItemList', quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
361

Kevin Deldycke's avatar
Kevin Deldycke committed
362
  def stepCheckGetVariationCategoryList(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
363 364
                                                 sequence_list=None, **kw):
    """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
365 366
    Check if getVariationCategoryList returns the good result, with default
    value for omit_individual_variation parameter
Romain Courteaud's avatar
Romain Courteaud committed
367 368 369 370 371
    """
    resource = sequence.get('resource')
    vcl = resource.getVariationCategoryList()
    self.failIfDifferentSet(self.category_list, vcl)

372
  def test_04_getVariationCategoryList(self, quiet=quiet, run=run_all_test):
Romain Courteaud's avatar
Romain Courteaud committed
373 374 375 376
    """
      Test the method getVariationCategoryList on a resource.
    """
    if not run: return
377
    self.genericTest('CheckGetVariationCategoryList', quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
378

Kevin Deldycke's avatar
Kevin Deldycke committed
379
  def stepCheckGetVariationCategoryListWithoutOmit(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
                                                 sequence_list=None, **kw):
    """
      Check if getVariationCategoryList returns the good result,
      with parameter omit_individual_variation=0.
    """
    resource = sequence.get('resource')
    vcl = resource.getVariationCategoryList(omit_individual_variation=0)
    correct_vcl = self.category_list[:]

    for base_category in resource.getVariationBaseCategoryList():
      # Check if resource has individual variations
      individual_variation_list = sequence.get(base_category)
      if individual_variation_list is not None:
        correct_vcl.extend(individual_variation_list)
    self.failIfDifferentSet(correct_vcl, vcl)

396
  def test_05_getVariationCategoryList(self, quiet=quiet, run=run_all_test):
Romain Courteaud's avatar
Romain Courteaud committed
397 398 399 400 401
    """
      Test the method getVariationCategoryList on a resource
      with parameter omit_individual_variation=0.
    """
    if not run: return
402
    self.genericTest('CheckGetVariationCategoryListWithoutOmit', quiet)
Romain Courteaud's avatar
Romain Courteaud committed
403

Kevin Deldycke's avatar
Kevin Deldycke committed
404
  def stepCheckGetVariationCategoryItemList(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
405 406 407 408 409 410 411 412 413 414
                                                 sequence_list=None, **kw):
    """
      Check if getVariationCategoryItemList returns the good result,
      with parameter omit_individual_variation=1.
    """
    resource = sequence.get('resource')
    vcl = resource.getVariationCategoryList()
    vcil = resource.getVariationCategoryItemList()
    self.failIfDifferentSet(vcl, map(lambda x: x[1], vcil))

415
  def test_06_getVariationCategoryItemList(self, quiet=quiet, run=run_all_test):
Romain Courteaud's avatar
Romain Courteaud committed
416 417 418 419
    """
      Test the method getVariationCategoryItemList on a resource.
    """
    if not run: return
420
    self.genericTest('CheckGetVariationCategoryItemList', quiet)
Romain Courteaud's avatar
Romain Courteaud committed
421

Kevin Deldycke's avatar
Kevin Deldycke committed
422
  def stepCheckGetVariationCategoryItemListWithoutOmit(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
423 424 425 426 427 428 429 430 431 432
                                                 sequence_list=None, **kw):
    """
      Check if getVariationCategoryItemList returns the good result,
      with parameter omit_individual_variation=0.
    """
    resource = sequence.get('resource')
    vcl = resource.getVariationCategoryList(omit_individual_variation=0)
    vcil = resource.getVariationCategoryItemList(omit_individual_variation=0)
    self.failIfDifferentSet(vcl, map(lambda x: x[1], vcil))

433
  def test_07_getVariationCategoryItemList(self, quiet=quiet, run=run_all_test):
Romain Courteaud's avatar
Romain Courteaud committed
434 435 436 437 438
    """
      Test the method getVariationCategoryItemList on a resource
      with parameter omit_individual_variation=0.
    """
    if not run: return
439 440
    self.genericTest('CheckGetVariationCategoryItemListWithoutOmit',
        quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
441

Kevin Deldycke's avatar
Kevin Deldycke committed
442
  def stepCheckGetVariationPropertyList(self, sequence=None,
443 444 445 446 447 448 449 450 451
                                        sequence_list=None, **kw):
    """
      Check if GetVariationPropertyList exists on a resource.
    """
    resource = sequence.get('resource')
    vpl = sequence.get('variation_property_list')
    self.failIfDifferentSet(resource.getVariationPropertyList(),
                            vpl)

Kevin Deldycke's avatar
Kevin Deldycke committed
452
  def stepCheckSetVariationPropertyList(self, sequence=None,
453 454 455 456 457 458 459 460 461 462 463 464
                                        sequence_list=None, **kw):
    """
      Check if SetVariationPropertyList exists on a resource.
      And test it.
    """
    resource = sequence.get('resource')
    vpl = ['prop1', 'prop2']
    sequence.edit(variation_property_list=vpl)
    resource.setVariationPropertyList(vpl)
    self.failIfDifferentSet(resource.variation_property_list,
                            vpl)

465
  def test_08_variationPropertyList(self, quiet=quiet, run=run_all_test):
466 467 468 469 470 471 472 473 474 475 476 477 478
    """
      Simply test if method are well generated by the property sheet.
    """
    if not run: return
    sequence_list = SequenceList()
    # Test when resource has no variation
    sequence_string = '\
                      CreateResource \
                      CheckGetVariationPropertyList \
                      CheckSetVariationPropertyList \
                      CheckGetVariationPropertyList \
                      '
    sequence_list.addSequenceString(sequence_string)
479
    sequence_list.play(self, quiet=quiet)
480

481 482 483 484 485 486 487
  def getPriceConfig(self):
    """
    Define somes cases of pricing configuration to test.
    """
    config = [
      {
        'base_price': None,
488 489 490
        'additional_price': None,
        'surcharge_ratio': None,
        'discount_ratio': None,
491 492 493 494
        'exclusive_discount_ratio': None,
        'price': None,
      },{
        'base_price': 5,
495 496 497
        'additional_price': None,
        'surcharge_ratio': None,
        'discount_ratio': None,
498 499 500 501
        'exclusive_discount_ratio': None,
        'price': 5,
      },{
        'base_price': 5,
502 503 504
        'additional_price': 1,
        'surcharge_ratio': None,
        'discount_ratio': None,
505 506 507 508
        'exclusive_discount_ratio': None,
        'price': 6,
      },{
        'base_price': 5,
509 510 511
        'additional_price': 3,
        'surcharge_ratio': 0.5,
        'discount_ratio': None,
512 513 514 515
        'exclusive_discount_ratio': None,
        'price': 12,
      },{
        'base_price': 5,
516 517 518
        'additional_price': 3,
        'surcharge_ratio': None,
        'discount_ratio': 0.25,
519 520 521 522
        'exclusive_discount_ratio': None,
        'price': 6,
      },{
        'base_price': 5,
523 524 525
        'additional_price': 3,
        'surcharge_ratio': None,
        'discount_ratio': None,
526 527 528 529
        'exclusive_discount_ratio': 0.5,
        'price': 4,
      },{
        'base_price': 5,
530 531 532
        'additional_price': 3,
        'surcharge_ratio': None,
        'discount_ratio': 0.5,
533 534 535 536
        'exclusive_discount_ratio': 0.75,
        'price': 2,
      },{
        'base_price': 5,
537 538 539
        'additional_price': 3,
        'surcharge_ratio': None,
        'discount_ratio': 0.75,
540 541 542 543
        'exclusive_discount_ratio': 0.25,
        'price': 2,
      },{
        'base_price': 5,
544 545 546
        'additional_price': 3,
        'surcharge_ratio': 1,
        'discount_ratio': 0.75,
547
        'exclusive_discount_ratio': 0.25,
548
        'price': 4,
549 550
      },{
        'base_price': None,
551 552 553
        'additional_price': 3,
        'surcharge_ratio': 1,
        'discount_ratio': 0.75,
554 555 556 557 558 559 560 561 562 563
        'exclusive_discount_ratio': 0.25,
        'price': None,
      }
    ]
    return config

  def logMessage(self, msg, tab=0):
    """
    Log a message.
    """
564 565
    if self.quiet:
      return
566 567 568 569 570
    if tab:
      msg = '  %s' % msg
    ZopeTestCase._print('\n%s' % msg)
    LOG('testResource.play', 0, msg)

571
  def test_09_getPrice(self, quiet=quiet, run=run_all_test):
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
    """
    Test the pricing model.
    """
    if not run: return
    config_list = self.getPriceConfig()
    for i in range(0, len(config_list)):
      self.logMessage("Starting New Pricing Case %i..." % i)
      config = config_list[i]
      # Create product
      self.logMessage("Creating product...", tab=1)
      product_module = self.portal.getDefaultModule(self.product_portal_type)
      product = product_module.newContent( \
                                   portal_type=self.product_portal_type,
                                   title='Product%i' % i)
      # Configure pricing parameters
      for key, value in config.items():
        if key != 'price':
          if value not in [None, []]:
            if type(value) != type([]):
              value_list = [value]
            else:
              value_list = value
            # Create requested supply line
            for pricing_param in value_list:
              self.logMessage("Creating supply line...", tab=1)
              supply_line = product.newContent(
598
                    portal_type=self.sale_supply_line_portal_type)
599
              # Set pricing parameter
600 601
              self.logMessage("Set %s on supply line with value %s..." % \
                              (key, str(pricing_param)), tab=1)
602 603 604
              supply_line.setProperty(key, pricing_param)
      # Commit transaction
      self.logMessage("Commit transaction...", tab=1)
605
      transaction.commit()
606 607 608 609 610 611 612
      # Tic
      self.logMessage("Tic...", tab=1)
      self.tic()
      # Check resource price
      self.logMessage("Check product price...", tab=1)
      self.assertEquals(config['price'], product.getPrice())

613
  def test_10_getPriceWithOptions(self, quiet=quiet, run=run_all_test):
614 615 616 617 618 619
    """
    Test the pricing model on a resource with options.
    """
    if not run: return
    i = 1
    self.logMessage("Starting New Option Pricing Case %i..." % i)
620 621 622 623
    # Fill the PDM preferences
    preference = self.portal.portal_preferences.default_site_preference
    preference.setPreferredProductOptionalVariationBaseCategoryList(['industrial_phase'])
    preference.enable()
624
    transaction.commit()
625
    self.tic()
Kevin Deldycke's avatar
Kevin Deldycke committed
626
    # Create another product/supply, in order to be sure that the
627 628 629 630 631 632 633 634 635
    # nothing will be generated from this supply!
    self.logMessage("Creating fake product...", tab=1)
    product_module = self.portal.getDefaultModule(self.product_portal_type)
    product = product_module.newContent( \
                                 portal_type=self.product_portal_type,
                                 title='FakeProduct%i' % i)
    product.setVariationCategoryList(self.industrial_phase_category_list)
    self.logMessage("Creating supply line...", tab=1)
    supply_line = product.newContent(
636
          portal_type=self.sale_supply_line_portal_type)
637 638 639 640
    supply_line.setProperty('base_price', 100)
    supply_line.setSurchargeRatioQuantityStepList([])
    supply_line.getCellKeyList(base_id='path_optional_surcharge_ratio')
    cell1 = supply_line.newCell('industrial_phase/phase1',
641
        base_id='path_optional_surcharge_ratio', 
642
        portal_type=self.sale_supply_cell_portal_type)
643 644 645 646
    cell1.setSurchargeRatio(20)
    cell1.setMappedValuePropertyList(["surcharge_ratio"])
    cell1.setMembershipCriterionBaseCategory('industrial_phase')
    cell1.setMembershipCriterionCategory('industrial_phase/phase1')
647 648 649 650 651 652 653 654 655 656 657
    # Create product
    self.logMessage("Creating product...", tab=1)
    product_module = self.portal.getDefaultModule(self.product_portal_type)
    product = product_module.newContent( \
                                 portal_type=self.product_portal_type,
                                 title='Product%i' % i)
    # Select some options on the resource
    product.setVariationCategoryList(self.industrial_phase_category_list)
    # Create requested supply line
    self.logMessage("Creating supply line...", tab=1)
    supply_line = product.newContent(
658
          portal_type=self.sale_supply_line_portal_type)
659 660 661 662 663 664
    # Set pricing parameter
    supply_line.setProperty('base_price', 1)
    # Define the additional price matrix range
    supply_line.setAdditionalPriceQuantityStepList([])
    supply_line.getCellKeyList(base_id='path_optional_additional_price')
    cell1 = supply_line.newCell('industrial_phase/phase1',
665
        base_id='path_optional_additional_price', 
666
        portal_type=self.sale_supply_cell_portal_type)
667
    cell1.setAdditionalPrice(2)
668 669 670
    cell1.setMappedValuePropertyList(["additional_price"])
    cell1.setMembershipCriterionBaseCategory('industrial_phase')
    cell1.setMembershipCriterionCategory('industrial_phase/phase1')
671
    cell2 = supply_line.newCell('industrial_phase/phase2',
672
        base_id='path_optional_additional_price', 
673
        portal_type=self.sale_supply_cell_portal_type)
674
    cell2.setAdditionalPrice(7)
675 676 677
    cell2.setMappedValuePropertyList(["additional_price"])
    cell2.setMembershipCriterionBaseCategory('industrial_phase')
    cell2.setMembershipCriterionCategory('industrial_phase/phase2')
678 679
    # Commit transaction
    self.logMessage("Commit transaction...", tab=1)
680
    transaction.commit()
681 682 683 684
    # Tic
    self.logMessage("Tic...", tab=1)
    self.tic()
    # Check resource price
685
    self.logMessage("Check product price without option...", tab=1)
686 687
    self.assertEquals(1, product.getPrice(context=supply_line))
    # Check resource option price
688 689
    self.logMessage("Check product price with option: %s..." % \
                    'industrial_phase/phase1', tab=1)
690 691
    self.assertEquals(3, product.getPrice(
                                   categories=['industrial_phase/phase1']))
692 693
    self.logMessage("Check product price with option: %s..." % \
                    'industrial_phase/phase2', tab=1)
694 695
    self.assertEquals(8, product.getPrice(
                                   categories=['industrial_phase/phase2']))
696 697 698 699 700
    self.logMessage("Check product price with options: %s..." % \
                    'industrial_phase/phase1 industrial_phase/phase2', tab=1)
    self.assertEquals(10, product.getPrice(
                                   categories=['industrial_phase/phase1',
                                               'industrial_phase/phase2']))
701

702
  def test_11_getPriceWithDestinationSection(self, quiet=quiet, run=run_all_test):
703 704
    """
    Test the pricing model with multiple price for 
705
    differents destination sections.
706 707 708 709 710 711
    """
    if not run: return
    # Initialize variables
    test_case_list = []
    # Create product
    product_module = self.portal.getDefaultModule(self.product_portal_type)
712
    supply_module = self.portal.getDefaultModule(self.sale_supply_portal_type)
713 714 715
    # Create generic supply
    self.logMessage("Creating generic fake supply ...", tab=1)
    generic_supply = supply_module.newContent(
716
                     portal_type=self.sale_supply_portal_type,
717
                     title='FakeGenericSupply',)
718 719
    # Create empty supply line
    supply_line = generic_supply.newContent(
720
          portal_type=self.sale_supply_line_portal_type)
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
    supply_line.setProperty('base_price', 0)
    for j in range(33, 35):
      self.logMessage("Creating fake product %s..." % j, tab=1)
      product = product_module.newContent(
                           portal_type=self.product_portal_type,
                           title='AnotherFakeProduct%s' % j)
      # Create some nodes
      node_module = self.portal.getDefaultModule(self.node_portal_type)
      for i in range(11, 14):
        self.logMessage("Creating fake node %s..." % i, tab=1)
        node = node_module.newContent(
                       portal_type=self.node_portal_type,
                       title='FakeNode%s%s' % (j, i))
        # Create a supply
        self.logMessage("Creating fake supply %s..." % i, tab=1)
        supply = supply_module.newContent(
737
                                     portal_type=self.sale_supply_portal_type,
738
                                     title='FakeSupply%s' % i,
739
                                     destination_section_value=node)
740 741
        self.logMessage("Creating fake supply line %s..." % i, tab=1)
        supply_line = supply.newContent(
742
              portal_type=self.sale_supply_line_portal_type,
743 744 745 746 747 748 749 750 751
              resource_value=product)
        # Set pricing parameter
        base_price = i*j
        supply_line.setProperty('base_price', base_price)
        # Register the case
        test_case_list.append((product, node, base_price))
      # Create generic supply line
      self.logMessage("Creating generic fake supply line ...", tab=1)
      supply_line = generic_supply.newContent(
752
            portal_type=self.sale_supply_line_portal_type,
753 754 755 756 757
            resource_value=product)
      supply_line.setProperty('base_price', j)
      test_case_list.append((product, None, j))
    # Commit transaction
    self.logMessage("Commit transaction...", tab=1)
758
    transaction.commit()
759 760 761 762 763 764
    # Tic
    self.logMessage("Tic...", tab=1)
    self.tic()
    # Test the cases
    for product, node, base_price in test_case_list:
      if node is not None:
765
        self.logMessage("Check product %s with destination section %s" % \
766 767 768 769
                        (product.getTitle(), node.getTitle()),
                        tab=1)
        self.assertEquals(base_price, 
                          product.getPrice(
770
                    categories=['destination_section/%s' % node.getRelativeUrl()]))
771
      else:
772
        self.logMessage("Check product %s without destination section" % \
773 774 775 776
                        product.getTitle(),
                        tab=1)
        self.assertEquals(base_price, 
                          product.getPrice())
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792

  def test_11b_getPriceWithCells(self, quiet=quiet, run=run_all_test):
    """
    Test the pricing model with multiple price for 
    differents destination sections, using supply cells
    """
    if not run: return
    # Initialize variables
    test_case_list = []
    # Create product
    product_module = self.portal.getDefaultModule(self.product_portal_type)
    supply_module = self.portal.getDefaultModule(self.sale_supply_portal_type)
    # Create generic supply
    self.logMessage("Creating generic fake supply ...", tab=1)
    generic_supply = supply_module.newContent(
                     portal_type=self.sale_supply_portal_type,
793
                     title='FakeGenericSupply',)
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 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
    # Create empty supply line
    supply_line = generic_supply.newContent(
          portal_type=self.sale_supply_line_portal_type)
    supply_line.setProperty('base_price', 0)
    for j in range(33, 35):
      self.logMessage("Creating fake product %s..." % j, tab=1)
      product = product_module.newContent(
                           portal_type=self.product_portal_type,
                           title='AnotherFakeProduct%s' % j)
      product.setVariationBaseCategoryList(['size'])
      product.setVariationCategoryList(['size/Baby', 'size/Man'])
      # Create some nodes
      node_module = self.portal.getDefaultModule(self.node_portal_type)
      for i in range(11, 14):
        self.logMessage("Creating fake node %s..." % i, tab=1)
        node = node_module.newContent(
                       portal_type=self.node_portal_type,
                       title='FakeNode%s%s' % (j, i))
        # Create a supply
        self.logMessage("Creating fake supply %s..." % i, tab=1)
        supply = supply_module.newContent(
                                     portal_type=self.sale_supply_portal_type,
                                     title='FakeSupply%s' % i,
                                     destination_section_value=node)

        if 0:
          # XXX if both a supply line for the resource and a supply cell for
          # the resource with the exact variation can be applied, one of them
          # is choosen randomly. It looks like a bug, but I'm not sure we
          # should handle such situation.
          self.logMessage("Creating wrong supply line %s..." % i, tab=1)
          wrong_supply_line = supply.newContent(
                portal_type=self.sale_supply_line_portal_type,
                resource_value=product)
          wrong_supply_line.setBasePrice(12454326)

        self.logMessage("Creating fake supply line %s..." % i, tab=1)
        supply_line = supply.newContent(
              portal_type=self.sale_supply_line_portal_type,
              resource_value=product)
        supply_line.setPVariationBaseCategoryList(['size'])
        supply_line.updateCellRange(base_id='path')

        baby_cell = supply_line.newCell('size/Baby',
                           portal_type=self.sale_supply_cell_portal_type)
        baby_cell.setVariationCategoryList(['size/Baby'])
        baby_cell.setPredicateCategoryList(['size/Baby'])
        baby_cell.setMappedValuePropertyList(['base_price'])
        baby_cell.setMembershipCriterionBaseCategory('size')
        baby_cell.setMembershipCriterionCategory('size/Baby')
        base_price = i*j
        baby_cell.setProperty('base_price', base_price)
        # Register the case
        test_case_list.append((product, 'size/Baby', node, base_price))

        man_cell = supply_line.newCell('size/Man',
                        portal_type=self.sale_supply_cell_portal_type)
        man_cell.setVariationCategoryList(['size/Man'])
        man_cell.setPredicateCategoryList(['size/Man'])
        man_cell.setMappedValuePropertyList(['base_price'])
        man_cell.setMembershipCriterionBaseCategory('size')
        man_cell.setMembershipCriterionCategory('size/Man')
        base_price = i*j+3
        man_cell.setProperty('base_price', base_price)
        # Register the case
        test_case_list.append((product, 'size/Man', node, base_price))

      # Create generic supply line
      self.logMessage("Creating generic fake supply line ...", tab=1)
      supply_line = generic_supply.newContent(
            portal_type=self.sale_supply_line_portal_type,
            resource_value=product)
      supply_line.setProperty('base_price', j)
      test_case_list.append((product, None, None, j))

    # Commit transaction
    self.logMessage("Commit transaction...", tab=1)
871
    transaction.commit()
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
    # Tic
    self.logMessage("Tic...", tab=1)
    self.tic()
    # Test the cases
    for product, variation, node, base_price in test_case_list:
      if node is not None:
        self.logMessage("Check product %s with destination section %s" % \
                        (product.getTitle(), node.getTitle()),
                        tab=1)
        self.assertEquals(base_price,
             product.getPrice(
               categories=['destination_section/%s' % node.getRelativeUrl(),
                           variation]))
      else:
        self.logMessage("Check product %s without destination section" % \
                        product.getTitle(),
                        tab=1)
        self.assertEquals(base_price,
                          product.getPrice(categories=[variation]))
891
  
892

893
  def test_12_getPurchaseVsSalePrice(self, quiet=quiet, run=run_all_test):
894 895
    """
    Test the pricing model with purchase and sale supply lines, and with
896
    source_section/destination_section.
897 898 899 900 901 902 903 904
    """
    if not run: return
    # Initialize variables
    product_module = self.portal.getDefaultModule(self.product_portal_type)
    organisation_module = self.getOrganisationModule()
    currency_module = self.getCurrencyModule()
    sale_order_module = self.portal.getDefaultModule("Sale Order")
    purchase_order_module = self.portal.getDefaultModule("Purchase Order")
905
    # Create product
906 907 908 909 910 911 912 913 914 915 916 917 918 919
    product = product_module.newContent(
        portal_type=self.product_portal_type,
        title="yet another product")
    # Create organisations
    orga1 = organisation_module.newContent(
        portal_type="Organisation",
        title="orga1")
    orga2 = organisation_module.newContent(
        portal_type="Organisation",
        title="orga2")
    # Create sale supply lines
    product.newContent(
        portal_type=self.sale_supply_line_portal_type,
        base_price=100.0,
920
        destination_section_value=orga1)
921 922 923
    product.newContent(
        portal_type=self.sale_supply_line_portal_type,
        base_price=200.0,
924
        destination_section_value=orga2)
925 926 927 928 929 930 931
    product.newContent(
        portal_type=self.sale_supply_line_portal_type,
        base_price=400.0)
    # Create purchase supply lines
    product.newContent(
        portal_type=self.purchase_supply_line_portal_type,
        base_price=10.0,
932
        source_section_value=orga1)
933 934 935
    product.newContent(
        portal_type=self.purchase_supply_line_portal_type,
        base_price=20.0,
936
        source_section_value=orga2)
937 938 939 940 941 942 943 944 945
    product.newContent(
        portal_type=self.purchase_supply_line_portal_type,
        base_price=40.0)
    # Create sale order and check price
    sale_order = sale_order_module.newContent(
        portal_type="Sale Order",
        start_date=DateTime(),
        stop_date=DateTime())
    sale_order_line = sale_order.newContent(
946
        portal_type=self.sale_order_line_portal_type,
947
        resource_value=product)
948
    transaction.commit()
949 950
    self.tic()
    self.assertEquals(sale_order_line.getPrice(), 400.0)
951
    sale_order.setDestinationSectionValue(orga2)
952
    transaction.commit()
953 954 955 956 957 958 959 960 961 962 963
    self.tic()
    sale_order_line.setPrice(None)
    self.assertEquals(sale_order_line.getPrice(), 200.0)
    # Create purchase order and check price
    purchase_order = purchase_order_module.newContent(
        portal_type="Purchase Order",
        start_date=DateTime(),
        stop_date=DateTime())
    purchase_order_line = purchase_order.newContent(
        portal_type="Purchase Order Line",
        resource_value=product)
964
    transaction.commit()
965 966
    self.tic()
    self.assertEquals(purchase_order_line.getPrice(), 40.0)
967
    purchase_order.setSourceSectionValue(orga2)
968
    transaction.commit()
969 970 971 972
    self.tic()
    purchase_order_line.setPrice(None)
    self.assertEquals(purchase_order_line.getPrice(), 20.0)
  
973 974 975 976 977 978 979
  def testGetPriceWithQuantityUnit(self):
    resource = self.portal.getDefaultModule(self.product_portal_type)\
                .newContent(portal_type=self.product_portal_type)
    resource.setDefaultQuantityUnitValue(self.quantity_unit_kilo)
    supply_line = resource.newContent(
                    portal_type=self.sale_supply_line_portal_type)
    supply_line.setBasePrice(1000)
980
    transaction.commit()
981 982 983 984
    self.tic()
    sale_order = self.portal.getDefaultModule("Sale Order").newContent(
                              portal_type='Sale Order',)
    sale_order_line = sale_order.newContent(
985
                          portal_type=self.sale_order_line_portal_type,
986 987 988 989 990 991 992
                          resource_value=resource,
                          quantity=5)
    self.assertEquals(1000, sale_order_line.getPrice())
    self.assertEquals(5000, sale_order_line.getTotalPrice())
    
    # if we give the quantity unit in grams
    sale_order_line = sale_order.newContent(
993
                          portal_type=self.sale_order_line_portal_type,
994 995 996 997 998 999
                          resource_value=resource,
                          quantity=5000,
                          quantity_unit_value=self.quantity_unit_gram)
    self.assertEquals(1, sale_order_line.getPrice())
    self.assertEquals(5000, sale_order_line.getTotalPrice())

1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
  def testGetPriceWithPriceCurrency(self):
    currency_module = self.portal.getDefaultModule("Currency")
    currency = currency_module.newContent(
                     portal_type="Currency",
                     title='A great currency')
    other_currency = currency_module.newContent(
                     portal_type="Currency",
                     title='Another currency')

    resource = self.portal.getDefaultModule(self.product_portal_type)\
                .newContent(portal_type=self.product_portal_type)
    resource.setDefaultQuantityUnitValue(self.quantity_unit_kilo)
    supply_line = resource.newContent(
                    portal_type=self.sale_supply_line_portal_type)
    supply_line.setBasePrice(1000)
    supply_line.setPriceCurrencyValue(currency)
    transaction.commit()
    self.tic()
    sale_order = self.portal.getDefaultModule("Sale Order").newContent(
                              portal_type='Sale Order',
                              price_currency_value=other_currency)
    sale_order_line = sale_order.newContent(
1022
                          portal_type=self.sale_order_line_portal_type,
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
                          resource_value=resource,
                          quantity=5)
    # order and supply lines uses different currency, price does not apply
    self.assertEquals(None, sale_order_line.getPrice())
    
    # set the same currency
    sale_order.setPriceCurrencyValue(currency)

    # price applies
    self.assertEquals(1000, sale_order_line.getPrice())
    self.assertEquals(5000, sale_order_line.getTotalPrice())
    
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
  def testQuantityPrecision(self):
    """test how to define quantity precision on resources.
    """
    resource = self.portal.getDefaultModule(self.product_portal_type)\
                .newContent(portal_type=self.product_portal_type)
    # default is 1
    self.assertEquals(1, resource.getBaseUnitQuantity())
    self.assertEquals(0, resource.getQuantityPrecision())
    # quantity precision is calculated using base quantity unit
    resource.setBaseUnitQuantity(0.001)
    self.assertEquals(3, resource.getQuantityPrecision())
1046

1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
  def test_defaultSupplyLineAfterClone(self):
    """Check that default supply line is properly set up after clone"""
    resource = self.portal.getDefaultModule(self.product_portal_type)\
                .newContent(portal_type=self.product_portal_type)

    resource.edit( purchase_supply_line_base_price=1.0,
      sale_supply_line_base_price=1.0,
    )

    self.assertEqual( resource,
        resource.getDefaultPurchaseSupplyLineValue().getResourceValue() )
    self.assertEqual( resource,
        resource.getDefaultSaleSupplyLineValue().getResourceValue() )

    module = resource.getParentValue()

    cb_data = module.manage_copyObjects(ids=[resource.getId()])
    p_data = module.manage_pasteObjects(cb_data)

    new_resource = module._getOb(p_data[0]['new_id'])

    self.assertEqual(
      new_resource,
      new_resource.getDefaultPurchaseSupplyLineValue().getResourceValue()
    )

    self.assertEqual(
      new_resource,
      new_resource.getDefaultSaleSupplyLineValue().getResourceValue()
    )
1077 1078 1079 1080 1081

def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestResource))
  return suite