testResource.py 52.5 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
from unittest import expectedFailure
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
Romain Courteaud's avatar
Romain Courteaud committed
34
from zLOG import LOG
35
from Products.ERP5Type.tests.Sequence import SequenceList
36
from DateTime import DateTime
Romain Courteaud's avatar
Romain Courteaud committed
37 38 39 40 41 42

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

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

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

  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)

79
  def setUpPreferences(self):
Fabien Morin's avatar
Fabien Morin committed
80 81 82 83 84 85 86
    #create apparel variation preferences
    portal_preferences = self.getPreferenceTool()
    preference = getattr(portal_preferences, 'test_site_preference', None)
    if preference is None:
      preference = portal_preferences.newContent(portal_type='System Preference',
                                title='Default Site Preference',
                                id='test_site_preference')
Jérome Perrin's avatar
Jérome Perrin committed
87 88
      if preference.getPreferenceState() == 'disabled':
        preference.enable()
89

90
    preference.setPreferredApparelModelVariationBaseCategoryList(('size', 'industrial_phase',))
Fabien Morin's avatar
Fabien Morin committed
91 92
    preference.setPreferredApparelClothVariationBaseCategoryList(('size',))
    preference.setPreferredApparelComponentVariationBaseCategoryList(('variation',))
93
    preference.setPreferredApparelModelIndividualVariationBaseCategoryList(('colour', 'morphology'))
Fabien Morin's avatar
Fabien Morin committed
94 95
    if preference.getPreferenceState() == 'disabled':
      preference.enable()
96 97
    self.tic()

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

Jérome Perrin's avatar
Jérome Perrin committed
105
  def beforeTearDown(self):
106
    self.abort()
Jérome Perrin's avatar
Jérome Perrin committed
107 108 109 110 111 112 113 114 115 116
    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()])
    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
    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',
                                      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',
                                      id='kilo')

173 174 175 176 177 178
    unit_conversion_module = self.portal.quantity_unit_conversion_module
    weight_group = unit_conversion_module._getOb('weight', None)
    if weight_group is None:
      weight_group = unit_conversion_module.newContent(id='weight',
                                  portal_type='Quantity Unit Conversion Group',
                                  quantity_unit='weight/kilo')
179
      weight_group.validate()
180 181 182 183 184 185 186

    gram_definition = weight_group._getOb('gram', None)
    if gram_definition is None:
      gram_definition = weight_group.newContent(id='gram',
                              portal_type='Quantity Unit Conversion Definition',
                              quantity_unit='weight/gram',
                              quantity=0.001)
187
      gram_definition.validate()
188

189 190 191 192 193 194
    # create some product line categories
    product_line = self.portal.portal_categories.product_line
    if product_line._getOb('a', None) is None:
      product_line.newContent(
          id='a',
          portal_type='Category')
195 196 197
      product_line.a.newContent(
          id='a1',
          portal_type='Category')
198 199 200 201
    if product_line._getOb('b', None) is None:
      product_line.newContent(
          id='b',
          portal_type='Category')
202

Romain Courteaud's avatar
Romain Courteaud committed
203 204 205 206 207 208 209 210 211 212
  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"
    )
213 214
    sequence.edit(resource=resource,
                  variation_property_list=[])
Romain Courteaud's avatar
Romain Courteaud committed
215 216 217 218 219
    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
220
  def stepCheckGetVariationBaseCategoryList(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
221 222 223 224 225 226 227 228
                                             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
229
  def stepCheckGetVariationRangeCategoryList(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
                                             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
255
    resource.setSizeList(size_list)
Romain Courteaud's avatar
Romain Courteaud committed
256 257
    self.category_list = self.size_list[:]

Kevin Deldycke's avatar
Kevin Deldycke committed
258
  def stepSetIndividualVariationWithEmptyBase(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
259 260
                                              sequence_list=None, **kw):
    """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
261 262
    Set the individual variation of the current resource to a base category
    that contains no subobjects.
Romain Courteaud's avatar
Romain Courteaud committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
    """
    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
278
  def stepSetIndividualVariationWithFillBase(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
279 280
                                              sequence_list=None, **kw):
    """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
281 282
    Set the individual variation of the current resource to a base category
    that contains some subobjects.
Romain Courteaud's avatar
Romain Courteaud committed
283 284 285
    """
    resource = sequence.get('resource')
    colour_list = []
Kevin Deldycke's avatar
Kevin Deldycke committed
286
    colour_variation_count = 1
Romain Courteaud's avatar
Romain Courteaud committed
287 288 289 290 291 292 293 294 295 296
    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)

297
  def test_01_getVariationBaseCategoryList(self, quiet=quiet, run=run_all_test):
Romain Courteaud's avatar
Romain Courteaud committed
298 299 300 301 302 303 304 305 306 307 308
    """
      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)
309
    sequence_list.play(self, quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
310

311
  def genericTest(self, test_method_name, quiet=quiet):
Romain Courteaud's avatar
Romain Courteaud committed
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    """
      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)
357
    sequence_list.play(self, quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
358

359
  def test_02_getVariationRangeCategoryList(self, quiet=quiet, run=run_all_test):
Romain Courteaud's avatar
Romain Courteaud committed
360 361 362 363
    """
      Test the method getVariationRangeCategoryList on a resource.
    """
    if not run: return
364
    self.genericTest('CheckGetVariationRangeCategoryList', quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
365

Kevin Deldycke's avatar
Kevin Deldycke committed
366
  def stepCheckGetVariationRangeCategoryItemList(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
367 368 369 370 371 372 373 374 375 376 377
                                                 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))

378
  def test_03_getVariationRangeCategoryItemList(self, quiet=quiet,
Romain Courteaud's avatar
Romain Courteaud committed
379 380 381 382 383
                                                run=run_all_test):
    """
      Test the method getVariationRangeCategoryItemList on a resource.
    """
    if not run: return
384
    self.genericTest('CheckGetVariationRangeCategoryItemList', quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
385

Kevin Deldycke's avatar
Kevin Deldycke committed
386
  def stepCheckGetVariationCategoryList(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
387 388
                                                 sequence_list=None, **kw):
    """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
389 390
    Check if getVariationCategoryList returns the good result, with default
    value for omit_individual_variation parameter
Romain Courteaud's avatar
Romain Courteaud committed
391 392 393 394 395
    """
    resource = sequence.get('resource')
    vcl = resource.getVariationCategoryList()
    self.failIfDifferentSet(self.category_list, vcl)

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

Kevin Deldycke's avatar
Kevin Deldycke committed
403
  def stepCheckGetVariationCategoryListWithoutOmit(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
                                                 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)

420
  def test_05_getVariationCategoryList(self, quiet=quiet, run=run_all_test):
Romain Courteaud's avatar
Romain Courteaud committed
421 422 423 424 425
    """
      Test the method getVariationCategoryList on a resource
      with parameter omit_individual_variation=0.
    """
    if not run: return
426
    self.genericTest('CheckGetVariationCategoryListWithoutOmit', quiet)
Romain Courteaud's avatar
Romain Courteaud committed
427

Kevin Deldycke's avatar
Kevin Deldycke committed
428
  def stepCheckGetVariationCategoryItemList(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
429 430 431 432 433 434 435 436 437 438
                                                 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))

439
  def test_06_getVariationCategoryItemList(self, quiet=quiet, run=run_all_test):
Romain Courteaud's avatar
Romain Courteaud committed
440 441 442 443
    """
      Test the method getVariationCategoryItemList on a resource.
    """
    if not run: return
444
    self.genericTest('CheckGetVariationCategoryItemList', quiet)
Romain Courteaud's avatar
Romain Courteaud committed
445

Kevin Deldycke's avatar
Kevin Deldycke committed
446
  def stepCheckGetVariationCategoryItemListWithoutOmit(self, sequence=None,
Romain Courteaud's avatar
Romain Courteaud committed
447 448 449 450 451 452 453 454 455 456
                                                 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))

457
  def test_07_getVariationCategoryItemList(self, quiet=quiet, run=run_all_test):
Romain Courteaud's avatar
Romain Courteaud committed
458 459 460 461 462
    """
      Test the method getVariationCategoryItemList on a resource
      with parameter omit_individual_variation=0.
    """
    if not run: return
463 464
    self.genericTest('CheckGetVariationCategoryItemListWithoutOmit',
        quiet=quiet)
Romain Courteaud's avatar
Romain Courteaud committed
465

Kevin Deldycke's avatar
Kevin Deldycke committed
466
  def stepCheckGetVariationPropertyList(self, sequence=None,
467 468 469 470 471 472 473 474 475
                                        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
476
  def stepCheckSetVariationPropertyList(self, sequence=None,
477 478 479 480 481 482 483 484 485 486 487 488
                                        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)

489
  def test_08_variationPropertyList(self, quiet=quiet, run=run_all_test):
490 491 492 493 494 495 496 497 498 499 500 501 502
    """
      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)
503
    sequence_list.play(self, quiet=quiet)
504

505 506 507 508 509 510 511
  def getPriceConfig(self):
    """
    Define somes cases of pricing configuration to test.
    """
    config = [
      {
        'base_price': None,
512 513 514
        'additional_price': None,
        'surcharge_ratio': None,
        'discount_ratio': None,
515 516 517 518
        'exclusive_discount_ratio': None,
        'price': None,
      },{
        'base_price': 5,
519 520 521
        'additional_price': None,
        'surcharge_ratio': None,
        'discount_ratio': None,
522 523 524 525
        'exclusive_discount_ratio': None,
        'price': 5,
      },{
        'base_price': 5,
526 527 528
        'additional_price': 1,
        'surcharge_ratio': None,
        'discount_ratio': None,
529 530 531 532
        'exclusive_discount_ratio': None,
        'price': 6,
      },{
        'base_price': 5,
533 534 535
        'additional_price': 3,
        'surcharge_ratio': 0.5,
        'discount_ratio': None,
536 537 538 539
        'exclusive_discount_ratio': None,
        'price': 12,
      },{
        'base_price': 5,
540 541 542
        'additional_price': 3,
        'surcharge_ratio': None,
        'discount_ratio': 0.25,
543 544 545 546
        'exclusive_discount_ratio': None,
        'price': 6,
      },{
        'base_price': 5,
547 548 549
        'additional_price': 3,
        'surcharge_ratio': None,
        'discount_ratio': None,
550 551 552 553
        'exclusive_discount_ratio': 0.5,
        'price': 4,
      },{
        'base_price': 5,
554 555 556
        'additional_price': 3,
        'surcharge_ratio': None,
        'discount_ratio': 0.5,
557 558 559 560
        'exclusive_discount_ratio': 0.75,
        'price': 2,
      },{
        'base_price': 5,
561 562 563
        'additional_price': 3,
        'surcharge_ratio': None,
        'discount_ratio': 0.75,
564 565 566 567
        'exclusive_discount_ratio': 0.25,
        'price': 2,
      },{
        'base_price': 5,
568 569 570
        'additional_price': 3,
        'surcharge_ratio': 1,
        'discount_ratio': 0.75,
571
        'exclusive_discount_ratio': 0.25,
572
        'price': 4,
573 574
      },{
        'base_price': None,
575 576 577
        'additional_price': 3,
        'surcharge_ratio': 1,
        'discount_ratio': 0.75,
578 579 580 581 582 583 584 585 586 587
        'exclusive_discount_ratio': 0.25,
        'price': None,
      }
    ]
    return config

  def logMessage(self, msg, tab=0):
    """
    Log a message.
    """
588 589
    if self.quiet:
      return
590 591 592 593 594
    if tab:
      msg = '  %s' % msg
    ZopeTestCase._print('\n%s' % msg)
    LOG('testResource.play', 0, msg)

595
  def test_09_getPrice(self, quiet=quiet, run=run_all_test):
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
    """
    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(
622
                    portal_type=self.sale_supply_line_portal_type)
623
              # Set pricing parameter
624 625
              self.logMessage("Set %s on supply line with value %s..." % \
                              (key, str(pricing_param)), tab=1)
626 627 628
              supply_line.setProperty(key, pricing_param)
      # Commit transaction
      self.logMessage("Commit transaction...", tab=1)
629
      self.commit()
630 631 632 633 634
      # Tic
      self.logMessage("Tic...", tab=1)
      self.tic()
      # Check resource price
      self.logMessage("Check product price...", tab=1)
635
      self.assertEqual(config['price'], product.getPrice())
636

637
  def test_10_getPriceWithOptions(self, quiet=quiet, run=run_all_test):
638 639 640 641 642 643
    """
    Test the pricing model on a resource with options.
    """
    if not run: return
    i = 1
    self.logMessage("Starting New Option Pricing Case %i..." % i)
644 645 646
    # Fill the PDM preferences
    preference = self.portal.portal_preferences.default_site_preference
    preference.setPreferredProductOptionalVariationBaseCategoryList(['industrial_phase'])
647 648
    if preference.getPreferenceState() == 'disabled':
      preference.enable()
649
    self.tic()
Kevin Deldycke's avatar
Kevin Deldycke committed
650
    # Create another product/supply, in order to be sure that the
651 652 653 654 655 656 657 658 659
    # 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(
660
          portal_type=self.sale_supply_line_portal_type)
661 662 663 664
    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',
665
        base_id='path_optional_surcharge_ratio',
666
        portal_type=self.sale_supply_cell_portal_type)
667 668 669 670
    cell1.setSurchargeRatio(20)
    cell1.setMappedValuePropertyList(["surcharge_ratio"])
    cell1.setMembershipCriterionBaseCategory('industrial_phase')
    cell1.setMembershipCriterionCategory('industrial_phase/phase1')
671 672 673 674 675 676 677 678 679 680 681
    # 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(
682
          portal_type=self.sale_supply_line_portal_type)
683 684 685 686 687 688
    # 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',
689
        base_id='path_optional_additional_price',
690
        portal_type=self.sale_supply_cell_portal_type)
691
    cell1.setAdditionalPrice(2)
692 693 694
    cell1.setMappedValuePropertyList(["additional_price"])
    cell1.setMembershipCriterionBaseCategory('industrial_phase')
    cell1.setMembershipCriterionCategory('industrial_phase/phase1')
695
    cell2 = supply_line.newCell('industrial_phase/phase2',
696
        base_id='path_optional_additional_price',
697
        portal_type=self.sale_supply_cell_portal_type)
698
    cell2.setAdditionalPrice(7)
699 700 701
    cell2.setMappedValuePropertyList(["additional_price"])
    cell2.setMembershipCriterionBaseCategory('industrial_phase')
    cell2.setMembershipCriterionCategory('industrial_phase/phase2')
702 703
    # Commit transaction
    self.logMessage("Commit transaction...", tab=1)
704
    self.commit()
705 706 707 708
    # Tic
    self.logMessage("Tic...", tab=1)
    self.tic()
    # Check resource price
709
    self.logMessage("Check product price without option...", tab=1)
710
    self.assertEqual(1, product.getPrice(context=supply_line))
711
    # Check resource option price
712 713
    self.logMessage("Check product price with option: %s..." % \
                    'industrial_phase/phase1', tab=1)
714
    self.assertEqual(3, product.getPrice(
715
                                   categories=['industrial_phase/phase1']))
716 717
    self.logMessage("Check product price with option: %s..." % \
                    'industrial_phase/phase2', tab=1)
718
    self.assertEqual(8, product.getPrice(
719
                                   categories=['industrial_phase/phase2']))
720 721
    self.logMessage("Check product price with options: %s..." % \
                    'industrial_phase/phase1 industrial_phase/phase2', tab=1)
722
    self.assertEqual(10, product.getPrice(
723 724
                                   categories=['industrial_phase/phase1',
                                               'industrial_phase/phase2']))
725

726
  def test_11_getPriceWithDestinationSection(self, quiet=quiet, run=run_all_test):
727
    """
728
    Test the pricing model with multiple price for
729
    differents destination sections.
730 731 732 733 734 735
    """
    if not run: return
    # Initialize variables
    test_case_list = []
    # Create product
    product_module = self.portal.getDefaultModule(self.product_portal_type)
736
    supply_module = self.portal.getDefaultModule(self.sale_supply_portal_type)
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
    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(
752
                                     portal_type=self.sale_supply_portal_type,
753
                                     title='FakeSupply%s' % i,
754
                                     destination_section_value=node)
755
        supply.validate()
756 757
        self.logMessage("Creating fake supply line %s..." % i, tab=1)
        supply_line = supply.newContent(
758
              portal_type=self.sale_supply_line_portal_type,
759 760 761 762 763 764 765 766
              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))
    # Commit transaction
    self.logMessage("Commit transaction...", tab=1)
767
    self.commit()
768 769 770 771 772
    # Tic
    self.logMessage("Tic...", tab=1)
    self.tic()
    # Test the cases
    for product, node, base_price in test_case_list:
773 774 775
      self.logMessage("Check product %s with destination section %s" % \
                      (product.getTitle(), node.getTitle()),
                      tab=1)
776
      self.assertEqual(base_price,
777 778
                        product.getPrice(
                  categories=['destination_section/%s' % node.getRelativeUrl()]))
779 780 781

  def test_11b_getPriceWithCells(self, quiet=quiet, run=run_all_test):
    """
782
    Test the pricing model with multiple price for
783 784 785 786 787 788 789 790 791 792 793 794
    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,
795
                     title='FakeGenericSupply',)
796
    generic_supply.validate()
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
    # 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)
821
        supply.validate()
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 871 872 873 874

        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)
875
    self.commit()
876 877 878 879 880
    # Tic
    self.logMessage("Tic...", tab=1)
    self.tic()
    # Test the cases
    for product, variation, node, base_price in test_case_list:
881
      categories = []
882 883 884 885
      if node is not None:
        self.logMessage("Check product %s with destination section %s" % \
                        (product.getTitle(), node.getTitle()),
                        tab=1)
886
        categories.append('destination_section/' + node.getRelativeUrl())
887 888 889 890
      else:
        self.logMessage("Check product %s without destination section" % \
                        product.getTitle(),
                        tab=1)
891 892
      if variation:
        categories.append(variation)
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915

      def sortResult(a, b):
        def _pricingSortMethod(a, b): # XXX copied from Resource.py
          # Simple method : the one that defines a destination section wins
          if a.getDestinationSection():
            return -1 # a defines a destination section and wins
          return 1 # a defines no destination section and loses
        if _pricingSortMethod(a, b):
          # now sort based on resource definition
          if a.getResourceValue():
            if b.getResourceValue():
              return 1
            else:
              return -1
          else:
            return 1
        else:
          return -1


      self.assertEqual(base_price, product.getPrice(categories=categories,
                                                    sort_method=sortResult))

916

917 918 919
  # The following test tests Movement.getPrice, which is based on the movement
  # context.

920
  def test_12_getInternalVsPurchaseVsSalePrice(self, quiet=quiet, run=run_all_test):
921
    """
922 923
    Test the pricing model with internal, purchase and sale supply
    lines, and with source_section/destination_section.
924 925 926 927 928 929 930 931
    """
    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")
932
    internal_packing_list_module = self.portal.getDefaultModule("Internal Packing List")
933
    # Create product
934 935 936 937 938 939 940 941 942 943 944 945 946 947
    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,
948
        destination_section_value=orga1)
949 950 951
    product.newContent(
        portal_type=self.sale_supply_line_portal_type,
        base_price=200.0,
952
        destination_section_value=orga2)
953 954 955 956 957 958 959
    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,
960
        source_section_value=orga1)
961 962 963
    product.newContent(
        portal_type=self.purchase_supply_line_portal_type,
        base_price=20.0,
964
        source_section_value=orga2)
965 966 967
    product.newContent(
        portal_type=self.purchase_supply_line_portal_type,
        base_price=40.0)
968 969 970 971 972 973 974 975 976 977 978 979
    # Create internal supply lines
    product.newContent(
        portal_type=self.internal_supply_line_portal_type,
        base_price=1.0,
        destination_section_value=orga1)
    product.newContent(
        portal_type=self.internal_supply_line_portal_type,
        base_price=2.0,
        destination_section_value=orga2)
    product.newContent(
        portal_type=self.internal_supply_line_portal_type,
        base_price=4.0)
980 981 982 983 984 985
    # 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(
986
        portal_type=self.sale_order_line_portal_type,
987 988
        resource_value=product)
    self.tic()
989
    self.assertEqual(sale_order_line.getPrice(), 400.0)
990
    sale_order.setDestinationSectionValue(orga2)
991 992
    self.tic()
    sale_order_line.setPrice(None)
993
    self.assertEqual(sale_order_line.getPrice(), 200.0)
994 995 996 997 998 999 1000 1001 1002
    # 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)
    self.tic()
1003
    self.assertEqual(purchase_order_line.getPrice(), 40.0)
1004
    purchase_order.setSourceSectionValue(orga2)
1005 1006
    self.tic()
    purchase_order_line.setPrice(None)
1007
    self.assertEqual(purchase_order_line.getPrice(), 20.0)
1008 1009 1010 1011 1012 1013 1014 1015 1016
    # Create internal packing list and check price
    internal_packing_list = internal_packing_list_module.newContent(
        portal_type="Internal Packing List",
        start_date=DateTime(),
        stop_date=DateTime())
    internal_packing_list_line = internal_packing_list.newContent(
        portal_type="Internal Packing List Line",
        resource_value=product)
    self.tic()
1017
    self.assertEqual(internal_packing_list_line.getPrice(), 4.0)
1018 1019 1020
    internal_packing_list.setDestinationSectionValue(orga2)
    self.tic()
    internal_packing_list_line.setPrice(None)
1021
    self.assertEqual(internal_packing_list_line.getPrice(), 2.0)
1022

1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
  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)
    self.tic()
    sale_order = self.portal.getDefaultModule("Sale Order").newContent(
                              portal_type='Sale Order',)
    sale_order_line = sale_order.newContent(
1034
                          portal_type=self.sale_order_line_portal_type,
1035 1036
                          resource_value=resource,
                          quantity=5)
1037 1038
    self.assertEqual(1000, sale_order_line.getPrice())
    self.assertEqual(5000, sale_order_line.getTotalPrice())
1039

1040 1041
    # if we give the quantity unit in grams
    sale_order_line = sale_order.newContent(
1042
                          portal_type=self.sale_order_line_portal_type,
1043 1044 1045
                          resource_value=resource,
                          quantity=5000,
                          quantity_unit_value=self.quantity_unit_gram)
1046 1047
    self.assertEqual(1, sale_order_line.getPrice())
    self.assertEqual(5000, sale_order_line.getTotalPrice())
1048

1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
  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)
    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(
1070
                          portal_type=self.sale_order_line_portal_type,
1071 1072 1073
                          resource_value=resource,
                          quantity=5)
    # order and supply lines uses different currency, price does not apply
1074
    self.assertEqual(None, sale_order_line.getPrice())
1075

1076 1077 1078 1079
    # set the same currency
    sale_order.setPriceCurrencyValue(currency)

    # price applies
1080 1081
    self.assertEqual(1000, sale_order_line.getPrice())
    self.assertEqual(5000, sale_order_line.getTotalPrice())
1082

1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
  def testGetPriceProductLine(self):
    """Test supply line set for a product line.
    """
    # This supply line defines a price applicable for all resources member
    # of product line a
    supply = self.portal.getDefaultModule(self.sale_supply_portal_type).newContent(
                     portal_type=self.sale_supply_portal_type)
    supply_line = supply.newContent(portal_type=self.sale_supply_line_portal_type)
    supply_line.setProductLineValue(self.portal.portal_categories.product_line.a)
    supply_line.setBasePrice(1000)
    supply.validate()

    resource_a = self.portal.getDefaultModule(self.product_portal_type)\
                .newContent(portal_type=self.product_portal_type)
    resource_a.setProductLineValue(self.portal.portal_categories.product_line.a)
1098 1099 1100
    resource_a_1 = self.portal.getDefaultModule(self.product_portal_type)\
                .newContent(portal_type=self.product_portal_type)
    resource_a_1.setProductLineValue(self.portal.portal_categories.product_line.a.a1)
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
    resource_b = self.portal.getDefaultModule(self.product_portal_type)\
                .newContent(portal_type=self.product_portal_type)
    resource_b.setProductLineValue(self.portal.portal_categories.product_line.b)

    self.tic()
    sale_order_line = self.portal.getDefaultModule("Sale Order").newContent(
                              portal_type='Sale Order').newContent(
                          portal_type=self.sale_order_line_portal_type,
                          resource_value=resource_a,
                          quantity=1)
    # resource_a is member of product_line/a, so our supply line applies.
    self.assertEqual(1000, sale_order_line.getPrice())

1114 1115 1116 1117 1118 1119 1120 1121
    sale_order_line = self.portal.getDefaultModule("Sale Order").newContent(
                              portal_type='Sale Order').newContent(
                          portal_type=self.sale_order_line_portal_type,
                          resource_value=resource_a_1,
                          quantity=1)
    # resource_a_1 is member of product_line/a/a1, so our supply line applies.
    self.assertEqual(1000, sale_order_line.getPrice())

1122 1123 1124 1125 1126 1127 1128 1129 1130
    sale_order_line = self.portal.getDefaultModule("Sale Order").newContent(
                              portal_type='Sale Order').newContent(
                          portal_type=self.sale_order_line_portal_type,
                          resource_value=resource_b,
                          quantity=1)
    # resource_b is member of product_line/b, so our supply line does not apply.
    self.assertEqual(None, sale_order_line.getPrice())


1131 1132 1133 1134 1135 1136
  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
1137 1138
    self.assertEqual(1, resource.getBaseUnitQuantity())
    self.assertEqual(0, resource.getQuantityPrecision())
1139 1140
    # quantity precision is calculated using base quantity unit
    resource.setBaseUnitQuantity(0.001)
1141
    self.assertEqual(3, resource.getQuantityPrecision())
1142

1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
  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()
    )
1173

1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
  def test_sourceDestinationReferenceOnSupplyLineOnDefaultSupplyLine(self):
    '''Check that it's possible to set and get a source/destination_reference
    on default supply line
    '''
    resource = self.portal.getDefaultModule(self.product_portal_type)\
                .newContent(portal_type=self.product_portal_type)

    resource.edit(\
        purchase_supply_line_source_reference='test_source_reference_on_purchase_supply_line',
        purchase_supply_line_destination_reference='test_destination_reference_on_purchase_supply_line',
        sale_supply_line_source_reference='test_source_reference_on_sale_supply_line',
        sale_supply_line_destination_reference='test_destination_reference_on_sale_supply_line',
        internal_supply_line_source_reference='test_source_reference_on_internal_supply_line',
        internal_supply_line_destination_reference='test_destination_reference_on_internal_supply_line',
    )
1189
    self.assertEqual(resource.getPurchaseSupplyLineSourceReference(),
1190
        'test_source_reference_on_purchase_supply_line')
1191
    self.assertEqual(resource.getPurchaseSupplyLineDestinationReference(),
1192
        'test_destination_reference_on_purchase_supply_line')
1193
    self.assertEqual(resource.getSaleSupplyLineSourceReference(),
1194
        'test_source_reference_on_sale_supply_line')
1195
    self.assertEqual(resource.getSaleSupplyLineDestinationReference(),
1196
        'test_destination_reference_on_sale_supply_line')
1197
    self.assertEqual(resource.getInternalSupplyLineSourceReference(),
1198
        'test_source_reference_on_internal_supply_line')
1199
    self.assertEqual(resource.getInternalSupplyLineDestinationReference(),
1200 1201
        'test_destination_reference_on_internal_supply_line')

1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
  def testQuantityUnitOnMovement(self):
    """Make sure that changing default quantity unit on resource does not
       affect to movement.
       In this test, always use Base.edit method. Because Base.edit is
       used when real user edit document through edit form.
    """
    # Set up quantity unit categories
    # weight
    quantity_unit_category_value = self.portal.portal_categories.quantity_unit
    quantity_unit_weight = quantity_unit_category_value._getOb('weight', None)
    if quantity_unit_weight is None:
      quantity_unit_weight = quantity_unit_category_value.newContent(
        id='weight', portal_type='Category')
    quantity_unit_gram = quantity_unit_weight._getOb('gram', None)
    if quantity_unit_gram is None:
      quantity_unit_gram = quantity_unit_weight.newContent(
        portal_type='Category', id='gram')
    # volume
    quantity_unit_volume = quantity_unit_category_value._getOb('volume', None)
    if quantity_unit_volume is None:
      quantity_unit_volume = quantity_unit_category_value.newContent(
        id='volume', portal_type='Category')
    quantity_unit_liter = quantity_unit_volume._getOb('liter', None)
    if quantity_unit_liter is None:
      quantity_unit_liter = quantity_unit_volume.newContent(
        portal_type='Category', id='liter')
    self.commit()

    # Create resource
    resource_value = self.portal.getDefaultModule(
      self.product_portal_type).newContent(portal_type=self.product_portal_type)
1233 1234
    resource_value.edit(quantity_unit_value_list=[
        quantity_unit_gram, quantity_unit_liter])
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
    self.commit()
    self.assertEqual(resource_value.getDefaultQuantityUnitValue(),
                     quantity_unit_gram)

    # Create sale order line
    sale_order = self.portal.getDefaultModule('Sale Order').newContent(
      portal_type='Sale Order')
    sale_order_line = sale_order.newContent(
      portal_type=self.sale_order_line_portal_type)
    self.commit()

    # Set resource to movement
    sale_order_line.edit(resource_value=resource_value)
    self.commit()
    self.assertEqual(sale_order_line.getQuantityUnitValue(),
                     quantity_unit_gram)

    # Select different quantity unit
    sale_order_line.edit(quantity_unit_value=quantity_unit_liter)
    self.commit()
    self.assertEqual(sale_order_line.getQuantityUnitValue(),
                     quantity_unit_liter)

    # Select empty(no quantity unit)
    sale_order_line.edit(quantity_unit_value=None)
    self.commit()

    # Select default quantity unit again
    sale_order_line.edit(quantity_unit_value=quantity_unit_gram)
    self.commit()
    self.assertEqual(sale_order_line.getQuantityUnitValue(),
                     quantity_unit_gram)

    # Change default quantity unit on resource
    # Now liter is default quantity unit.
1270 1271
    resource_value.edit(quantity_unit_value_list=[
        quantity_unit_liter, quantity_unit_gram])
1272 1273 1274 1275 1276 1277 1278 1279
    self.commit()

    # Check existing movement again and make sure that quantity
    # unit is not changed.
    expectedFailure(self.assertEqual)(
      sale_order_line.getQuantityUnitValue(),
      quantity_unit_gram)

1280 1281 1282 1283
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestResource))
  return suite